SQL 光标导致无限循环
SQL cursor result in infinite loop
我正在尝试将发票项目插入到数量为负值的现有发票中。我决定为此使用游标,但是当我 运行 查询时,它会导致无限循环。
这是我的代码:
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
正在插入与游标读取相同的 table 中的值。
您必须使用 static
关键字 (declare c cursor static
) 声明游标,以防止将新插入的记录取回游标。
静态游标始终显示游标打开时的结果集。在其他情况下,当您将记录插入同一个 table 并且它们满足选择到游标中的数据条件时 - 这些新记录将被检索并且游标再次迭代。
我正在尝试将发票项目插入到数量为负值的现有发票中。我决定为此使用游标,但是当我 运行 查询时,它会导致无限循环。
这是我的代码:
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
正在插入与游标读取相同的 table 中的值。
您必须使用 static
关键字 (declare c cursor static
) 声明游标,以防止将新插入的记录取回游标。
静态游标始终显示游标打开时的结果集。在其他情况下,当您将记录插入同一个 table 并且它们满足选择到游标中的数据条件时 - 这些新记录将被检索并且游标再次迭代。