
The SET IDENTITY_INSERT statement in SQL Server allows explicit values to be inserted into the identity column of a table. This can be useful when you need to insert specific values into a column that is normally auto-incremented. Here is a brief overview of how it works:
Syntax
SET IDENTITY_INSERT [database_name].[schema_name].[table_name] { ON | OFF }
Usage
- ON: Allows explicit values to be inserted into the identity column.
- OFF: Resumes the normal auto-increment behaviour.
Example
USE [YourDB]
GO
SET IDENTITY_INSERT [dbo].[YourTable] ON
INSERT INTO [dbo].[YourTable] ([ID], [Col1], [Col2])
SELECT [ID], [Col1], [Col2]
FROM [StagingDB].[dbo].[YourTable_Copy]
GO
SET IDENTITY_INSERT [dbo].[YourTable] OFF
This command is particularly useful when migrating data or restoring databases where the original identity values must be kept.
From my SQL Server DBA handbook.