This is kind of a followup to my question Reference a column and update it in the same statement. I am now trying to use a local variable and have it updated in the same update statement.
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
You can run the query here, here is the results it gives
ID UNPAID ----------- --------------------- 1 0.00 2 0.00 3 58.00 4 41.00 LeftoverPayment --------------- 0
All of the value should of been 0 and @paymentAmmount at the end should also be 0. What is going wrong that is causing the values to not be applied correctly?
P.S. I know how to fix it, just break the one query in to the 3 following queries, but I wanted to do it as a single query so I did not need as many lookups against the real table
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
I just wanted to know why what I am doing currently does not work.
1 Answer