I copied oldDatabase
as newDatabase
. Modified newDatabase
's schema.
Meanwhile, oldDatabase
's data are processing and updating.
I want to copy oldDatabase
's data to newDatabase
.
What I have done is:
- Clean the data of
newDatabase
- Generate data only script of
oldDatabase
- Run this script in
newDatabase
.
And I got a lot of error messages like:
Cannot insert explicit value for identity column in table 'MyTableName' when
IDENTITY_INSERT is set to OFF.
Invalid column name 'MyColumnName'.
Violation of PRIMARY KEY constraint 'PK_MyTableName'. Cannot insert duplicate
key in object 'dbo.MyTableName'.
Some tables and rows data are affected. But, tables with above error are not affected. How can I fix it? Is there a best way to make this stuff?
PS
I run my script using this command ,
sqlcmd -S myServerName -U userName -P passowrd -i PathOfMyScriptFile
Best Answer
You have three different types of problems from the looks of it.
You have identity columns. For a table that has an identity column you have three choices. First when you do your insert exclude the identity column. Second remove the identity property from the column in the destination table. Third use identity_insert. To use identity_insert you first turn it on for the table.
Then you do your insert. Note: you have to list all of the columns in the insert.
Not
And last but not least make sure you turn identity_insert back off again. Identity_insert can only be turned on for one table at a time for a given connection.
Here is a good walkthrough for insert into identity columns.
You said you changed the structure of 'newDatabase'. Well my guess is you removed 'MyColumnName'. Either exclude this from the insert or add the column back. You either need to make sure the structure in
newDatabase
matchesoldDatabase
or account for the differences in your inserts.Last but not least you are inserting data into
newDatabase
were the data already exists. Or at least the primary key values already exist innewDatabase.MyTableName
. My suggestion here is if there is any chance that you are doing updates as well as inserts change yourINSERT
statements toMERGE
statements. Otherwise add aWHERE NOT EXISTS
or something similar to theSELECT
statement in yourINSERT
statement to exclude any rows where the primary key already exists innewDatabase.MyTableName
.