T-Sql

CURSOR 中的無限循環

  • August 20, 2019

我正在嘗試在不再需要臨時表時使用游標來清理它們。我有一個小表,其中包含臨時表的名稱和標識符。游標卡在無限循環中,但前提是我在其中執行某些語句。如果我只是從 中列印出值FETCH,它就可以完美地工作。這是程式碼。

DECLARE @id bigint;
DECLARE @table_name varchar(max);

DECLARE st CURSOR LOCAL FAST_FORWARD FOR 
SELECT ID, TableName FROM SearchTables WHERE CustomerID IS NULL

OPEN st
FETCH NEXT FROM st INTO @id, @table_name
WHILE @@FETCH_STATUS <> -1 
BEGIN   
   IF(OBJECT_ID(@table_name) IS NOT NULL) 
       EXEC('DROP TABLE ' + @table_name);

   UPDATE SearchTables SET Deleted=1 WHERE ID=@id;

   PRINT CAST(@id AS varchar(max)) + ' ' + @table_name;

   FETCH NEXT FROM st INTO @id, @table_name;
END 

CLOSE st
DEALLOCATE st

如果我註釋掉這些行

   IF(OBJECT_ID(@table_name) IS NOT NULL) 
       EXEC('DROP TABLE ' + @table_name);

   UPDATE SearchTables SET Deleted=1 WHERE ID=@id;

PRINT輸出所有的 ID 和表名。如果我不評論它們,我得到的只是第一行一遍又一遍,直到我取消查詢。我也嘗試將IF線路更改為,EXEC('DROP TABLE IF EXISTS ' + @table_name)但這也不起作用。

當您設置Deleted=1並使用 FAST_FORWARD 游標再次讀取它時,您可能正在移動該行。改用 STATIC 游標,它將迭代數據的副本,並避免改變您正在遍歷的資料結構。

DECLARE st CURSOR LOCAL STATIC FOR . . .

你想要WHILE @@FETCH_STATUS = 0這意味著繼續,除非有什麼不對勁。

using<> -1意味著即使提取的行失去,它也會繼續,或者它沒有執行提取操作,使其無限,除非你得到-1作為返回值,因為有4 個返回@@FETCH_STATUS

0  The FETCH statement was successful.
-1  The FETCH statement failed or the row was beyond the result set.
-2  The row fetched is missing.
-9  The cursor is not performing a fetch operation

.

引用自:https://dba.stackexchange.com/questions/245699