Use of SET Identity_insert
SET Identity_insert [Database. [owner.] ] {table} {on | OFF}
--powerful self-added bars can be inserted into the record.
--database is the name of the data library.
--owner is all the names of the tables.
--table a unique field's table name
Examples:
--Create Products table. Create a test table
CREATE TABLE products (id int IDENTITY PRIMARY KEY, product varchar (40))
Go
--inserting values into the Products table. Insert test data into the 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
SELECT * FROM Products
--Create a gap in the identity values. To remove the data by leaving gaps
DELETE Products
WHERE Product = ' saw '
Go
SELECT *
From Products
--At this point the id=3 record does not exist and is deleted.
Go
--Attempt to insert a explicit ID value of 3;
--should return a warning. Inserting data will be wrong at this time. Be interrupted.
INSERT into the products (ID, product) VALUES (3, ' garden shovel ')
--Hint: Cannot insert explicit value for identity column in table ' products ' while IDENTITY_INSERT is set to OFF.
-When the IDENTITY_INSERT is set off, insert self-add data cannot be specified in the table products (that is, the specific self increment value).
Go
--SET identity_insert to ON.
SET Identity_insert Products on
Go
--Attempt to insert a explicit ID value of 3 will be successful
INSERT into the products (ID, product) VALUES (3, ' garden shovel ')
Go
SELECT *
From Products
Go
--Drop Products table.
SET Identity_insert Products off
DROP TABLE Products
Go