I have to work with an old 2005 database, where there are no foreign key constraints specified (I know).Now I'm trying to copy some data from one SQL server (production) to another (test) with the following code
declare @ServerFrom as varchar(10)declare @ServerTo as varchar(10)declare @TableName as varchar(50)declare @Fields as varchar(500)declare @SqlStatement as varchar(max)set @ServerFrom = 'ServerA';set @ServerTo = 'ServerB';set @TableName = 'MyDataBase.dbo.MyTable';set @Fields = ' Field1, Field2, Field3 'set @SqlStatement = 'delete from ' + @ServerTo + '.' + @TableNameexec(@SqlStatement);set @SqlStatement = 'set identity_insert ' + @TableName + ' on'exec(@SqlStatement);set @SqlStatement = 'insert into ' + @ServerTo + '.' + @TableName + '(' + @Fields + ') ' + 'select ' + @Fields + ' from ' + @ServerFrom + '.' + @TableNameexec(@SqlStatement);set @SqlStatement = 'set identity_insert ' + @TableName + ' off'exec(@SqlStatement);
But when I run this, I get the following message
Msg 544, Level 16, State 1, Line 1Cannot insert explicit value for identity column in table 'MyTable' when IDENTITY_INSERT is set to OFF.
Although I used the statement "set identity_insert MyTable on".What am I missing here?