select top 1 id from 表 a
where not exists(select 1 from 表 where id = a.id+1)
order by id

解决方案 »

  1.   

    --求最小应该补的id(假设最小id为1,并且考虑1缺的时候补1)--测试数据
    declare @t table(id int)
    insert @t select 2
    union all select 3
    union all select 5--求缺少的最小id
    select min(id)+1
    from(
    select id=0 union all select id from @t
    )a where not exists(
    select * from @t where id=a.id+1)--结果: 1
      

  2.   

    declare @tb table(id int)
    declare @id intinsert into @tb select 1 union select 2 union select 4 union select 7
    select top 1 @id=[id]+1 from @tb where (id+1) not in (select id from @tb) order by [id]select @id
      

  3.   

    楼上的几位朋友,,我的表名是TEST,,几位高手做的东西出来的结果不是我理想的结果,也许是我搞错了,,我不熟悉SQL脚本,请再帮忙一下。。感谢感谢
      

  4.   

    select top 1 (id+1) as id1 from TEST where (id+1) not in (select id from TEST) order by id
      

  5.   

    select min(id)+1
    from (select id=0 union all select id from TEST) a 
    where not exists(
    select * from TEST where id=a.id+1)