在 SQL Server 中 如果对一个表明为 identity 的列插入指定的值,会引发一个错误。

例子如下:




  1.         create table T_Person(ID int identity ,Name nvarchar(20))

  2.         insert into T_Person(ID,Name) values(0,'0');由于我们在create 时指定了 identity         所以这个插入语句会出错。

  3.         用set identity_insert 命令来解决问题。

            set identity_insert T_Person on --允许显式插入值

            insert into T_Person(ID,Name) values(0,'0');

            set identity_insert T_Person off  --不允许显式插入值

  4. 改动表的 identity_insert 属性后要记得改回去。

  5. 当新插入的值比,原来的所有值都大时,数据库会用当前插入的值作为‘基值’ 以后插入的数据 会在这个基础上 加一(当然如果增量是一的话)