I have a table in database Foo
named Bar
, that has a column named ID
, which is the primary key, and this database is living on the development SQL Server.
I'm trying to copy data from our production server into the development server so I can play with said data, so I execute the following:
set IDENTITY_INSERT Foo.dbo.Bar ON
insert into Foo.dbo.Bar
(
ID
,Something
,Else
,Is
,Going
,Horribly
,Wrong
,With
,SQL
)
select
ID
,Something
,Else
,Is
,Going
,Horribly
,Wrong
,With
,SQL
from Production.Foo.dbo.Bar
set IDENTITY_INSERT Foo.dbo.Bar OFF
And I get the error
Msg 8107, Level 16, State 1, Line 1
IDENTITY_INSERT is already ON for table 'Foo.dbo.Bar'. Cannot perform SET operation for table 'Foo.dbo.Bar'.
Hmm..okay, so IDENTITY_INSERT is turned on for the table. So I removed the SET IDENTITY_INSERT Foo.dbo.Bar ON
from the top of my query, and then execute it, and I get this error:
Msg 544, Level 16, State 1, Line 1
Cannot insert explicit value for identity column in table 'Bar' when IDENTITY_INSERT is set to OFF.
I can execute SET IDENTITY_INSERT Foo.dbo.Bar OFF
all day long, but if I try to turn it ON
, then SQL Server 2012 says that IDENTITY_INSERT
is already turned on.
IDENTITY_INSERT
is on for a table I can continually set it to on with no error, similarly if it is off, I can set it to off, the only time I can't set it to ON is if it is there is another table in the same session. As you can see in this fiddle the first 3 batches work fine turning off and on again multiple times, it is only the 4 batch that fails. – GarethD