【问题标题】:SQL Server : stuck in WHILE loop using @@fetch_statusSQL Server:使用@@fetch_status 卡在 WHILE 循环中
【发布时间】:2015-09-15 08:18:15
【问题描述】:

我尝试使用带有 @@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

【问题讨论】:

  • 您在end 之前忘记了另一个fetch next from items into @iteid;,在您的update 声明之后。
  • 非常感谢您的快速答复!这解决了我的问题!
  • 没那么快!请检查我的答案。对于这个简单的任务,您不应该使用 CURSOR
  • 好的@FelixPamittan 非常感谢!! :)

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


【解决方案1】:

您忘记在 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;

【讨论】:

    最近更新 更多