`
yiyeqinghuasoon
  • 浏览: 644190 次
文章分类
社区版块
存档分类
最新评论

逐行更新数据,满足条件后终止 --【叶子】

 
阅读更多

需求贴:

http://topic.csdn.net/u/20110423/13/f5b302f4-417d-4890-995e-65a5b5fb23ce.html?seed=1731769063&r=72947420#r_72947420

--要求说明

例如下表中有充值记录,每个人可能充值多次,当消费的时候,根据消费金额更新充值记录

例如张三充值3次,分别为17,2,12,假设其消费22元,则更新为0,0,9 就是说172的两笔钱花完了,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,发现我上面的代码并不适用于所有的情况。

现换了思路重新写了一个:





分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics