SQL游标导致无限循环

时间:2015-04-28 06:55:11

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

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

这是我的代码:

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正在光标读取的同一个表中插入值。

1 个答案:

答案 0 :(得分:3)

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

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

相关问题