SQL Server 2025 · Module 6

CLOSE Cursor in SQL Server 2025 (Remaining data)

Lesson 9

CLOSE a Cursor in SQL Server 2025

Objective: Close an open cursor while understanding what engine resources are released and what remains allocated.

Executing CLOSE employee_cursor; terminates the cursor's active result set and releases any scroll locks held on the rows over which the cursor is positioned. However, CLOSE leaves the cursor's internal data structures and its named or variable reference intact so you can reopen it later. Closing a cursor is distinct from deallocating the cursor and distinct from committing or rolling back an enclosing transaction.

Close and reopen a cursor

Because CLOSE retains the cursor definition in memory, issuing a second OPEN statement re-evaluates the defining SELECT query and builds a fresh result set. After running the Lesson 2 setup to create #Employees, execute the following as one batch:

DECLARE employee_cursor CURSOR LOCAL FAST_FORWARD FOR
    SELECT EmployeeID, EmployeeName
    FROM #Employees
    ORDER BY EmployeeID;

OPEN employee_cursor;
FETCH NEXT FROM employee_cursor; -- Returns the first row of the initial result set
CLOSE employee_cursor;           -- Releases the result set and row-position locks

-- Modify the underlying table while the cursor is closed
UPDATE #Employees
SET EmployeeName = N'Updated_' + EmployeeName
WHERE EmployeeID = 1;

OPEN employee_cursor;            -- Re-executes the defining query against current data
FETCH NEXT FROM employee_cursor; -- Returns the first row of the newly populated result set
CLOSE employee_cursor;
DEALLOCATE employee_cursor;      -- Destroys the cursor definition and frees memory
CLOSE changes an open cursor into a closed cursor that must be reopened before FETCH.
CLOSE releases the current result set and cursor positioning locks, while retaining the structures needed to reopen the cursor.

Engine resources: What CLOSE releases vs. retains

When you execute CLOSE in SQL Server 2025, the Database Engine separates active result-set resources from the cursor's structural metadata:

  • Tempdb worktables (Released): If the cursor uses a STATIC or KEYSET model—or if the query plan requires a spool or sort operator—OPEN populates an internal worktable in tempdb. Calling CLOSE drops or truncates that temporary worktable immediately, freeing tempdb space before the batch ends.
  • Scroll and positioning locks (Released): Any read or scroll locks (`SCROLL_LOCKS`) held strictly to maintain the cursor's current row position are released when the cursor closes.
  • Cursor definition and plan reference (Retained): The cursor's parsed query tree, concurrency options, and identifier (`employee_cursor` or `@cv`) remain allocated in session memory until DEALLOCATE is called or the scoping block exits.
  • Transaction locks (Retained): If you execute `UPDATE` or `DELETE` statements—including positioned updates using `WHERE CURRENT OF`—inside an explicit transaction before closing the cursor, the exclusive (`X`) locks protecting those modified rows are held until `COMMIT TRANSACTION` or `ROLLBACK TRANSACTION` executes.

What CLOSE does not do

Closing a cursor only suspends row retrieval and positioned updates; it does not complete transaction or memory lifecycle management:

  • Does not free the cursor identifier: You cannot run DECLARE employee_cursor CURSOR... again in the same scope until you run DEALLOCATE employee_cursor.
  • Does not permit row operations: Executing FETCH or UPDATE ... WHERE CURRENT OF against a closed cursor raises error 16917 ("The cursor is not open.").
  • Does not close already-closed or unallocated cursors: Calling CLOSE immediately after DECLARE (before OPEN) or calling CLOSE twice in a row also raises error 16917.

Defensive cleanup with CURSOR_STATUS

In error handling (`TRY...CATCH`) or shared cleanup blocks, you rarely know for certain whether execution failed before or after the OPEN statement. Always inspect CURSOR_STATUS before issuing CLOSE to avoid raising a secondary error:

IF CURSOR_STATUS(N'local', N'employee_cursor') >= 0
BEGIN
    CLOSE employee_cursor;
END;

The scalar function CURSOR_STATUS returns a smallint indicating the state of a named cursor (`'local'` or `'global'`) or a cursor variable (`'variable'`):

  • 1: The cursor is open and contains at least one row (or is a DYNAMIC cursor, which always returns 1 when open even if its result set has zero rows).
  • 0: The cursor is open, but its result set is empty. Because it is still open, it must be closed before reopening.
  • -1: The cursor is declared, allocated, and currently closed.
  • -2: Not applicable to named cursors; returned only for a cursor variable when the previously assigned cursor was deallocated or never assigned.
  • -3: A cursor with the specified name or variable does not exist in the requested scope.

Testing for >= 0 safely captures both non-empty (1) and empty (0) open cursors while skipping closed (-1) or nonexistent (-3) cursors.

Automatic closure on transaction end (CURSOR_CLOSE_ON_COMMIT)

By default in SQL Server 2025, the session and database option CURSOR_CLOSE_ON_COMMIT is OFF, meaning open cursors remain open across transaction boundaries. However, if SET CURSOR_CLOSE_ON_COMMIT ON is active for the session—or if a transaction rolls back an uncommitted `OPEN` statement—SQL Server automatically closes open cursors when the transaction finishes. Using `CURSOR_STATUS(...) >= 0` protects your cleanup code when transaction rollbacks close a cursor implicitly.

Separate closure from final cleanup

Use CLOSE by itself only when your routine intentionally needs to re-execute the cursor query for a subsequent pass—for example, inside a nested loop or after refreshing staging data. When the routine is completely finished with the cursor, always follow CLOSE with DEALLOCATE to release the remaining structural memory. Lesson 10 covers DEALLOCATE, multiple variable references, and complete `TRY...CATCH` cleanup patterns.


Microsoft documentation