I have 2 SQL tables with the same structure. One is an updated version of the second. How can I merge the 2 so that the newer table's records take precedence over the other, and records that do not have updates in the newer table are still included?
Original Table ID (is primary key):
ID, NAME, ADDRESS
11 AL 1 main street
22 BOB 2 main street
33 CHAZ 3 main street
Updated Table
ID, NAME, ADDRESS
11 AL 99 maple street
22 BOB 2 main street
Result I want
ID, NAME, ADDRESS
11 AL 99 maple street
22 BOB 2 main street
33 CHAZ 3 main street
thanks, MC
coalesce
will return the first non-null value. Combined with a left join
this will first use the new data and if null the old one.
select coalesce(u.id, o.id) as id,
coalesce(u.name, o.name) as name,
coalesce(u.address, o.address) as address
from original_table o
left join updated_table u on u.id = o.id
UPDATE o
SET Name=u.Name
,Address=u.Address
from [original] o
inner join [updated] u on u.id = o.id
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With