假设有一列值类型为int,即值均为整数,有n行,n行里的数值并不是连续的,例:1,3,9,12,15,25......这样,我希望从1开始向大数遍历,找到最小的那个该列里不存在的值,如何实现?在数据库外部用逻辑编程的方法要频繁连接数据库,当表行数很多的时候,相当耗费时间.能否在数据库内部完成,最好是一条语句完成

解决方案 »

  1.   

    create table Mytable
    (
     id int,
     Re varchar(50)
    )insert into Mytable values (1,newid())
    insert into Mytable values (3,newid())
    insert into Mytable values (4,newid())
    insert into Mytable values (5,newid())
    insert into Mytable values (7,newid())select min(id)+1 as 第一个不连续的ID from mytable 
    where id not in
    (select A.id from Mytable A inner join Mytable B
    on A.id=B.id-1)第一个不连续的ID
    2
      

  2.   

    select MIN(rowid) minid
    from (
    select ROW_NUMBER() over(order by id) as rowid,id
    from tb)  as a 
    where rowid<>id
      

  3.   

    不是回答过了么:
    select top 1 rn from(select row_number()over(order by num1)rn from tb)a
    where not exists(select 1 from tb where num1=a.rn)
    OR
    select min(number) from master..spt_values a 
    where type='p' and number>0 and not exists(select 1 from tb where num1=a.number)
      

  4.   

    2005:
    create table tb(num1 int)
    insert into tb select 3 union all select 6 union all select 9
    go
    select min(number) from master..spt_values a 
    where type='p' and number>0 and not exists(select 1 from tb where num1=a.number)
    /*
    -----------
    1(1 行受影响)
    */
    go
    insert into tb select 1
    select min(number) from master..spt_values a 
    where type='p' and number>0 and not exists(select 1 from tb where num1=a.number)
    /*
    -----------
    2(1 行受影响)
    */
    go
      

  5.   

    你没明白我的意思,我给ID规定的最小值是1,也就是所,如果表中的ID不是从1开始的,那么应该返回1,我主要是为避免ID不能重复利用的问题,否则只要删掉最小的ID,那么ID值也是无法重用
      

  6.   

    每条命令我都测试过,目前看就4楼那位朋友提供的方法貌似还没出bug
      

  7.   

    create table #A(id int)
    insert into #A
    select 1 union 
    select 2 union 
    select 4 union 
    select 10
    --测试
    select MIN(rowid) minid
     from (
     select ROW_NUMBER() over(order by id) as rowid,id
     from #A)  as a 
     where rowid<>id
    --不清楚 你怎么测试的 ,怎么就 返回2???
      

  8.   

    因为 你id列不是int 类型。