开发者

T-sql Cursor, what will happen in case of error?

What will happen if an error occurs during:

  1. Declaring a cursor
  2. Fetching data

What will happen if the error occurs before the cursor is closed? Does it close automatically?

When I use a cursor, wha开发者_StackOverflowt is the best practice for handling errors?


Updated with a better solution

The [CURSOR_STATUS][1] function can be used to check the state of a cursor.

In SQL 2005 and later, this can be wrapped in a TRY...CATCH block.
Something like

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


When an error occurs after declaring the cursor and the batch terminates, the cursor will remain open. The cursor will be closed after the connection is closed.

If you can capture the error, it is good practice to close the cursor as part of the error handling.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜