这是对我的问题Reference a column 并在同一语句中更新它的一种跟进。我现在正在尝试使用局部变量并在同一个更新语句中对其进行更新。
declare @tmp table (ID int primary key, UNPAID money)
insert into @tmp select 1, 31.63
insert into @tmp select 2, 49.20
insert into @tmp select 3, 99.00
insert into @tmp select 4, 41.00
declare @paymentAmmount money
select @paymentAmmount = SUM(UNPAID) from @tmp
declare cur_oustandingAR cursor local static for select ID from @tmp order by ID
open cur_oustandingAR
declare @currentID int
fetch next from cur_oustandingAR into @currentID
while (@@fetch_status = 0 and @paymentAmmount > 0)
begin
begin
update @tmp
set UNPAID = case when @paymentAmmount > UNPAID then 0 else UNPAID - @paymentAmmount end,
@paymentAmmount = case when @paymentAmmount > UNPAID then @paymentAmmount - UNPAID else 0 end
where ID = @currentID
end
fetch next from cur_oustandingAR into @currentID
end
select * from @tmp
select @paymentAmmount as LeftoverPayment
您可以在此处运行查询,这是它给出的结果
身份证未付 ------------ --------- 1 0.00 2 0.00 3 58.00 4 41.00 剩余付款 --------------- 0
所有的值都应该是 0,@paymentAmmount
最后也应该是 0。出了什么问题导致无法正确应用这些值?
PS 我知道如何修复它,只需将一个查询分解为以下 3 个查询,但我想将其作为单个查询进行,因此我不需要针对真实表进行尽可能多的查找
select @oldUnpaid = UNPAID from @tmp where ID = @currentID
update @tmp
set UNPAID = case when @paymentAmmount > UNPAID then 0 else UNPAID - @paymentAmmount end
where ID = @currentID
select @paymentAmmount = case when @paymentAmmount > @oldUnpaid then @paymentAmmount - @oldUnpaid else 0 end
我只是想知道为什么我目前正在做的事情不起作用。