FOR UPDATE游标的基本语法

时间:2010-12-21 23:09:30

标签: sql-server-2005 cursor

好吧,我当然熟悉使用只读光标浏览表格,但我似乎无法找到正确更新当前行的正确语法(两者都不是{ {3}}并且在线图书中的cursor page似乎也显示了这个简单的操作):

DECLARE @counter int;
SET @counter = 1;
DECLARE myCursor CURSOR FOR
        SELECT RowID, Value FROM myTable
        FOR UPDATE OF Value;
OPEN myCursor;
WHILE @counter < 100
    FETCH NEXT FROM myCursor
    UPDATE myCursor SET Value = @Counter << DOESN'T WORK 
    SET @counter = @counter + 1
END
CLOSE myCursor
DEALLOCATE myCursor

我还尝试了SET Value = @Counter并在FETCH上使用INTO @Value,但似乎无法使其工作。

这显然过于简化,有一些更有效的方法可以“计算”一列。我不会厌倦你的实际计算。

是的,我确实需要一个游标而不是整个表上的UPDATE(每个连续行的值将基于一个取决于已经写入的前一行的计算)。

最初在SQL 2005上进行测试,但我还需要将代码移植到SQL 2000和2008。谢谢!

1 个答案:

答案 0 :(得分:2)

您想使用WHERE CURRENT OF -

DECLARE complex_cursor CURSOR FOR
    SELECT a.BusinessEntityID
    FROM HumanResources.EmployeePayHistory AS a
    WHERE RateChangeDate <> 
         (SELECT MAX(RateChangeDate)
          FROM HumanResources.EmployeePayHistory AS b
          WHERE a.BusinessEntityID = b.BusinessEntityID) ;
OPEN complex_cursor;
FETCH FROM complex_cursor;
UPDATE HumanResources.EmployeePayHistory
SET PayFrequency = 2 
WHERE CURRENT OF complex_cursor;
CLOSE complex_cursor;
DEALLOCATE complex_cursor;
GO

来自MSDN