Monday 15 September 2014

Updating Identity Column in SQL Server.

If you want to update the value of identity column of existing records then you need to set

set identity_insert YourTable ON
 
 
 
Example
-- Set Identity insert on so that value can be inserted into this column
SET IDENTITY_INSERT YourTable ON
GO
-- Insert the record which you want to update with new value in identity column
INSERT INTO YourTable(IdentityCol, otherCol) VALUES(13,'myValue')
GO
-- Delete the old row of which you have inserted a copy (above) (make sure about FK's)
DELETE FROM YourTable WHERE ID=3
GO
--Now set the idenetity_insert OFF to back to prevoius track
SET IDENTITY_INSERT YourTable OFF