Introduction to the usage of IDENTITY_INSERT
IDENTITY_INSERT is an option in SQL Server that allows inserting specific identity column values into a table when inserting data.
In SQL Server, an identity column refers to a column with automatically incrementing numeric values that are generated by the database. When inserting data, if a table has an identity column, by default, the value for that column is automatically generated and cannot be manually specified.
However, in certain situations, we may want to manually specify the values of the identity column instead of having them generated by the database. This is where the use of IDENTITY_INSERT comes in.
Here is how you can use IDENTITY_INSERT:
- First, use the ALTER TABLE statement to enable identity column insertion. For example, if we have a table called “myTable” with an identity column named “ID”, you can execute the following statement:
 - Enable the identity insert for the table myTable.
 - Please note that only users with ALTER TABLE permissions can perform this operation.
 - After enabling the identity column insertion, you can execute an insert statement and manually specify the value of the identity column. For example:
 - Add a record to myTable with an ID of 1 and a name of ‘John’.
 - In this example, we manually specified the value of the ID column as 1.
 - After the insertion is complete, if you no longer need to manually specify the value of the identity column, you should use the following statement to disable identity column insertion:
 - Disable the identity insert on the table “myTable”
 - Only users with ALTER TABLE permission are able to perform this operation.
 
When using IDENTITY_INSERT, it is important to keep in mind the following points:
- Each table can only have one identity column that allows insertion.
 - After enabling the identity column for insertion, the inserted values must be unique, otherwise it will cause an error.
 - If no value is specified after enabling the identity column insertion, the automatically generated identity column value will be used.
 - During the insertion of an identity column, the current value of the identity column cannot be changed.
 - The scope of enabling identity column inserts is limited to the current session and will reset to the default value OFF when the session ends.
 
In summary, IDENTITY_INSERT is an option in SQL Server that allows you to manually specify the value of an identity column when inserting data. Enable identity column insertion using the ALTER TABLE statement, then you can execute the insert statement and manually specify the value of the identity column. After the insertion is complete, you should disable identity column insertion.