I am comparing two tables A and B. A and B are months (we will go with JAN and FEB).
FEB has updated data that belongs in JAN.
I need to update the data like so
UPDATE A
SET A.x = B.x, A.y = B.y, A.z = B.z
FROM JAN A, FEB B
WHERE (A.x <> B.x OR A.y <> B.y OR A.z <> B.z) AND A.PK = B.PK
Now I want the above to not take place on the Original JAN table.
Should I go about it this way? Or is there a better way?
SELECT *
INTO JAN_UPDATED
FROM JAN
UPDATE A
SET A.x = B.x, A.y = B.y, A.z = B.z
FROM JAN_UPDATED A, FEB B
WHERE (A.x <> B.x OR A.y <> B.y OR A.z <> B.z) AND A.PK = B.PK
EDIT: I want all of the original values + the updates in the new table
EDIT: Added PK
Using an outer join, you could select the data into a new table and update them along the way. Here’s how:
The left part of the join, the
JANtable, will return all theJANrows, and the right part of the join,FEB, will only return matching rows, those which are different from their counterparts inJAN. When there’s no match, the right part’s columns will be filled withNULLs. Now, when pulling values, theCOALESCE()function is used forx,y, andz: theFEBversion is tried first, and if it isNULL(meaning this is a non-matchingJANrow, the one that has no updates inFEB), then theJANparty (the unchanged value) is used instead.