Tuesday, January 19, 2010

IDENTITY_INSERT is already ON for table [Table_Name]

I was editing  some script in SQL Server Management Studio.
And interacted with error:
IDENTITY_INSERT is already ON for table [Table_Name]

How did I come to this error?
That script looked like:

SET IDENTITY_INSERT [TABLE_NAME] ON
--insert statements
--failure on one of inserts because of not existing column
SET IDENTITY_INSERT [TABLE_NAME] ON

Failure occurred on one of inserts, because one of the columns was missed. After that I added column to fix problem, but I started getting this error: IDENTITY_INSERT is already ON for table [Table_Name].
tried to run inserts independently but still the same.

Why it happened?
IDENTITY_INSERT works in scope of one session.

How to solve?

You just need another session. I simply reconnected to the same database and run without issues. Of course I changed script to set IDENTITY_INSERT to OFF in the end.

4 comments:

  1. Thanks for this. I had a maddening problem with this of there being only one IDENTITY_INSERT statement. I could then run SET IDENTITY_INSERT table OFF followed by SET IDENTITY_INSERT table ON and it would still fail.

    Closing and re-opening the connection worked nicely.

    Ian

    ReplyDelete
  2. Genuinely very helpful tip, thanks
    - Mike

    ReplyDelete
  3. Yep, worked for me also - thanks very much!

    ReplyDelete
  4. Thanks, it is really helpful tip.

    ReplyDelete