我想迭代地更新每一行,当更新行时,它应该使用以前的最新更新值,但是要使用CTE方法来避免出现游标
游标的伪代码;光标{
-光标在第1行时更新@tableset Balance = dbo.somefunction(行<1即0之前的余额总和)
-光标在第2行时更新@tableset Balance = dbo.somefunction(第2行之前的余额总和,即950)。。。
};
声明@table表(id int,col int,col2 int,balance int);
插入到@table中值(1,200,50,0),(2,60,150,0),(3,250,3,0),(4,65,2,0);
最终结果看起来像这样1200 50 9502 60 150 13 250 3 34 65 2 50
您可以使用row_number函数来标识先前的行并对其求和。
with cte as (
select *, row_number() over (order by id) as row
from table
)
select *,
(select sum(cte2.balance)
from cte as cte2
where cte2.row < cte1.row)
from cte as cte1