T-sql Cursor, what happens if an error occurs?

What happens if an error occurs during execution:

  • Cursor declaration
  • Data retrieval

What happens if an error occurs before the cursor closes? Does it automatically close?

When I use the cursor, what is best for error handling?

+5
source share
2 answers

If an error occurs after the cursor is declared and the batch is completed, the cursor remains open. The cursor will close after closing the connection.

If you can fix the error, it is recommended that you close the cursor as part of the error handling.

+1
source

Updated with better solution.

[CURSOR_STATUS][1] .

SQL 2005 TRY...CATCH.
-

BEGIN TRY

    DECLARE <cursorName>... CURSOR FOR
    ...cursor statement, fetch block, close & deallocate

END TRY
BEGIN CATCH

    IF (CURSOR_STATUS('global', '<cursorName>') > -2)
    DEALLOCATE dbCursor

    ...other error handling

END CATCH
+2

All Articles