我想将DriverID
表的Driver
列设置为5000,5001,....
为此,我写了这个脚本:
use WeighbridgeDB
GO
DECLARE @NewDriverID int;
SET @NewDriverID = 5000;
DECLARE Driver_Cursor CURSOR FOR
SELECT DriverID FROM Driver
FOR UPDATE;
OPEN Driver_Cursor;
FETCH NEXT FROM Driver_Cursor
WHILE @@FETCH_STATUS = 0
BEGIN
UPDATE Driver SET DriverID = @NewDriverID WHERE CURRENT OF Driver_Cursor;
SET @NewDriverID += 1;
FETCH NEXT FROM Driver_Cursor
END
CLOSE Driver_Cursor;
DEALLOCATE Driver_Cursor;
GO
但是While循环不会停止,@@FETCH_STATUS
的值始终为0.我认为Cursor重建自己,因为更新发生在表或其他东西上。
如何纠正这种情况?
感谢。
答案 0 :(得分:4)
无论如何你都不需要游标(一般来说,尝试并在TSQL中避免这些,除非极少数情况)
WITH T AS
(
SELECT *,
ROW_NUMBER() OVER (ORDER BY DriverID) + 4999 AS NewDriverID
FROM Driver
)
UPDATE T SET DriverID = NewDriverID
答案 1 :(得分:0)
你可以这样做:
UPDATE Driver
SET
Driver.DriverID = d.NewDriverID
FROM
(
select
ROW_NUMBER() Over (ORDER BY DriverID) + 5000 AS NewDriverID,
Driver.DriverID
from Driver
) AS d
WHERE Driver.DriverID = p.DriverID
几乎没有理由使用光标。