允許將顯式值插入表的標(biāo)識(shí)列中。
SET IDENTITY_INSERT [ database.[ owner.] ] { table } { ON | OFF }
database
是指定的表所駐留的數(shù)據(jù)庫名稱。
owner
是表所有者的名稱。
table
是含有標(biāo)識(shí)列的表名。
任何時(shí)候,會(huì)話中只有一個(gè)表的 IDENTITY_INSERT 屬性可以設(shè)置為 ON。如果某個(gè)表已將此屬性設(shè)置為 ON,并且為另一個(gè)表發(fā)出了 SET IDENTITY_INSERT ON 語句,則 Microsoft® SQL Server™ 返回一個(gè)錯(cuò)誤信息,指出 SET IDENTITY_INSERT 已設(shè)置為 ON 并報(bào)告此屬性已設(shè)置為 ON 的表。
如果插入值大于表的當(dāng)前標(biāo)識(shí)值,則 SQL Server 自動(dòng)將新插入值作為當(dāng)前標(biāo)識(shí)值使用。
SET IDENTITY_INSERT 的設(shè)置是在執(zhí)行或運(yùn)行時(shí)設(shè)置,而不是在分析時(shí)設(shè)置。
執(zhí)行權(quán)限默認(rèn)授予 sysadmin 固定服務(wù)器角色和 db_owner 及 db_ddladmin 固定數(shù)據(jù)庫角色以及對象所有者。
下例創(chuàng)建一個(gè)含有標(biāo)識(shí)列的表,并顯示如何使用 SET IDENTITY_INSERT 設(shè)置填充由 DELETE 語句導(dǎo)致的標(biāo)識(shí)值中的空隙。
-- Create products table.
CREATE TABLE products (id int IDENTITY PRIMARY KEY, product varchar(40))
GO
-- Inserting values into products table.
INSERT INTO products (product) VALUES ('screwdriver')
INSERT INTO products (product) VALUES ('hammer')
INSERT INTO products (product) VALUES ('saw')
INSERT INTO products (product) VALUES ('shovel')
GO
-- Create a gap in the identity values.
DELETE products
WHERE product = 'saw'
GO
SELECT *
FROM products
GO
-- Attempt to insert an explicit ID value of 3;
-- should return a warning.
INSERT INTO products (id, product) VALUES(3, 'garden shovel')
GO
-- SET IDENTITY_INSERT to ON.
SET IDENTITY_INSERT products ON
GO
-- Attempt to insert an explicit ID value of 3
INSERT INTO products (id, product) VALUES(3, 'garden shovel').
GO
SELECT *
FROM products
GO
-- Drop products table.
DROP TABLE products
GO
相關(guān)文章