Skip to content
Advertisement

Update records in SQL by looking up in different table

I am copying data from few tables in SQL server A to B. I have a set of staging tables in B and need to update some of those staging tables based on updated values in final target table in B.

Example:

Server B:

StagingTable1:

StagingTable2:

After Copying StagingTable1 to TargetTable1 (ID’s get auto polulated and I get new ID’s, now ID 1 becomes 2 and ID 2 becomes 3)

TargetTable1:

So now before I can copy the StagingTable2 I need to update the Table1ID column in it by correct values from TargetTable1.

StagingTable2 should become:

I am writing a stored procedure for this and not sure how do I lookup and update the records in staging tables?

Advertisement

Answer

Assuming that (name, city) tuples are unique in StagingTable1 and TargetTable1, you can use an updatable common table expression to generate the new mapping and assign the corresponding values:

Demo on DB Fiddle – content of StagingTable2 after the update:

id | age | Table1ID
-: | --: | -------:
10 |  15 |        2
20 |  16 |        3
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement