Skip to content

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:

-- Example of a cursor without proper deallocation
DECLARE cursor_name CURSOR FOR
SELECT column1 FROM TableName;
OPEN cursor_name;
FETCH NEXT FROM cursor_name INTO @variable;
-- Accidentally omitted DEALLOCATE
CLOSE 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:

1.Declare the cursor using DECLARE and provide a cursor name.

2.Open the cursor with the OPEN statement to begin processing the result set.

3.Perform operations such as fetching rows using the cursor. Use FETCH to retrieve rows one at a time.

4.Once done processing, close the cursor with the CLOSE statement to release the current result set.

5.Finally, deallocate the cursor using the DEALLOCATE statement to free the resources allocated for this cursor.

For example:

DECLARE cursor_name CURSOR FOR
SELECT column1 FROM TableName;
OPEN cursor_name;
FETCH NEXT FROM cursor_name INTO @variable;
-- Proper cursor closure and deallocation
CLOSE cursor_name;
DEALLOCATE 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.

2 minutes per issue.

Performance Rules, Bugs

There is no additional info for this rule.

DECLARE objects_cursor CURSOR FOR
SELECT object_id, name
FROM sys.objects where type = 'U'
OPEN objects_cursor
CLOSE objects_cursor
-- DEALLOCATE objects_cursor
  Message Line Column
1 SA0025 : Local cursor ‘objects_cursor’ not explicitly deallocated. 1 8

Analysis Rules