2015-09-15 65 views
0

我试图用while循环更新mtrl表,但使用@@fetch_status,但它看起来发生了某些事情,并且存在无限循环。SQL Server:停留在WHILE循环中使用@@ fetch_status

当我在SQL Server中运行以下代码时,它会卡住。

任何想法是什么问题?

USE [TEST_DB] 
GO 

SET ANSI_NULLS ON 
SET QUOTED_IDENTIFIER ON 
GO 

BEGIN 
    declare @iteid int; 

    SET NOCOUNT ON; 
    Declare items cursor for 
     select mtrl 
     from mtrl 
     where sodtype = 51 and company = 1 and socurrency = 1; 

    open items; 

    fetch next from items into @iteid; 

    while @@fetch_status = 0 
    begin 
     update mtrl 
     set pricer = 2 
     where mtrl = @iteid; 
    end 

    close items; 
    deallocate items; 
END 
GO 
+2

在'update'语句之后,您忘记了另一个'从项目中获取下一个'@iteid;''end''之前。 –

+0

非常感谢你的快速回答!这解决了我的问题! – user2242558

+1

不是那么快!请检查我的答案。你不应该为这个简单的任务使用'CURSOR'。 –

回答

5

你忘了添加WHILE环路内的另一个FETCH声明:

open items; 
fetch next from items into @iteid; 

while @@fetch_status=0 
begin 
    update mtrl 
    set pricer=2 
    where mtrl = @iteid; 

    fetch next from items into @iteid; 
end 

然而,看到你的查询,你不应该使用CURSOR这个简单的任务:

update mtrl 
    set pricer = 2 
where 
    sodtype = 51 
    and company = 1 
    and socurrency = 1;