Use of CURSOR to update field with row number
Suppose you want to update a field in a database table based on row number, and you want to start with 20000.
The following code will update a table, so it looks like this:
ClientIncId AccountingClientID
——————————————
50 20000
51 20001
52 20002
DECLARE @ClientIncID AS INT
DECLARE @AccountingClientId AS INT
SET @AccountingClientId = 20000
DECLARE table_cursor CURSOR FOR
SELECT c.clientIncId FROM Clients c
OPEN table_cursor
FETCH NEXT FROM table_cursor INTO @ClientIncID
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @AccountingClientId
UPDATE clients SET accountingClientId = @AccountingClientId
WHERE clientIncId = @ClientIncID
SET @AccountingClientId = @AccountingClientId + 1
FETCH NEXT FROM table_cursor INTO @ClientIncID
END
CLOSE table_Cursor
DEALLOCATE table_Cursor
It works.









Leave your response!
You must be logged in to post a comment.