首先在一张空表中,我要插入4行数据,那么正常情况下,标识列分别是1、2、3、4,自动生成,自动增长的。 
现在,我在插1,2时,发生了SQL语句的错误,然后,我改正了错误,正常插入所需的4组数据,此时,标识列是3、4、5、6了 
我想请问,怎么才能将其变为1、2、3、4呢? 
万分感谢

解决方案 »

  1.   

    一般情况下,没有必要追求这个标识列一定要连续
    如果要使用行号,可以在查询中处理如果一定要把它改为连续的,可以通过一个临时表来处理select id=identity(int,1,1),col2,col3,... into # from tb
    --col2,col3,...是除了标识列以外的列truncate table tbselect * into tb from #drop table #
      

  2.   

    ;with Args
    (
    select *,row_number() over (order by id) as Rownum
    from tb
    )update tb 
    set keycol = Rownum
      

  3.   

    truncate table  tablename
      

  4.   

    select col1,col2,col3.....into #tb from tb
    truncate table tb
    insert into tb  select identity(int ,1,1),* from #tb
      

  5.   

    declare @t table(id int identity ,[name] varchar(10))
    insert @t select 'A' union all
    select 'B' union all
    select 'C' union all
    select 'D'
    delete @t where id=2
    --2000
    select id=(select count(*) from @t where id<=t.id),[name] from @t t
    --2005
    select id=row_number() over(order by id),[name] from @t
    /*id          name
    ----------- ----------
    1           A
    2           C
    3           D(3 行受影响)id                   name
    -------------------- ----------
    1                    A
    2                    C
    3                    D(3 行受影响)
    */
      

  6.   

    原因:当你插入1、2的以后,@@identity的时候变成3了,当你再插入的时候@@identity不会自动变成1。可以重置标识列的值,再插入