Create table ywxx([spbm] char(10),[nsjg] numeric(18,4))
Insert ywxx 
select '0101000100',2.1 union all
select '0101000200',2.1 union all
select '0101000300',2.1 union all
select '0101000400',2.1 union all
select '0101000500',2.1
Godeclare @zje numeric(18,4)
declare @spbm char(10)
declare @nsjg numeric(18,4)
select @zje=100
select top 0 spbm,nsjg into resultB from ywxx
set nocount on
while @zje>=0
    begin
        set @spbm = null --这里变量赋个初始值
        select top 1 @spbm=spbm,@nsjg=nsjg from ywxx yw where not exists(select 1 from resultB where spbm=yw.spbm)
        if @spbm is  not null
            begin
                insert into resultB values(@spbm,@nsjg)
                select @zje=@zje-@nsjg
                print @zje
            end
        else
            begin
                print '金额不够'
                goto xx
            end
    end
xx:
drop table ywxx
select * from resultB a
drop table resultB
/*
spbm       nsjg                 
---------- -------------------- 
0101000100 2.1000
0101000200 2.1000
0101000300 2.1000
0101000400 2.1000
0101000500 2.1000
*/

解决方案 »

  1.   

    Create table ywxx([spbm] char(10),[nsjg] numeric(18,4)) 
    Insert ywxx 
    select '0101000100',2.1 union all 
    select '0101000200',2.1 union all 
    select '0101000300',2.1 union all 
    select '0101000400',2.1 union all 
    select '0101000500',2.1 
    Go declare @zje numeric(18,4) 
    declare @spbm char(10) 
    declare @nsjg numeric(18,4) 
    select @zje=100 
    select top 0 spbm,nsjg into resultB from ywxx 
    set nocount on 
    while @zje>=0 
        begin         select top 1 @spbm=spbm,@nsjg=nsjg from ywxx yw where not exists(select 1 from resultB where spbm=yw.spbm) 
            if @@rowcount > 0 -- is  not null 
                begin 
                    insert into resultB values(@spbm,@nsjg) 
                    select @zje=@zje-@nsjg 
                    print @zje 
                end 
            else 
                begin 
                    print '金额不够' 
                    goto xx 
                end     end 
    xx: 
    drop table ywxx 
    select * from resultB a 
    drop table resultB 
    97.9000
    95.8000
    93.7000
    91.6000
    89.5000
    金额不够
    spbm       nsjg
    ---------- ---------------------------------------
    0101000100 2.1000
    0101000200 2.1000
    0101000300 2.1000
    0101000400 2.1000
      

  2.   

    感谢2楼和4楼的朋友,你们的方法都能得到我想要的结果
    原来我没把select @xx=xx from xx 中如果行不存在的返回值搞明白,
    如果行存在就改写@xx的值,如果不存在,@xx是保存原来值的,我以为不存在会使@xx为null