2010-08-24 81 views

回答

2

這是標準TSQL光標中的通用循環。但儘可能避免使用遊標。他們的表現非常糟糕。

DECLARE @somevariable VARIABLE_TYPE_HERE 
DECLARE @sampleCursor CURSOR 

SET @sampleCursor = CURSOR FOR 
SELECT somefield... from bla bla bla... 

OPEN @sampleCursor 
FETCH NEXT 
FROM @sampleCursor INTO @somevariable 
WHILE @@FETCH_STATUS = 0 
BEGIN 

PRINT @somevariable 

FETCH NEXT 
FROM @sampleCursor INTO @somevariable 

END 
CLOSE @sampleCursor 
DEALLOCATE @sampleCursor 
+0

從Oracle的世界在這裏遊標是更爲常見的到來,海報probaly來使用它們。在SQL Server中避免它們是非常重要的。 – HLGEM 2010-08-24 16:39:24

0

T-SQL中沒有FOR。與WHILE一個例子:

DECLARE Employee_Cursor CURSOR FOR 
SELECT EmployeeID, Title 
FROM AdventureWorks2008R2.HumanResources.Employee 

OPEN Employee_Cursor; 

FETCH NEXT FROM Employee_Cursor; 

WHILE @@FETCH_STATUS = 0 
BEGIN 
    FETCH NEXT FROM Employee_Cursor; 
END; 

CLOSE Employee_Cursor; 

DEALLOCATE Employee_Cursor; 

欲瞭解更多信息:http://msdn.microsoft.com/en-us/library/ms178642.aspx