2017-06-15 95 views
1

交易表定義:遊標FETCH失敗。 @@ FETCH_STATUS爲-1

create table Transactions ([ID] [int] NOT NULL, [Value] [int] NOT NULL) 

讓我們插入一些記錄。

INSERT INTO Transactions Values(1,100) 
INSERT INTO Transactions Values(2,10) 

這是我如何使用光標

create table #Tmp_Transactions ([ID] [int] NOT NULL, [Value] [int] NOT NULL) 
INSERT INTO #Tmp_Transactions SELECT * FROM Transactions WHERE Value>100 
DECLARE @rowcount int 
SET @rowcount = @@rowcount 
PRINT @rowcount 
DECLARE @ID int 
DECLARE txcursor CURSOR FOR SELECT ID FROM #Tmp_Transactions 
OPEN txcursor 
FETCH NEXT FROM txcursor INTO @ID 
PRINT @@FETCH_STATUS ---//prints -1 

CLOSE txcursor 
DEALLOCATE txcursor 
drop table #Tmp_Transactions 

-----打印

(0 row(s) affected) 
0 
-1 
+0

您**還**需要用'INSERT INTO #Tmp_Transactions SELECT * FROM Transactions等'代替'SELECT * INTO'' –

+0

無效。它仍然會返回-1 – user1

+0

您在#Tmp_Transactions中有多少行?你有任何行嗎?根據[Microsoft的文檔](https://docs.microsoft.com/en-us/sql/t-sql/functions/fetch-status-transact-sql#return-value),狀態「-1」表示「」 FETCH語句失敗或行超出結果集。「' –

回答

1

打開光標之後,你必須使用FETCH..like下面

OPEN db_cursor 
FETCH NEXT FROM db_cursor INTO @name 

既然你沒有這樣做,Fetch_status無線會是-1

更新按照有關的變化:

沒有結果,由於設置爲此WHERE Value>100,所以你得到-1.When您使用> = 100,有一個結果集並且您不會看到獲取狀態-1

+0

這不是問題所在。我在我的問題中錯過了FETCH聲明。按照您的建議,即使在FETCH NEXT之後,我仍然遇到問題。我編輯了這個問題。 – user1

+0

@ user1:查看已更新 – TheGameiswar

相關問題