SQL Server 表在导入数据时,有时需要将自增长列指定数值,来保证导入前后的数据完全一致,如何实现?
SQL Server 提供了方法:
SET IDENTITY_INSERT,允许将显式值插入表的标识列中。
参考文档:SET IDENTITY_INSERT | Miscosoft Docs
语法:
SET IDENTITY_INSERT [ database_name . [ schema_name] . ] table { ON | OFF }
用法:
-- SET IDENTITY_INSERT to ON. SET IDENTITY_INSERT dbo.Tool ON GO -- Try to insert an explicit ID value of 3. INSERT INTO dbo.Tool (ID, Name) VALUES (3, 'Garden shovel') GO -- SET IDENTITY_INSERT to OFF. SET IDENTITY_INSERT dbo.Tool OFF GO
注意事项:
- INSERT INTO语句必须输入列名,否则执行时会报错“仅当使用了列列表并且 IDENTITY_INSERT 为 ON 时,才能为表‘Tool’中的标识列指定显式值”。
- 一个会话中只有一个表的 IDENTITY_INSERT 属性可以设置为 ON,在设置为ON、插入数据后,还需要设置该表 IDENTITY_INSERT为 OFF。