SA0025 : Local cursor not explicitly deallocated |
![]() |
Ensuring proper deallocation of cursors to prevent resource leaks and maintain optimal SQL Server performance.

The problem this rule addresses is the improper management of cursors in T-SQL code. Cursors that are not explicitly deallocated using the DEALLOCATE command can lead to resource constraints and reduced performance in SQL Server. This issue is significant because cursors are used to iterate over a result set row-by-row, but they can consume server resources if not properly closed and deallocated.
For example:
1-- Example of a cursor without proper deallocation 2DECLARE cursor_name CURSOR FOR 3SELECT column1 FROM TableName; 4OPEN cursor_name; 5FETCH NEXT FROM cursor_name INTO @variable; 6-- Accidentally omitted DEALLOCATE 7CLOSE cursor_name;
In this example, the cursor cursor_name is closed but not deallocated. This oversight can result in unnecessary memory usage and potential performance degradation because the resources associated with the cursor remain reserved.
-
Leaving cursors undeallocated can lead to memory bloat, impacting SQL Server’s ability to manage resources effectively.
-
Failure to deallocate cursors may result in higher CPU usage and degraded query performance.

Ensure proper cursor management by explicitly deallocating local cursors when they are no longer needed, thereby preventing resource leaks.
Follow these steps to address the issue:
-
Declare the cursor using DECLARE and provide a cursor name.
-
Open the cursor with the OPEN statement to begin processing the result set.
-
Perform operations such as fetching rows using the cursor. Use FETCH to retrieve rows one at a time.
-
Once done processing, close the cursor with the CLOSE statement to release the current result set.
-
Finally, deallocate the cursor using the DEALLOCATE statement to free the resources allocated for this cursor.
For example:
1DECLARE cursor_name CURSOR FOR 2SELECT column1 FROM TableName; 3OPEN cursor_name; 4FETCH NEXT FROM cursor_name INTO @variable; 5-- Proper cursor closure and deallocation 6CLOSE cursor_name; 7DEALLOCATE cursor_name;

The rule has a Batch scope and is applied only on the SQL script.

Rule has no parameters.

The rule does not need Analysis Context or SQL Connection.


Performance Rules, Bugs

There is no additional info for this rule.

SQL
1DECLARE objects_cursor CURSOR FOR 2SELECT object_id, name 3FROM sys.objects where type = 'U' 4 5OPEN objects_cursor 6 7CLOSE objects_cursor 8 9-- DEALLOCATE objects_cursor |

Message | Line | Column | |
---|---|---|---|
1 | SA0025 : Local cursor ‘objects_cursor’ not explicitly deallocated. | 1 | 8 |
