名為' '的游標已存在


現象

解決方法

關於游標作用域

判斷游標是否已存在

參考資料

現象:

.NET 應用程序,調用數據庫存儲過程,存儲過程中使用游標遍歷表格,格式如下:

DECLARE cursorTmp CURSOR FOR
    SELECT * FROM Student;
OPEN cursorTmp ;
FETCH NEXT FROM cursorTmp INTO @Name,@Age,@Score;
WHILE @@FETCH_STATUS = 0 
BEGIN
....
END
CLOSE C_LOC;
DEALLOCATE C_LOC;

程序調用(循環調用)一段時間之后報錯,顯示名為cursorTmp 的游標已存在。

解決方法:

聲明游標的時候修改為:

DECLARE C_LOC CURSOR LOCAL FAST_FORWARD FOR

將游標范圍定義為'LOCAL'解決這個問題;FAST_FORWARD非必須,若只遍歷不修改,可以使用這個來提高遍歷效率。

關於游標的作用域:

游標的作用域分有兩種:

  • Local:作用域為局部,只在定義它的批處理,存儲過程或觸發器中有效。
  • Global:作用域為全局,由連接執行的任何存儲過程或批處理中,都可以引用該游標

存儲過程中聲明的游標若不指定作用域則視具體數據庫的設置而定,查看當前默認是Global還是Local,可以使用下面的語句查看:

select is_local_cursor_default from sys.databases where name = '[your database name]'

返回值為0代表默認為Global,1代表為Local。

判斷游標是否已存在

可以使用下面的語句

IF (SELECT CURSOR_STATUS('global','myCursor')) >= -1
BEGIN
 DEALLOCATE myCursor
END

CURSOR_STATUS的返回值如下;

Return value Cursor name Cursor variable
1 The cursor result set has at least one row.

For insensitive and keyset cursors, the result set has at least one row.

For dynamic cursors, the result set can have zero, one, or more rows.
The cursor allocated to this variable is open.

For insensitive and keyset cursors, the result set has at least one row.

For dynamic cursors, the result set can have zero, one, or more rows.
0 The cursor result set is empty.* The cursor allocated to this variable is open, but the result set is definitely empty.*
-1 The cursor is closed. The cursor allocated to this variable is closed.
-2 Not applicable. Has one of these possibilities:

The previously called procedure did not assign a cursor to this OUTPUT variable.

The previously assigned procedure assigned a cursor to this OUTPUT variable, but the cursor was in a closed state when the procedure completed. Therefore, the cursor is deallocated, and not returned to the calling procedure.

No cursor is assigned to the declared cursor variable.
-3 A cursor with the specified name does not exist. A cursor variable with the specified name does not exist, or if one exists, no cursor is yet allocated to it.

參考資料:

CURSOR_STATUS具體使用:https://docs.microsoft.com/en-us/sql/t-sql/functions/cursor-status-transact-sql?view=sql-server-ver15

查看游標已存在: https://stackoverflow.com/questions/7430560/how-to-check-if-cursor-exists-open-status

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM