How to Check for Open Cursors
Cursors are a database object that allows programmers to loop through records in tables. A cursor stays open until the SQL Server programmer deallocates the memory on the server. Leaving cursors open in the database can hurt performance on the server. There is a special function in transact SQL that gives the programmer the ability to check for any open cursors. The programmer checks the cursor's status, and if it is returned as open, the programmer can deallocate the memory.
Instructions
-
-
1
Open the Microsoft SQL Server Management console. The icon to open the program is in the Windows Start menu in the "SQL Server" program directory.
-
2
Open a cursor. The code below creates a new cursor to test the status function.
declare my_cur cursor -
-
3
Get the status of a cursor to detect if it's open. Step 2 created the cursor, but it's not opened yet. Therefore, the return status value is "-1." The code below checks the status:
select cursor_status('global','my_cur') -
4
Open the cursor and evaluate the status again. A return value of 1 means the cursor is open. This function can be used for any cursor you've created on the database server. The following code detects an open cursor:
select cursor_status('global','my_cur')
Although the syntax is the same as Step 3, the return value is different. -
5
Deallocate and remove the cursor from database memory. Too many opened cursors reduce performance on the machine. The code below frees the database memory and closes the cursor:
deallocate my_cur
-
1