This is probably a familiar problem but i didn’t find an answer in searches. I do have a solution (shown below) that involves COALESCE on every non-key column, I’m wondering if there’s a Dynamic TSQL routine, or perhaps a different way of forumulating the query that doesn’t involve explicitly naming all the columns.
I have two tables, “targetTable” and “deltaTable”, that have a the same field names and types. Both have a unique key, “id”.
Deltatable has data that has changed for a corresponding row in targetTable. Any column where the value hasn’t changed is null. I want to update the columns in the targetTable that have non-null values in the corresponding row of the deltaTable. DetlaTable.id is guaranteed to exist in TargetTable.id, and I never want to update a field to NULL.
I’m using SQL Server 2005 (which doesn’t have the merge statement, not that I know it would help).
So if a targetTable row looks like
id | name | dob | next_appt
5 Bill 1-1-2012 | 3-3-2015
and a deltaTable row looks like
id | name | dob | next_appt
5 | NULL | NULL | 4-4-2015
I want targetTable updated to
id | name | dob | next_appt
5 Bill 1-1-2012 | 4-4-2015
What I have now that I want to improve on is:
UPDATE target
SET target.colA = COALESCE(delta.colA, target.colA),
target.colN = COALESCE(delta.colN, target.colN)
FROM delta JOIN target on delta.id = target.id
I’m not sure it’s a great idea, but if you really want to do it, you could do something like this: