我目前正在从事一个数据迁移项目,对于与性能相关的问题,我想预定义一组身份,而不是让表生成它们。
我发现将属性添加到列中并不容易identity
,所以我想使用IDENTITY_INSERT ON
语句。
我的问题是:这会禁用对表身份表的更新(这会影响性能),还是我需要真正删除identity
列的属性?
我目前正在从事一个数据迁移项目,对于与性能相关的问题,我想预定义一组身份,而不是让表生成它们。
我发现将属性添加到列中并不容易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 具有会话范围,因此只有您的会话才能显式插入标识行。并且一次会话中只有一个表可以有 IDENTITY_INSERT ON。
那么性能呢?我实际上没有你的问题的答案,但我有一些代码应该给你一个答案。这是我在这里找到的东西的修改版本:
/* 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 来运行它,所以让我知道它是怎么回事。希望能帮助到你。
关于带有 SET IDENTITY_INSERT ON 的标识列的一些注意事项。
刚刚检查了SQL 2012,如果您打开该选项,您将无法使用内置的自动标识插入。
下面快速测试...
BEGIN TRY DROP TABLE #T END TRY BEGIN CATCH END CATCH;
CREATE TABLE #T (id int IDENTITY, Name varchar(50));
INSERT INTO #T (Name) VALUES ('Darren'); -- built in Identity format
SET IDENTITY_INSERT #T ON;
INSERT INTO #T (id, Name) VALUES (5, 'Jerry'); -- explicit format of identity
INSERT INTO #T (Name) VALUES ('Thomas'); -- TRY to use built in format
SET IDENTITY_INSERT #T OFF;
SELECT * FROM #T;
结果...
(1 row(s) affected)
(1 row(s) affected)
Msg 545, Level 16, State 1, Line 11
Explicit value must be specified for identity column in table '#T__________________________________________________________________________________________________________________000000C34998' either when IDENTITY_INSERT is set to ON or when a replication user is inserting into a NOT FOR REPLICATION identity column.
(2 row(s) affected)