1. 已有的列不能直接更改为自增列,要先删除该列:
alter table test01
drop column id
alter table test01
add id int identity(1,1)
2. 修改自增列的种子的方法
--原来的表,id为2
select * from test01;
--name id
--t11 1
--t22 2
--这里把表(test.dbo.test01)自增列(id)的种子修改为5(从6开始增长)
dbcc checkident('test.dbo.test01',RESEED,5)
--再插入一条
select @@IDENTITY --2
insert into test01 values ('t66');
select @@IDENTITY --6
select * from test01 --可以看到从6开始增长了
--name id
--t11 1
--t22 2
--t66 6
3. truncate table test.dbo.test01 的话会重置自增种子为1
4. 向自增列插入值时,直接插入会报错:
insert into test01 values (7,'t77');
--消息 8101,级别 16,状态 1,第 1 行
--仅当使用了列列表并且 IDENTITY_INSERT 为 ON 时,才能为表'test01'中的标识列指定显式值。
--下面才是正确的插入方法
set identity_insert test.dbo.test01 on
insert into test01(id,name) values (7,'t77');
select @@IDENTITY --此时自增的种子应该变为7
set identity_insert test.dbo.test01 off
select * from test.dbo.test01
--name id
--t11 1
--t22 2
--t66 6
--t77 7
--当再插入一条 values (7,'t77');时,自增的种子还是为7
set identity_insert test.dbo.test01 on
insert into test01(id,name) values (7,'t77');
select @@IDENTITY --还是为7
set identity_insert test.dbo.test01 off
select * from test.dbo.test01
--name id
--t11 1
--t22 2
--t66 6
--t77 7
--t77 7