How do you use the IDENTITY_INSERT statement to insert explicit values into an identity column?
Posted by KarenKg
Last Updated: July 16, 2024
In SQL Server, the IDENTITY_INSERT setting allows you to explicitly insert values into an identity column by temporarily allowing the insertion of values into columns that are normally auto-incrementing. Here's how you can use the IDENTITY_INSERT statement:
Steps to Use IDENTITY_INSERT
1. Enable IDENTITY_INSERT: You need to set the IDENTITY_INSERT property for the specific table to ON. This allows you to explicitly insert values into an identity column. 2. Insert values: Perform the INSERT statement including the identity column and the values you want. 3. Disable IDENTITY_INSERT: Once you're done inserting the explicit values, you should set IDENTITY_INSERT back to OFF to revert to the default behavior.
Example
Here's an example using a hypothetical table named Employees that has an EmployeeID as an identity column:
-- Step 1: Enable IDENTITY_INSERT
SET IDENTITY_INSERT Employees ON;

-- Step 2: Insert explicit values into the identity column
INSERT INTO Employees (EmployeeID, FirstName, LastName)
VALUES (1, 'John', 'Doe'),
       (2, 'Jane', 'Smith');

-- Step 3: Disable IDENTITY_INSERT
SET IDENTITY_INSERT Employees OFF;
Important Notes
- You can only have IDENTITY_INSERT set to ON for one table at a time in a session. Trying to set it to ON for another table while it is still on for the first one will result in an error. - When you insert explicit values into an identity column, the auto-increment feature will still be functioning; future inserts without specifying the identity column will continue from the highest value in the identity column. - It's good practice to turn IDENTITY_INSERT back to OFF as soon as you finish your operation to avoid unintended consequences. This statement can be very useful during data migrations, bulk inserts, or when you need to maintain specific values in a system where identity columns are utilized.