我对TSQL游标中的无限循环有一个奇怪的问题。当我没有将TOP 300添加到游标的定义select语句时,游标无限循环。以下是代码的示例:非常感谢对此问题的任何帮助。
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 :(得分: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
你想更新光标指向的当前行吗?如果是这样,就有办法做到。
桌子上有索引吗?你可以发布更新查询吗?