我目前正在進行數據遷移項目和性能相關的問題,我想預定義一組身份,而不是讓表自己生成它們。SQL:將設置IDENTITY_INSERT ON是否禁用更新表的身份表?
我發現將identity
屬性添加到列並不容易,所以我想使用IDENTITY_INSERT ON
語句。
我的問題是:這是否會禁用表的身份表更新(這是影響性能),還是我需要真正刪除列(s)的identity
屬性?
我目前正在進行數據遷移項目和性能相關的問題,我想預定義一組身份,而不是讓表自己生成它們。SQL:將設置IDENTITY_INSERT ON是否禁用更新表的身份表?
我發現將identity
屬性添加到列並不容易,所以我想使用IDENTITY_INSERT ON
語句。
我的問題是:這是否會禁用表的身份表更新(這是影響性能),還是我需要真正刪除列(s)的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。
那麼性能呢?我其實沒有回答你的問題,但我有一些應該給你答案的代碼。它的東西修改後的版本,我發現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得心應手上運行這一點,所以讓我知道如何去。希望能幫助到你。
謝謝Xcaliburp,我的遲到回覆sory! – thomaux 2011-03-18 09:19:14
@Anzeo - 我只是好奇 - 是身份價值還在遞增,而身份插入呢? – sheikhjabootie 2011-03-18 11:52:42
我還沒有測試(尚),因爲我稍微改變了我的方法,但我認爲他們不會增加,你不得不在最後重新標識標識列 – thomaux 2011-03-18 12:55:07
如果你不能改變列來擺脫身份:創建第二個表的列完全相同,但沒有標識,然後將所有現有數據插入到那個列表中,最後刪除舊列表中的數據有什麼困難?所有這些甚至可以通過一段代碼自動完成。 – Krumelur 2011-03-10 10:11:18
看來您使用的是Microsoft SQLServer。那是對的嗎? – 2011-03-10 10:12:28
@jon_darkstar,是的,這是正確的:) @Krumelur,因爲我需要爲遷移數據的身份,我只是不希望他們生成的表 – thomaux 2011-03-10 10:15:16