自动编号(1)

本文探讨了SQL Server中Identity列的多种特性及其用法,包括在一个会话中只能为一个表启用identity_insert、如何设置identity_insert为ON来直接插入ID值、避免以手动插入的小ID值作为后续递增的基础以及如何在普通列与identity列之间进行转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

--(1)当一个会话启动的时候只能有一个identity_insert #tb on,否则会报错 create table #ta ( id int identity(1,1), col1 int ) create table #tb ( id int identity(1,1), col1 int ) set identity_insert #ta off set identity_insert #tb on --(2)当设置identity_insert选项值为 ON的时候,可以插入id. create table #te ( id int identity(1,1), col1 varchar(10) ) insert into #te values ('aa') insert into #te values ('bb') select * from #te set identity_insert #te on insert into #te(id,col1) values (10,'ff') set identity_insert #te off insert into #te values ('hh') --(3)当使用identity_insert插入一个最小的id,之后在在插入新的值,不会以那个小的值进行递增的 create table #TF ( id int identity(1,1), col1 int ) insert into #TF select 1 union all select 2 union all select 3 set identity_insert #TF on insert into #TF (id,col1) select 1,10 set identity_insert #TF off insert into #TF select 4 select * from #TF --(4)identity列与普通列的相互转换 ---<1>indetity列转换为普通列 create table #tg ( id int identity(1,1), col1 int ) insert into #tg select 1 union all select 2 union all select 3 alter table #tg add col2 int update #tg set col2=id select * from #tg alter table #tg drop column id select * from #tg ---<2>将普通列转换为identity列 create table #TY ( col1 int, col2 int ) insert into #TY select 1,1 union all select 2,2 union all select 13,53 union all select 24,44 --铺助表 create table #TT ( id int identity(1,1), col1 int ) set identity_insert #TT off insert into #TT (id,col1) select col1,col2 from #TY select * from #TT insert into #TT select 46

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值