解决方案 »

  1.   

    不用游标的方法,create table 订货表
    (货号 varchar(10),客人 varchar(10),订货数 int)insert into 订货表
     select 'A001','C001',100 union all
     select 'A001','C002',50 union all
     select 'A001','C003',200create table 入库表
    (货号 varchar(10),入库 int)insert into 入库表
     select 'A001',180 union all
     select 'A002',300
    select 货号,客人,订货数,identity(int,1,1) 'rn'
     into #dh
     from 订货表select 货号,客人,订货数,
           (select sum(b.订货数) 
            from #dh b 
            where b.货号=a.货号 and b.rn<=a.rn) 'qty'
     into #dh2
     from #dh aselect a.货号,a.客人,a.订货数,
           case when b.入库>=a.qty then a.订货数
                when b.入库>(a.qty-a.订货数) then b.入库-(a.qty-a.订货数)
                else 0 end  '分配库存数'
     from #dh2 a
     inner join 入库表 b on a.货号=b.货号/*
    货号         客人         订货数         分配库存数
    ---------- ---------- ----------- -----------
    A001       C001       100         100
    A001       C002       50          50
    A001       C003       200         30(3 row(s) affected)
    */
      

  2.   

    4楼方法确实是可以实现。不过这个方法逐行做条件SUM,速度不会比游标快多少。唉,我还是老老实实用游标吧。