-- 最小未用的idselect min(id)+1 from tb a
where not exists(
    select * from tb where id=a.id+1)

解决方案 »

  1.   

    declare @t table(id int)
    insert into @t select 1
    insert into @t select 2
    insert into @t select 4
    insert into @t select 6
    insert into @t select 7select
        min(id)+1
    from
        (select id=0 from @t where not exists(select 1 from @t where id=1)
         union
         select id from @t a where exists(select 1 from @t where id>a.id) and not exists(select 1 from @t where id=a.id+1)
         union
         select max(id) from @t) a
      

  2.   

    declare @t table(id int)
    insert into @t select 1
    insert into @t select 2
    insert into @t select 4
    insert into @t select 6
    insert into @t select 7select
        min(id)+1
    from
        (select id=0 from @t where not exists(select 1 from @t where id=1)
         union
         select id from @t a where not exists(select 1 from @t where id=a.id+1)) a
      

  3.   

    declare @t table(id int)
    insert into @t select 1
    insert into @t select 2
    insert into @t select 4
    insert into @t select 6
    insert into @t select 7
    select min(id+1) from @t a where not exists(select 1 from @t where id=a.id+1)