Iterate a SQL Server Cursor and Release Its Resources
A cursor visits a query's rows one at a time. Use it when the operation really needs sequential processing, such as invoking a procedure for each item. For ordinary calculations and updates, first consider whether one set-based statement can express the result more simply.
Declare the Data and Cursor
Run this complete batch in a new query window:
DECLARE @Items TABLE (ItemId int PRIMARY KEY, Label nvarchar(30));
INSERT @Items VALUES (1, N'Import'), (2, N'Review');
DECLARE @ItemId int, @Label nvarchar(30);
DECLARE ItemCursor CURSOR LOCAL FAST_FORWARD FOR
SELECT ItemId, Label FROM @Items ORDER BY ItemId;
BEGIN TRY
OPEN ItemCursor;
FETCH NEXT FROM ItemCursor INTO @ItemId, @Label;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT CONCAT(@ItemId, N': ', @Label);
FETCH NEXT FROM ItemCursor INTO @ItemId, @Label;
END;
CLOSE ItemCursor;
DEALLOCATE ItemCursor;
END TRY
BEGIN CATCH
IF CURSOR_STATUS('local', 'ItemCursor') >= 0
CLOSE ItemCursor;
IF CURSOR_STATUS('local', 'ItemCursor') >= -1
DEALLOCATE ItemCursor;
THROW;
END CATCH;
The Messages pane prints 1: Import followed by 2: Review. The query's ORDER BY establishes the visit order. The variable list matches the selected columns in both order and compatible data types.
Understand the Lifecycle
LOCAL keeps the cursor in the local batch or procedure scope. FAST_FORWARD requests a forward-only, read-only cursor suitable for a single pass. OPEN establishes the result, and each FETCH attempts to obtain the next row.
Check @@FETCH_STATUS after every fetch, including the first one. An empty result then skips the loop naturally. The next fetch belongs inside the loop so that it advances rather than processing the same row indefinitely. That status is connection-wide, so a called routine using another cursor can change it. Keep the controlling fetch and test together.
CLOSE releases the active result and cursor locks but leaves a cursor that can be reopened. DEALLOCATE removes its reference and releases the remaining cursor structures when the last reference is gone. The catch block accounts for whether the cursor is open, closed or already unavailable, then rethrows the original failure.
Add Work Deliberately
Replace the PRINT only after deciding how each operation handles errors and transactions. Avoid one long transaction around a large cursor by default. If processing is retryable, define how already-completed items are recognized. Cursor cleanup does not by itself roll back business work performed in the loop.
Microsoft References
Author: Herman Schoenfeld