1

我对 TSQL 游标中的无限循环有一个奇怪的问题。当我没有将 TOP 300 添加到游标的定义选择语句时,游标会无限循环。以下是代码示例:非常感谢对此问题的任何帮助。

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

谢谢, 雷内格林

4

1 回答 1

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

你想更新光标指向的当前行吗?如果是这样,有办法做到这一点。

表上有索引吗?您可以发布更新查询吗?

于 2015-02-07T22:19:24.230 回答