MSSQL – Identity Insert

| |
-- 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

-- SET IDENTITY_INSERT to OFF
SET IDENTITY_INSERT products OFF
GO
-- SET IDENTITY_INSERT to ON.
SET IDENTITY_INSERT products ON
GO

-- Attempt to insert values from another table
INSERT INTO productsNEW (id, product)
SELECT (id, product) FROM products
GO

-- SET IDENTITY_INSERT to OFF
SET IDENTITY_INSERT products OFF
GO

Reference: http://technet.microsoft.com/en-us/library/aa259221(v=sql.80).aspx

Originally Posted on March 10, 2014
Last Updated on June 15, 2017
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.