Wednesday 15 May 2013

SQL Server Copy Data With New Primary Key Without Removing Old Data -


Here's an example of what I'm trying to do:

I have a Name Table:

  ID (PK) | Foreign Kayid (FK) | Data 1 Data2  

Then say I have data such as

  1 4 John 12 2 4 Josh 13 3 4 Kelly 15  

Is there a way that I can copy this data to a single table, by changing only the primary and foreign keys?

Example:

  4 99 John 12 5 99 Josh 13 6 99 Kelly 15  

I already had a new parent (With ID 99) in my table, I have defined the primary key for auto increment, so I do not care what will be my primary key value. Now, I want to move all the rows where the foreign key ID = 4 and copy that data to that name table, where the foreign key ID = 99. I do not want to move the data. Data with foreign key = 4 should still be there. How do I do this? Any help would be greatly appreciated.

You need a INSERT SELECT statement:

< Select the name of the pre-> name (foreign cad, data1, data2) 99, data1, data from 2 where foreign key = 4

No comments:

Post a Comment