As Tom points out this can be done entirely as set operations.
Let's assume a simple scenario where a 'match' requires matches on two columns Column1 and Column2, and you wish to update the values in three columns in the target table, Column3, Column4 and Column5, with the values of the same three columns in the source
table where there is a match on Column1 and Column2, but not on Column3, Column4 and Column5
You don't really need to concern yourself with whether there is a mismatch on Column3, Column4 and Column5. Simply updating all rows where there is a match on Column1 and Column2 is enough as any updated rows where there is no mismatch on Column3, Column4
and Column5 will simply be updated to their existing values. So the query would be like this:
UPDATE TargetTable INNER JOIN SourceTable
ON TargetTable.Column1 = SourceTable.Column1
AND TargetTable.Column2 = SourceTable.Column2
SET TargetTable.Column3 = SourceTable.Column3,
TargetTable.Column4 = SourceTable.Column4,
TargetTable.Column5 = SourceTable.Column5;
Can there also be new rows in the source table which are not yet in the target table, i.e. have no matches on Column1 and Column2? If so do you need to append these rows to the target table? This would need a second query:
INSERT INTO TargetTable(Column1,Column2,Column3,Column4,Column5)
SELECT Column1,Column2,Column3,Column4,Column5
FROM SourceTable
WHERE NOT EXISTS
(SELECT *
FROM TargetTable
WHERE TargetTable.Column1 = SourceTable.Column1
AND TargetTable.Column2 = SourceTable.Column2);
For efficiency you should ensure that Coumn1 and Column2 are each indexed none-uniquely.
However, this is based on a number of assumptions which may or may not be valid:
1. That Column1 and Column2 constitute a candidate key of both tables, i.e. in each the values of these columns in combination are distinct.
2. That the values which you wish to update are not in either of the columns which make up the candidate key, i.e. Column1 and Column2.
It goes without saying that before executing set operations of this nature it is imperative that the target table be securely backed up.