【发布时间】: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