日期:2014-05-18 浏览次数:20667 次
declare mycursor cursor
for
select xh,bs,num from goal order by xh desc
open mycursor
declare @xh int,@bs char(1),@num int
fetch next from mycursor into @xh,@bs,@num
while @@fetch_status=0
begin
    declare @total int,@val int
    select @total=total from mid where bs=@bs
    if @total is not null
    begin
        if @total>=@num
            set @val=@num
        else
            set @val=@total
        update goal set num=num-@val where xh=@xh
        update mid set total=total-@val where bs=@bs
    end
    fetch next from mycursor into @xh,@bs,@num
end
close mycursor
deallocate mycursor
select * from mid
select * from goal
-------------------------------
bs   total
---- ---------------------------------------
a    0.00
b    0.00
c    0.00
(3 行受影响)
xh          bs   num
----------- ---- ---------------------------------------
1           a    0.00
2           a    0.00
3           a    0.00
6           b    3000.00
7           b    0.00
8           b    0.00
11          b    0.00
16          c    1000.00
18          c    0.00
19          d    500.00
(10 行受影响)
------解决方案--------------------
with c as
(select a.rn,a.xh,a.bs,a.num,b.total
 from 
 (select row_number() over(partition by bs order by xh desc) rn,
  xh,bs,num from goal) a
 left join mid b on a.bs=b.bs
),
d as
(select c.xh,c.bs,
case when c.total is null then c.num
when (c.total-(select isnull(sum(c2.num),0) from c c2 where c2.bs=c