表test 含有列:(int)id, (vachar)name, (int)groupid, (vachar)group.
要求:id的取值自动累加排列,groupid的取值自小到大排列,同时自动填补缺额数字(如有1,2,4,插入的数据的时候将自动填补3).

解决方案 »

  1.   


    declare cur cursor for select groupid from test order by groupid 
    declare @old int,@groupid int
    open cur
    fetch next from   cur   into   @groupid 
    set @old=@groupid
    while (@@fetch_status=0 )
    begin
     
     if @groupid > @old+1
     begin
      insert into test values('',@old+1,'')--插入
      break 
     end
    else 
      fetch next from   cur   into   @groupid 
    set @old=@groupid--保留上次的值
    end
    close cur
    deallocate cur
      

  2.   

    create table test (id int,name varchar(50),groupid int,[group] varchar(50))
    insert into test (name,groupid,[group]) values('a',1,'a')
    insert into test (name,groupid,[group]) values('b',2,'b')
    insert into test (name,groupid,[group]) values('c',5,'c')
    insert into test (name,groupid,[group]) values('d',8,'d')
    declare @groupid int
    set @groupid=1
    while (select count(*) from test where groupid>@groupid )>0
    begin
    if ((select count(*) from test where groupid=@groupid )=0)
    insert into test (name,groupid,[group]) values('',@groupid,'')--插入
    set @groupid=@groupid+1
    endselect * from test