根据入库的时间顺序来update,看下面的例子 --利用不停变化的@i,更新表值 create table t1(编号 int,姓名 varchar(4),金额 int) insert into t1 select 1,'张三',17 union all select 2,'李四',210 union all select 3,'张三',2 union all select 4,'李四',12 union all select 5,'张三',12--张三 消费 22 declare @i int;set @i=22update t1 set @i=case when @i<0 then 0 else @i-金额 end, 金额=case when @i>0 then 0 when @i=0 then 金额 else -@i end where 姓名='张三'select * from t1 /* 编号 姓名 金额 ----------- ---- ----------- 1 张三 0 2 李四 210 3 张三 0 4 李四 12 5 张三 9 */ @i=5 金额=0 @i=3 金额=0 @i=-9 金额=9
--利用不停变化的@i,更新表值
create table t1(编号 int,姓名 varchar(4),金额 int)
insert into t1
select 1,'张三',17 union all
select 2,'李四',210 union all
select 3,'张三',2 union all
select 4,'李四',12 union all
select 5,'张三',12--张三 消费 22
declare @i int;set @i=22update t1
set @i=case when @i<0 then 0 else @i-金额 end,
金额=case when @i>0 then 0 when @i=0 then 金额 else -@i end
where 姓名='张三'select * from t1
/*
编号 姓名 金额
----------- ---- -----------
1 张三 0
2 李四 210
3 张三 0
4 李四 12
5 张三 9
*/
@i=5 金额=0
@i=3 金额=0
@i=-9 金额=9