Identity_insert is set to OFF - How to turn it ON?
To insert explicit values into an identity column, turn on IDENTITY_INSERT:
Replace YourTable with your actual table's name. After executing the inserts, ensure to switch IDENTITY_INSERT off:
Note that you can only have IDENTITY_INSERT on for one table at a time per session. Also, make sure you have the correct permissions to use this statement.
Demystifying IDENTITY_INSERT
IDENTITY_INSERT gives you override ability when working with auto-incrementing primary keys. It allows you to insert explicit identity values into the identity column of a table, which can be incredibly useful during processes such as data migration or maintaining historical IDs.
Best cases for IDENTITY_INSERT usage
IDENTITY_INSERT proves valuable when:
- Migrating or restoring data with the necessity to keep the original IDs.
- Precisely inserting legacy data with specific ID values.
Sequence to success
Follow these four steps to avert errors when working with IDENTITY_INSERT:
- Wrap your insert statement with
SET IDENTITY_INSERT YourTable ON/OFF. - Avoid any
GOstatements; keep settings bundled in a single batch. - Use the correct table name within the statement.
- Always switch OFF
IDENTITY_INSERTwhen done.
Permission check & Test Run
Before you move ahead, don’t forget to:
- Inspect user permissions – it should ideally be
db_ownerordb_ddladmin. - Run a test – insert a row without activating
IDENTITY_INSERTto confirm the auto-increment behavior of the column.
Essential tips and troubleshooting
When dealing with IDENTITY_INSERT, it pays to be mindful of these practices and potential issues:
Best practices
- Bundle up! – Encapsulate the
IDENTITY_INSERTwithin a stored procedure for a smoother ride. - Check settings – Keep an eye on the settings of ANSI_NULLS and QUOTED_IDENTIFIER for error-free stored procedure execution.
- Plan it out – Use a dedicated procedure for complex data insertions with
IDENTITY_INSERT.
Tricky bits to look out for
- Patience, my friend! –
IDENTITY_INSERTworks with one table at a time. So, no juggling! - Off on vacation – Always turn
IDENTITY_INSERTOFF after you're done to avoid any unexpected behavior. - Respect the natives – Make sure the manually inserted ID values don't clash with the increment settings of your table.
It’s all about being mindful and managing your IDENTITY_INSERT use efficiently.
Practical scenarios to get you going
Here are a few practical scenarios that illustrate when and how IDENTITY_INSERT is used:
Scenario 1: Data migration express
Moving data and want to keep those IDs intact? Here's your method:
Scenario 2: Legacy system integration
Integrating old with new? Keep records arranged with preserved IDs:
Was this article helpful?