SQL:设置 IDENTITY_INSERT ON 会禁止更新表的身份表吗?

标签 sql sql-server performance identity-column

我目前正在从事一个数据迁移项目,对于与性能相关的问题,我想预定义一组身份,而不是让表生成它们。

我发现将 identity 属性添加到列中并不容易,所以我想使用 IDENTITY_INSERT ON 语句。

我的问题是:这会禁用对表的标识表的更新(这会影响性能),还是我需要真正删除列的 identity 属性?

最佳答案

数据迁移脚本很常见:

SET IDENTITY_INSERT [MyTable] ON
INSERT INTO [MyTable] ...
INSERT INTO [MyTable] ...
INSERT INTO [MyTable] ...
...
SET IDENTITY_INSERT [MyTable] OFF

启用后,该字段不会为其他插入自动递增。

IDENTITY_INSERT 具有 session 范围,因此只有您的 session 才能显式插入标识行。并且一次 session 中只有一个表可以有 IDENTITY_INSERT ON。

那么性能呢?我实际上没有你的问题的答案,但我有一些代码应该给你一个答案。这是我发现的东西的修改版本 here :

/* Create a table with an identity value */
CREATE TABLE test_table
  (
     auto_id  INT IDENTITY(1, 1),
     somedata VARCHAR(50)
  )
GO 

/* Insert 10 sample rows */
INSERT INTO test_table
SELECT 'x'
GO 10

/* Get the current identity value (10) */
SELECT Ident_current('test_table') AS IdentityValueAfterTenInserts

GO

/* Disable the identity column, insert a row, enable the identity column. */
SET identity_insert test_table ON
INSERT INTO test_table(auto_id, somedata)
SELECT 50, 'x'
SET identity_insert test_table OFF 

GO

/* Get the current identity value (50) */
SELECT Ident_current('test_table') AS IdentityValueAfterIdentityInsertWithIdentityEnabled

GO

/* Disable the identity column, insert a row, check the value, then enable the identity column. */
SET identity_insert test_table ON
INSERT INTO test_table(auto_id, somedata)
SELECT 100, 'x'

/* 
   Get the current identity value (?) 
   If the value is 50, then the identity column is only recalculated when a call is made to:
       SET identity_insert test_table OFF
   Else if the value is 100, then the identity column is recalculated constantly and your 
   performance problems remain.
*/
SELECT Ident_current('test_table') AS IdentityValueAfterIdentityInsertWithIdentityDisabled


SET identity_insert test_table OFF 

GO
/* Get the current identity value (100) */
SELECT Ident_current('test_table') AS IdentityValueAfterIdentityInsertWithIdentityEnabled

GO

DROP TABLE test_table

我没有方便的 SQL SERVER 来运行它,所以请告诉我它是怎么回事。希望对您有所帮助。

关于SQL:设置 IDENTITY_INSERT ON 会禁止更新表的身份表吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5258123/

相关文章:

python - 检测元素是否在成对的区间限制内

python - 为什么这个 C++ 代码只比 Python 快一点点?

mysql - 计算相同类型的两行之间的差异

sql - 如何让第一个员工在临近轮类时间时入场

mysql - 如何使用 SQL 查询连接表并获取绑定(bind)列的数量?

sql - 表扫描和聚集索引扫描有什么区别?

sql-server - 如何在特定数据库上执行最昂贵的 SQL 查询

mysql - MSSQL 与 MYSQL 的数据库安全问题

c# - lambda 表达式中的 SQL double 'IN' 子句

python - Numpy 根据其值对数组中的元素求和