SQL Server:使用@@ fetch_status停留在WHILE循环中

chr*_*sst 0 sql database sql-server sql-server-2008

我试图使用while循环更新mtrl表,@@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
Run Code Online (Sandbox Code Playgroud)

Fel*_*tan 5

你忘了FETCHWHILE循环中添加另一个语句:

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
Run Code Online (Sandbox Code Playgroud)

但是,看到您的查询,您不应该使用a CURSOR来完成这个简单的任务:

update mtrl
    set pricer = 2
where
    sodtype = 51
    and company = 1
    and socurrency = 1;
Run Code Online (Sandbox Code Playgroud)