SQL Server 自增列

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


 


 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值