我目前正致力于数据迁移项目和与性能相关的问题,我想预定义一组身份,而不是让表自己生成它们。
我发现将identity
属性添加到列并不容易,因此我想使用IDENTITY_INSERT ON
语句。
我的问题是:这是否会禁用对表的标识表的更新(这会影响性能),还是我需要真正删除列的identity
属性?
答案 0 :(得分:10)
数据迁移脚本通常具有以下内容:
SET IDENTITY_INSERT [MyTable] ON
INSERT INTO [MyTable] ...
INSERT INTO [MyTable] ...
INSERT INTO [MyTable] ...
...
SET IDENTITY_INSERT [MyTable] OFF
启用后,该字段不会自动增加其他插入。
IDENTITY_INSERT具有会话范围,因此只有您的会话才能显式插入标识行。并且会话中只有一个表可以一次打开IDENTITY_INSERT。
那么性能呢?我实际上没有回答你的问题,但我有一些代码可以给你一个答案。这是我发现的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,所以让我知道它是怎么回事。希望它有所帮助。
答案 1 :(得分:0)
关于带有 SET IDENTITY_INSERT ON 的 Identity 列的注意事项。
刚刚检查了 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)