1

我想将Table 的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 会重建自身,因为更新发生在表或其他东西上。

如何纠正这种情况?

谢谢。

4

2 回答 2

4

无论如何,您不需要游标(一般来说,除了极少数情况外,请尽量避免在 TSQL 中使用这些游标)

WITH T AS
(
SELECT *,
       ROW_NUMBER() OVER (ORDER BY DriverID) + 4999 AS NewDriverID
FROM Driver
)
UPDATE T SET DriverID = NewDriverID
于 2012-07-09T11:44:48.363 回答
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 

几乎没有理由使用游标。

于 2012-07-09T11:53:34.823 回答