I have a table “@table1″ and I would like recursively update on the”Amount” column from the BOTTOM to the TOP ordering by RowID. That is taking the negative values subtracting that value with value of row above, if the end result is still a negative subtract that value with the next row, replacing the previous value with 0.
DECLARE @table1 TABLE (RowID int, Amount int);
INSERT @table1 VALUES
(1,20),
(2,10),
(3,-10),
(4,10),
(5,-5),
(6,30);
Select * from @table1
RowID Amount
----------- -----------
1 20
2 10
3 -10
4 10
5 -5
6 30
Results Table
DECLARE @table1 TABLE (RowID int, Amount int);
INSERT @table1 VALUES
(1,20),
(2,0),
(3,0),
(4,5),
(5,0),
(6,30);
Select * from @table1
RowID Amount
----------- -----------
1 20
2 0
3 0
4 5
5 0
6 30
The only way I can think of implementing this (as a single query) would be to use something like a running total . This effectively ends up joining the Product table on itself in such a way that for each row in the “left” table, the “right” table contains all records that “come before it”. This way, you could keep a running total of your updated field. Unfortunately it’s quite confusing to write and performs atrociously.
Depending on your intended usage scenarios, this might be one of those rare cases where cursors are the better alternative. Writing one using cursors and table variables should be relatively trivial.