【问题标题】:SQL cursor result in infinite loopSQL游标导致无限循环
【发布时间】:2015-07-06 21:15:16
【问题描述】:

我正在尝试将发票项目插入现有发票的数量为负值。我决定为此使用游标,但是当我运行查询时,它会导致无限循环。

这是我的代码:

declare @cKey char(13);
set @cKey = '1512000000043';

-- declare cursor to get
-- all items for specific invoice
declare c cursor
for
    select
        acIdent, anQty
    from
        tHE_MoveItem where acKey = @cKey;

declare @cIdent  char (16),
        @nQty decimal(19,6),
        @nNo int,
        @cStatus varchar(2),   
        @cErrorOut varchar(1024);
open c
fetch c into @cIdent, @nQty
while (@@fetch_status=0)
begin

    -- add all items with negative qty
    -- to same invoice
    select @cIdent;
    -- invert value
    set @nQty = @nQty *-1;
    select @nQty;

    -- insert ident with negative value to invoice
    EXEC dbo.pHE_MoveItemsCreAll @cKey, @cIdent,@nQty, '', 1, @nNo OUTPUT,@cErrorOut OUTPUT,@cStatus OUTPUT;

    fetch c into @cIdent, @nQty
end

close c
deallocate c

我使用的是 SQL Server 2008 R2。

过程pHE_MoveItemsCreAll 正在将值插入到光标读取的同一表中。

【问题讨论】:

  • 从您的代码中不太清楚 - 您是否将记录插入到您正在读取的同一个表中?
  • 是的,程序正在同一个表中插入。
  • 你如何断定你的代码块进入了无限循环。可能程序执行也需要更多时间。评论该过程执行并尝试
  • @knkarthick24 因为发票上只有一个项目,并且在我强制关闭执行后它有 500 多行:)
  • 答案已由@AndyKorneyev 添加。相应地修改您的代码。

标签: sql-server tsql sql-server-2008-r2 cursor


【解决方案1】:

您必须使用 static 关键字 (declare c cursor static) 声明您的游标,以防止将新插入的记录取回游标。

静态游标始终显示打开游标时的结果集。在其他情况下,当您将记录插入到同一个表中并且它们满足选择到游标中的数据条件时 - 这些新记录将被检索并再次游标迭代。

【讨论】:

  • 谢谢!我完全忘记了静态。现在它就像一个魅力:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-27
  • 2021-05-07
  • 2012-08-24
  • 2020-11-16
相关资源
最近更新 更多