需求贴:
--要求说明
例如下表中有充值记录,每个人可能充值多次,当消费的时候,根据消费金额更新充值记录
例如张三充值3次,分别为17,2,12,假设其消费22元,则更新为0,0,9 就是说17和2的两笔钱花完了,12那笔钱还剩9元。如果消费18元,则更新为0,1,12。如果消费了13元,则变成4,2,12。
--测试数据
declare @info table (编号int,姓名varchar(4),金额int)
insert into @info
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=22
update @info
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 @info
/*
编号 姓名 金额
----------- ---- -----------
1 张三 0
2 李四 210
3 张三 0
4 李四 12
5 张三 9
*/
首先感谢Freedom0227,发现我上面的代码并不适用于所有的情况。
现换了思路重新写了一个: