-- 建表
create table t1(
b int,
i int,
o int,
e int,
d datetime default getdate()
)
-- 插入数据
insert into t1
select 100,10,20,null,'2008-07-01' union all
select null,20,30,null,'2008-07-02' union all
select null,50,20,null,'2008-07-03' union all
select null,50,20,null,'2008-07-04'
-- 存储过程
create procedure prDoSomething
as
declare @b int,
@i int,
@o int,
@e int,
@d datetime
declare cur cursor for
select b,i,o,d from t1
open cur
fetch next from cur into @b,@i,@o,@d
while(@@fetch_status = 0)
begin
update t1 set e = @b + @i - @o where d = @d
update t1 set b = @b + @i - @o where d = (select min(d) from t1 where d > @d)
fetch next from cur into @b,@i,@o,@d
end
close cur
deallocate cur
-- 执行procedure
exec prDoSomething
-- 查询
select * from t1
-- 清理
drop table t1
drop procedure prDoSomething