SA0026 : Local cursor variable not explicitly deallocated |
![]() |
Cursors should be deallocated before the end of a batch using the DEALLOCATE statement to avoiding resource leaks.

Cursors provides a mechanism to iterate through the results of a query row by row. However, if not properly managed, cursors can lead to resource leaks by consuming memory and other resources if they are not closed and deallocated appropriately. This issue is particularly relevant in SQL Server where resource efficiency is crucial for performance.
Example of a cursor not being deallocated:
1DECLARE cursor_name CURSOR FOR 2SELECT column_name FROM TableName; 3 4OPEN cursor_name; 5FETCH NEXT FROM cursor_name; 6-- More cursor logic 7-- Missing DEALLOCATE statement
When a cursor is not explicitly deallocated, the resources it consumes remain allocated, which can degrade performance and lead to inefficient use of system resources. It’s crucial to avoid such scenarios by ensuring that every opened cursor is deallocated after use.
-
Resource consumption: Open cursors that are not deallocated continue to consume memory and CPU resources.
-
Potential for performance issues: Accumulation of undeallocated cursors can lead to degraded performance and increased load on the database server.

To prevent resource leaks and ensure efficient use of system resources, explicitly deallocate the local cursor variable after it is no longer needed using the DEALLOCATE statement.
Follow these steps to address the issue:
-
Declare the cursor using the DECLARE statement.
-
Open the cursor with the OPEN statement to begin using it.
-
Use FETCH statements to retrieve data and perform required operations.
-
Close the cursor using the CLOSE statement once you have finished processing.
-
Finally, deallocate the cursor using the DEALLOCATE statement to free up system resources.
Example of correctly handling a cursor:
1DECLARE cursor_name CURSOR FOR 2SELECT column_name FROM TableName; 3OPEN cursor_name; 4FETCH NEXT FROM cursor_name; 5-- More cursor logic 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 @MyVariable CURSOR 2 3DECLARE MyCursor CURSOR FOR 4SELECT LastName FROM AdventureWorks.Person.Contact 5 6SET @MyVariable = MyCursor 7 8/* Use DECLARE @local_variable and SET */ 9DECLARE @MyVariable1 CURSOR 10 11SET @MyVariable1 = CURSOR SCROLL KEYSET FOR 12SELECT LastName FROM AdventureWorks.Person.Contact; 13DEALLOCATE MyCursor; 14 15DEALLOCATE @MyVariable1; 16 17-- Uncomment the line below in order to deallocate the cursor variable 18--DEALLOCATE @MyVariable; |

Message | Line | Column | |
---|---|---|---|
1 | SA0026 : Local cursor reference ‘@MyVariable’ not explicitly deallocated. | 1 | 8 |
