2012-11-13 83 views
1

我對TSQL遊標中的無限循環有個奇怪的問題。當我不將TOP 300添加到遊標的定義選擇語句時,遊標會無限循環。以下是代碼的示例:對此問題的任何幫助非常感謝。在SELECT語句中沒有TOP xxx的TSQL遊標無限循環

DECLARE @Done BIT 
SET @Done = 0 

DECLARE cursOut CURSOR LOCAL FAST_FORWARD 
FOR 
SELECT 
    --TOP 300 
    FirstName FirstName 
    ,LastName LastName 
    ,MiddleName MiddleName 
    ,Email Email 
    ,Address1 Address1 
    ,Address2 Address2 
    ,City City 
    ,[State] [State] 
     FROM StagedUsers 

OPEN cursOut; 

WHILE (@Done = 0) 
    BEGIN  
--Fetch next row 
    FETCH NEXT 
    FROM cursOut 
    INTO ,@v_FirstName 
     ,@v_LastName 
     ,@v_MiddleName 
     ,@v_Email 
     ,@v_Address1 
     ,@v_Address2 
     ,@v_City 
     ,@v_State 

    IF (@@FETCH_STATUS <> 0) 
    BEGIN 
     SET @Done = 1 
     BREAK 
    END 

    --if @batch = 0 
    BEGIN TRANSACTION 

    --process statements 
    --updates or insert statements 


    --Commit transaction  
    COMMIT TRANSACTION 

--End While    
    END 


--CleanUp: 
CLOSE cursOut 
DEALLOCATE cursOut 

感謝, Renegrin

+0

您是否插入了您正在選擇的同一張表中? – Alex

+0

不,我不更新或插入同一張表。 – Renegrin

+0

你的遊標定義似乎缺少一個'FROM'子句。或者我在這裏錯過了什麼? – GolfWolf

回答

0

首先,我認爲你不需要交易在這裏,我相信這是隻有一個語句執行,因此,從代碼中刪除交易。

其次,它沒有@done標誌,它很混亂(這可能不是問題)。

DECLARE @v_FirstName VARCHAR(500),@v_LastName VARCHAR(500),@v_MiddleName VARCHAR(500),@v_Email VARCHAR(500),@v_Address1 VARCHAR(500),@v_Address2 VARCHAR(500),@v_City VARCHAR(500),@v_State VARCHAR(500) 

DECLARE cursOut CURSOR FAST_FORWARD FOR 
SELECT FirstName FirstName,LastName LastName,MiddleName MiddleName,Email Email,Address1 Address1,Address2 Address2,City City,[State] [State] 
FROM StagedUsers 

OPEN cursOut; 

FETCH NEXT FROM cursOut INTO @v_FirstName,@v_LastName,@v_MiddleName,@v_Email,@v_Address1,@v_Address2,@v_City,@v_State 

declare @i int = 1 

WHILE @@FETCH_STATUS = 0 
BEGIN  
print cast(@i as varchar(10)) 

--> statement here 

FETCH NEXT FROM cursOut INTO @v_FirstName,@v_LastName,@v_MiddleName,@v_Email,@v_Address1,@v_Address2,@v_City,@v_State 

set @i = @i + 1  
END 

CLOSE cursOut 
DEALLOCATE cursOut 

是否要更新光標點的當前行?如果是這樣,有辦法做到這一點。

桌子上有沒有索引?你能發佈更新查詢嗎?