“IDENTITY_INSERT is already ON for table X” When Applied to Multiple Tables

Today, I needed to insert data into multiple tables in SQL Server and write to the tables’ identity columns. My SQL script looked like this:

SET IDENTITY_INSERT Table1 ON
SET IDENTITY_INSERT Table2 ON
SET IDENTITY_INSERT Table3 ON

-- insert statements go here

SET IDENTITY_INSERT Table1 OFF
SET IDENTITY_INSERT Table2 OFF
SET IDENTITY_INSERT Table3 OFF

The first time I ran the script, I got the following error at line 2: IDENTITY_INSERT is already ON for table ‘Table1’. Cannot perform SET operation for table ‘Table2’. What’s wrong?

The answer is simple: “At any time, only one table in a session can have the IDENTITY_INSERT property set to ON.” So the fix was easy:

SET IDENTITY_INSERT Table1 ON
-- insert statements for table1
SET IDENTITY_INSERT Table1 OFF

SET IDENTITY_INSERT Table2 ON
-- insert statements for table2
SET IDENTITY_INSERT Table2 OFF

SET IDENTITY_INSERT Table3 ON
-- insert statements for table3
SET IDENTITY_INSERT Table3 OFF

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s