假如现在有一张表,里面有一列是[序号],由于过去的增删操作,导致序号是不连续的,如何通过SQL查询出其中少了哪些行。如表1:
序号 
001
002
005
012
013
015
如何把003、004、006、007……这些数给找出来

解决方案 »

  1.   


    declare @表1 table(a varchar(20))
    insert @表1  select '001'
    insert @表1  select '002'
    insert @表1  select '004'
    insert @表1  select '006'
    insert @表1  select '009'
    insert @表1  select '013'
    insert @表1  select '015'declare @max  int
    declare @a table(id int identity(1,1) ,a int)select @max=cast(max(a) as int) from @表1set rowcount @max
    insert @a select 0 from syscolumns
    set rowcount 0
    select right(1000+id,3) from @表1 a right join @a b on cast(a.a as int)=b.id where a.a is null
    --result
    /*------ 
    003
    005
    007
    008
    010
    011
    012
    014(所影响的行数为 8 行)*/
      

  2.   


    create table #t(id varchar(10))insert into #t values('001')
    insert into #t values('002')
    insert into #t values('005')
    insert into #t values('012')
    insert into #t values('013')
    insert into #t values('015')select top 8000  id=identity(int,1,1) into #id from sysobjects a,syscolumns bselect right('000'+convert(varchar(3),a.id),3) from #id a where id not in (select id=convert(int,id) from #t) and id <=(select id=max(id) from #t)------
    003
    004
    006
    007
    008
    009
    010
    011
    014(9 行受影响)