create table tbIdentity(ID int identity(1,1) primary key,Number int)
go
insert into tbIdentity
select 2
go
insert into tbIdentity          --插入不成功,但Identity也自动增大
 select 'BB'
Union all select 2
go
insert into tbIdentity         --插入成功,但Identity值已经变位3
select 3
go
select * from tbIdentity drop table tbIdentity

解决方案 »

  1.   

    --有几种原因都会导致这种情况--1.事务回滚(包括自动的(见1楼)和手工的)
    create table #(id int identity(0,1),a int)
    insert # select 0 union all select 1--事务回滚
    begin tran
    insert # select 1
    rollback traninsert # select 2
    select * from #
    drop table #
    GO
    /*--结果
    id          a           
    ----------- ----------- 
    0           0
    1           1
    3           2   --事务回滚一样导致id自增(所影响的行数为 3 行)
    --*/
      

  2.   

    --2.插入后再删除
    create table #(id int identity(0,1),a int)
    insert # select 0 union all select 1 union all select 2--删除插入的最后一条
    delete from # where a=2insert # select 2
    select * from #
    drop table #
    GO
    /*--结果
    id          a           
    ----------- ----------- 
    0           0
    1           1
    3           2  --删除后,id不回收(所影响的行数为 3 行)
    --*/
      

  3.   


    --3.强制设置标识值
    create table #(id int identity(0,1),a int)
    insert # select 0 union all select 1--强制设置当前标识值
    DBCC CHECKIDENT(#,RESEED,2)insert # select 2
    select * from #
    drop table #
    GO
    /*--结果id          a           
    ----------- ----------- 
    0           0
    1           1
    3           2(所影响的行数为 3 行)
    --*/
      

  4.   

    在使用自增類型的字段時要注意你在插入數據的時候一定要相符。insert into newtablename(a,b)
    select a,b from oldtablename(a,b)選擇的字段除了自增字段外一定要相符
      

  5.   

    标识列(identity)是自增的,数据库记录了当前的最大标识值,新增记录的时候,新记录的标识值被设置为记录的最大标识值+标识增量所以任何影响当前最大标识值的操作都可能导致新增记录的标识值不连续