Sql Server - Insert data in one table along with the new auto-incremented inserted ids of another table

StackOverflow https://stackoverflow.com/questions/23602430

Question

I have 2 databases DB1 and DB2. I need to write query to copy data from DB2 to DB1. Both the databases have same table structure.

For Example:

CREATE TABLE DB1.Group(
GroupID [int] IDENTITY(1,1) NOT NULL,
[Company] [varchar](10) NOT NULL,
[Description] [varchar](1000) NOT NULL 
  )     

 CREATE TABLE DB1.Instance(
[InstanceID] [int] IDENTITY(1,1) NOT NULL,
[Description] [varchar](1000) NOT NULL,
[GroupID] [int] NOT NULL,
 ) 

I read the data from DB2.Group and insert it in DB1.Group :

 Insert into DB1.Group (Company,Description) 
 select Company,Description from DB2.Group

The GroupID is auto-incremented in DB1. And this I do not want to turn off as will conflict with the existing data.

Now, while inserting data into the DB1.Instance, I need to provide the new auto-incremented insert ids (GroupID) of DB1.Group table

Insert into DB1.Instance (Description,GroupID) 
select Description, GroupID from DB2.Instance

Please guide me how can I do that. Thanks.

Was it helpful?

Solution

Insert you first table with the new keys (leave the pk blank on insert) and make a (temporary) col in the DB1 table for the old key. lookup (join) your second insert on the old key column to get your new fk. When your done delete the old key column and your done.

Here is the sql:

CREATE TABLE DB1.Group(
GroupID [int] IDENTITY(1,1) NOT NULL,
[Company] [varchar](10) NOT NULL,
[Description] [varchar](1000) NOT NULL,
[old_key] [int] 
  )     

 CREATE TABLE DB1.Instance(
[InstanceID] [int] IDENTITY(1,1) NOT NULL,
[Description] [varchar](1000) NOT NULL,
[GroupID] [int] NOT NULL,
 ) 

 Insert into DB1.Group (Company,Description, old_key) 
 select Company,Description,GroupID  from DB2.Group

 Insert into DB1.Instance (Description,GroupID) 
select Description, DB1.Group.GroupID 
from DB2.Instance join DB1.Group ON DB1.Group.old_key = DB2.Instance.GroupID

ALTER TABLE DB1.Group DROP COLUMN old_key
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top