--如果楼主不仅要求期初数,还要同时生成所有的余额的数据,就用:declare @i1 int,@i2 int,@ye int select @i2=0,@ye=余额 from 表 update 表 set @i1=@i2+isnull(借方,0)-isnull(贷方,0) ,余额=@i1,@i2=@i1 update 表 set 余额=余额+@ye-@i1
--测试--测试数据 create table #t(客户代码 char(4),客户名称 varchar(10),借方 int,贷方 int,余额 int) insert #t select '0001','aa',0 ,0 ,0 union all select '0001','aa',1000,0 ,0 union all select '0001','aa',0 ,2000,0 union all select '0001','aa',500 ,800 ,0 union all select '0001','aa',0 ,0 ,8000 go--更新处理 declare @i1 int,@i2 int,@ye int select @i2=0,@ye=余额 from #t update #t set @i1=@i2+isnull(借方,0)-isnull(贷方,0) ,余额=@i1,@i2=@i1 update #t set 余额=余额+@ye-@i1--显示处理结果 select * from #t go--删除测试 drop table #t/*--测试结果 客户代码 客户名称 借方 贷方 余额 ---- ---------- ----------- ----------- ----------- 0001 aa 0 0 9300 0001 aa 1000 0 10300 0001 aa 0 2000 8300 0001 aa 500 800 8000 0001 aa 0 0 8000(所影响的行数为 5 行) --*/
select @i2=0,@ye=余额 from 表
update 表 set @i1=@i2+isnull(借方,0)-isnull(贷方,0)
,余额=@i1,@i2=@i1
update 表 set 余额=余额+@ye-@i1
create table #t(客户代码 char(4),客户名称 varchar(10),借方 int,贷方 int,余额 int)
insert #t select '0001','aa',0 ,0 ,0
union all select '0001','aa',1000,0 ,0
union all select '0001','aa',0 ,2000,0
union all select '0001','aa',500 ,800 ,0
union all select '0001','aa',0 ,0 ,8000
go--更新处理
declare @i1 int,@i2 int,@ye int
select @i2=0,@ye=余额 from #t
update #t set @i1=@i2+isnull(借方,0)-isnull(贷方,0)
,余额=@i1,@i2=@i1
update #t set 余额=余额+@ye-@i1--显示处理结果
select * from #t
go--删除测试
drop table #t/*--测试结果
客户代码 客户名称 借方 贷方 余额
---- ---------- ----------- ----------- -----------
0001 aa 0 0 9300
0001 aa 1000 0 10300
0001 aa 0 2000 8300
0001 aa 500 800 8000
0001 aa 0 0 8000(所影响的行数为 5 行)
--*/