--供测试
create table ##T_air
([name]  varchar(20),
 [count] int,
 [Time] datetime)
insert ##T_air
select '旅行社1'   ,    '5'  ,  '04-1-1' union
select '旅行社2'   ,    '3'  ,  '04-2-1' union
select '旅行社3'   ,    '3'  ,  '04-3-1' select * from ##T_air declare cursor_add cursor for
  select count,name from ##T_air  order by time    --按时间顺序
declare 
    @Temp_count int ,    --保存当前记录的count值
    @remain int,         --保存还需要要申请的机票
    @name varchar(20)    --保存当前记录的旅行社名set @remain='10'         --申请机票的张数
open cursor_add
fetch cursor_add into @Temp_count,@name   
while @@fetch_status=0 and @remain>0 
  begin   
    if  @remain>@Temp_count
      update ##T_air set count='0' where name=@name
    else
      update ##T_air set count=@Temp_count-@remain where name=@name      set @remain=@remain-@Temp_count     
    fetch cursor_add into @Temp_count,@name
  end
close cursor_add
deallocate cursor_addinsert ##T_air select '申请的旅行社名','10',getdate()  --有足够机票,申请成功,插入申请记录select * from ##T_air --删除
truncate table ##T_air
drop table ##T_air
测试结果:名称           代售量      申请时间
--------  ------------  ----------------------
旅行社1          0      2004-01-01 00:00:00.000
旅行社2          0      2004-02-01 00:00:00.000
旅行社3          1      2004-03-01 00:00:00.000
申请的旅行社名   10    2005-02-22 14:11:39.733

解决方案 »

  1.   

    申请10个机位的记录不是插入同一表的,此表是记录代售(退票).申请时间理解为申请代售
    时间,不是申请机位时间,但也不妨。修改一下为存储过程:
    --供测试
    create table ##T_air
    ([name]  varchar(20),
     [count] int,
     [Time] datetime)
    insert ##T_air
    select '旅行社1'   ,    '5'  ,  '04-1-1' union
    select '旅行社2'   ,    '3'  ,  '04-2-1' union
    select '旅行社3'   ,    '3'  ,  '04-3-1' select * from ##T_air go
    create proc apply_air 
      @@apply_count int
    as
    beginif (select sum(count) from ##T_air)>@@apply_count  
    begindeclare cursor_add cursor for
      select count,name from ##T_air  order by time    --按时间顺序
    declare 
        @Temp_count int ,    --保存当前记录的count值
        @remain int,         --保存还需要要申请的机票
        @name varchar(20)    --保存当前记录的旅行社名set @remain=@@apply_count         --申请机票的张数
    open cursor_add
    fetch cursor_add into @Temp_count,@name   
    while @@fetch_status=0 and @remain>0 
      begin   
        if  @remain>@Temp_count
          update ##T_air set count='0' where name=@name
        else
          update ##T_air set count=@Temp_count-@remain where name=@name      set @remain=@remain-@Temp_count     
        fetch cursor_add into @Temp_count,@name
      end
    close cursor_add
    deallocate cursor_addend
    else 
      print '代售的机票数不够'
    endGOexec apply_air '10'insert ##T_air select '申请的旅行社名','10',getdate()  --有足够机票,申请成功,插入申请记录select * from ##T_air--删除存储过程
    drop proc apply_air 
    --删除表
    truncate table ##T_air
    drop table ##T_air
      

  2.   

    非常感谢楼上的
    我想问一下
    fetch cursor_add into @Temp_count,@name   是什么意思啊
      

  3.   

    取当前行的记录[select count,name from ##T_air  order by time    --按时间顺序]
    赋给自定义的变量(游标是一行一行地读表)