Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Ordered, updatable cursors and the FETCH NEXT order
Message
From
01/03/2007 16:41:12
Bob Thomsen
Fabtrol Systems, Inc
Eugene, Oregon, United States
 
 
To
All
General information
Forum:
Microsoft SQL Server
Category:
Stored procedures, Triggers, UDFs
Title:
Ordered, updatable cursors and the FETCH NEXT order
Environment versions
SQL Server:
SQL Server 2005
Miscellaneous
Thread ID:
01200120
Message ID:
01200120
Views:
60
My question is why the update of SomeTable.OrderKey within the loop can affect the order in which MyCursor records are delivered by FETCH NEXT.
Experimentation seems to show that under some circumstances, records can jump around in the FETCH NEXT order as a result of the UPDATE command and can be processed multiple times within the loop. I wouldn't have expected updates made directly to the table would make it into the cursor while the procedure was running, but apparently this is what is happening.
DECLARE @OrderKeyValue     decimal(10,4)
DECLARE @OrderKeyField     decimal(10,4)

SET @OrderKeyValue = 0.0001 

DECLARE MyCursor CURSOR LOCAL FORWARD_ONLY FOR 
SELECT OrderKey FROM SomeTable ORDER BY OrderKey
FOR UPDATE OF OrderKey

OPEN MyCursor
FETCH NEXT FROM MyCursor
WHILE @@FETCH_STATUS = 0 
BEGIN
   UPDATE SomeTable SET OrderKey = @OrderKeyValue WHERE CURRENT OF MyCursor
   SET @OrderKeyValue = @OrderKeyValue + 1
   FETCH NEXT FROM MyCursor INTO @OrderKeyField 
END

CLOSE MyCursor
DEALLOCATE MyCursor
Next
Reply
Map
View

Click here to load this message in the networking platform