T-Sql
CURSOR 中的無限循環
我正在嘗試在不再需要臨時表時使用游標來清理它們。我有一個小表,其中包含臨時表的名稱和標識符。游標卡在無限循環中,但前提是我在其中執行某些語句。如果我只是從 中列印出值
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;
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
.