数据插入数据库时自动填充空白ID
例如已经有了ID: 1,3,6,8,9
ID主键,现在为自动增长,
能否实现在插入时id=2 4,5
[解决办法]
SET IDENTITY_INSERT
允许将显式值插入表的标识列中。
语法
SET IDENTITY_INSERT [ database.[ owner.] ] { table } { ON | OFF }
参数
database
是指定的表所驻留的数据库名称。
owner
是表所有者的名称。
table
是含有标识列的表名。
注释
任何时候,会话中只有一个表的 IDENTITY_INSERT 属性可以设置为 ON。如果某个表已将此属性设置为 ON,并且为另一个表发出了 SET IDENTITY_INSERT ON 语句,则 Microsoft® SQL Server™ 返回一个错误信息,指出 SET IDENTITY_INSERT 已设置为 ON 并报告此属性已设置为 ON 的表。
如果插入值大于表的当前标识值,则 SQL Server 自动将新插入值作为当前标识值使用。
SET IDENTITY_INSERT 的设置是在执行或运行时设置,而不是在分析时设置。
权限
执行权限默认授予 sysadmin 固定服务器角色和 db_owner 及 db_ddladmin 固定数据库角色以及对象所有者。
[解决办法]
--> 测试数据:[ta]if object_id('[ta]') is not null drop table [ta]create table [ta](id int primary key)insert [ta]select 3 union allselect 5 union allselect 6 union allselect 9select * from [ta]--> 测试数据:生成连续数据表if object_id('[tb]') is not null drop table [tb]select identity(int,1,1) as id into tb from sysobjects a,sysobjects binsert into ta select min(b.id) from tb b where not exists(select 1 from ta where b.id=id)insert into ta select min(b.id) from tb b where not exists(select 1 from ta where b.id=id)select * from ta/*id-----------123569(6 行受影响)
[解决办法]