I've got a database with 2 tables. Let call them table and tableWithUpdatedValues
The table structure is the same, they have only few columns: title, plot and review. table has also a column updated.
The value both can assume are NULL, 1 and 2.
Null = '' = string.empty != 1
Null = '' = string.empty != 1
Null = '' = string.empty != 2
1 != 2
I want to copy values from tableWithUpdatedValues to table and set the updated flag to 1 in all cases except one: when the plot value or the review value on the two tables are different AND the destination table value is not null. There is also a difference in the behavior: if the values are different, but the value on tableWithUpdatedValues is null I will keep the value on table
The concept is pretty easy and intuitive. Null is an unuseful value. 1 and 2 have instead the same value. I will never overwrite 1 or 2 with null, and I will have a conflict on overwriting 1 with 2 or viceversa (so I will not overwrite).
http://en.wikipedia.org/wiki/Karnaugh_map
I've realized that the table is simmetrical
Title: Vajont
Plot on table = ''
Plot on tableWithUpdatedValues = 'Nice movie'
Result wanted on table:
plot = 'Nice movie'
updated = 'true'
Title: Lost in Translation
Plot on table = 'Nice movie'
Plot on tableWithUpdatedValues = 'Very nice movie'
Result wanted on table:
plot = 'Nice movie'
updated = 'false'
This should do what you want.
update @myTable
set updated = 0
update t
set plot = ut.plot
, updated = 1
from @myTable t
inner join @myUpdatedTable ut on ut.title = t.title
where ((t.plot is null or t.plot = '')
or t.plot = ut.plot)
and ((t.review is null or t.review = '')
or t.review = ut.review)
Note: since you did not specify a RDBMS I did it in SQL Server 2008. If it does not work, something similar should do it.