SQL Server:使用@@ fetch_status

时间:2015-09-15 08:18:15

标签: sql sql-server database sql-server-2008

我尝试使用带有@@fetch_status的while循环来更新mtrl表,但它看起来发生了某些事情并且存在无限循环。

当我在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

1 个答案:

答案 0 :(得分:5)

您忘了在FETCH循环中添加另一个WHILE语句:

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;