以前经常会碰到这样的问题,当我们删除了一条自增长列为1的记录以后,再次插入的记录自增长列是2了。我们想在插入一条自增长列为1的记录是做不到的。我们可以通过设置SET IDENTITY_INSERT <table_name> ON;来取消自增长,等我们插入完数据以后在关闭这个功能。实验如下:
1 use TESTDB2 2 --step1:创建表 3 create table customers( 4 id int identity primary key not null, 5 name varchar(15) 6 ); 7 8 --step2:执行插入操作 9 insert into customers(id,name) values(1,'name1'); 10 --报错:An explicit value for the identity column in table 'customers' can only be specified when a column list is used and IDENTITY_INSERT is ON. 11 12 --step3:放开主键列的自增长 13 SET IDENTITY_INSERT customers ON; 14 15 --step4:插入两条记录,主键分别为1和3。插入成功 16 insert into customers(id,name) values(1,'name1'); 17 insert into customers(id,name) values(3,'name1'); 18 19 --step5:再次插入一个主键为2的记录。插入成功 20 insert into customers(id,name) values(2,'name1'); 21 22 --step6:插入重复主键, 23 --报错:Violation of PRIMARY KEY constraint 'PK__customer__3213E83F00551192'. Cannot insert duplicate key in object 'dbo.customers'. 24 insert into customers(id,name) values(3,'name1'); 25 26 --step7:关闭IDENTITY_INSERT 27 SET IDENTITY_INSERT customers OFF;