Sunday, March 23, 2014

Transfer data from one database to another without identities but keep the relation b/w PK and Foreign key

Try the below:



/********************************SAMPLE TARGET***************************************************************/
Use MSDNSamples
create table TableA(LevelValueId int identity(1,1) primary key, name varchar(100))

Insert into TableA(name) Select 'R1'
Insert into TableA(name) Select 'R2'

create Table TableB(ChildId int identity(100,1),name varchar(100), LevelValueID int references TableA(LevelValueId))

Insert into TableB(name,LevelValueID) Select 'Childname1',1

/********************************SAMPLE TARGET***************************************************************/


/********************************SAMPLE SOURCE***************************************************************/
Use Sample
create table TableA(LevelValueId int identity(1,1) primary key, name varchar(100))

Insert into TableA(name) Select 'C1'
Insert into TableA(name) Select 'C2'

create Table TableB(ChildId int identity(100,1),name varchar(100), LevelValueID int references TableA(LevelValueId))

Insert into TableB(name,LevelValueID) Select 'Kidname1',1

/********************************SAMPLE SOURCE***************************************************************/


USe MSDNSamples
/********************************MIGRATION INTERMEDIATE TABLE***************************************************************/
--Migration table
Create table Mg_TableA(LevelValueId int, NewValueId int)
/********************************MIGRATION INTERMEDIATE TABLE***************************************************************/



/********************************ACTUAL MIGRATION FOR MASTER TABLE***************************************************************/
MERGE INTO TableA
USING sample.dbo.TableA AS tv
ON 1 = 0
WHEN NOT MATCHED THEN
INSERT(name) Values(tv.name)
Output tv.levelValueId ,inserted.LevelValueid INTO
Mg_TableA;
/********************************ACTUAL MIGRATION FOR MASTER TABLE***************************************************************/


/********************************ACTUAL MIGRATION FOR CHILD TABLE***************************************************************/
Insert into TableB (name,LevelValueID)
Select A.name,B.NewValueId From sample.dbo.TableB A
Inner join Mg_TableA B on A.LevelValueID = B.LevelValueId
/********************************ACTUAL MIGRATION FOR CHILD TABLE***************************************************************/


/********************************TEST THE VALUES***************************************************************/
Select * From TableA
Select * From Mg_TableA
Select * From TableB
/********************************TEST THE VALUES***************************************************************/

Drop table TableB,Tablea,Mg_TableA

Use Sample

Drop Table TableB,Tablea


No comments:

Post a Comment