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

需求贴:

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,发现我上面的代码并不适用于所有的情况。

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

declare @infomation table (编号 int,姓名 varchar(4),金额 int)  
insert into @infomation  
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=19
declare @j int;declare @k int
;with maco as
( select * from @infomation where 姓名='张三'),maco1 as(
select *,总金额=(select sum(金额) from maco where 编号<=a.编号) from maco a)

select top 1 @j=编号,@k=总金额-@i from maco1 where 总金额>=@i
update @infomation set 金额=@k where 编号=@j
update @infomation set 金额=0 where 姓名='张三' and 编号<@j

select * from @infomation
/*
编号          姓名   金额
----------- ---- -----------
1           张三   0
2           李四   210
3           张三   0
4           李四   12
5           张三   12
*/




  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值