Key words: Merge compare Columns
When we contact merge SQL in ETL,
When we update some columns we shoshould compare the value change or not.
We always write coalesce (columnname, valueifnull) <> coalesce (columnname, valueifnull)
But we shoshould take care of the valueifnull, the value shoshould not exist in tables and the Data Type
Shocould be right. Two points need to satisfy the requirements.
If you want to use SQL to generate the SQL automatically, you shoshould know the column type for every column,
We can get this from database's meta data table, but we also need set the value if the column is null, this part
Will need a long case when, if not, we shoshould have a configuration table to store this.
Another solution is:
ORACLE:
Merge into target tar using (select * from source) as SRC
On tar. colx = SRC. colx...
When matched update set Col = SRC. Col... Where tar. Col! = SRC. col or (tar. Col is null and SRC. Col is not null) or (tar. Col is not null and SRC. Col is null)
It is long, if we execute it dynamically, the string may long exceed varchar2 (4000 );
Tar. Col! = SRC. COL (when the both columns are valid and not null)
Now, I think another expression to stand for not equal.
Not (tar. Col is null and SRC. Col is null)
Sqlserver:
Merge into target tar using (select * from source) as SRC
On tar. colx = SRC. colx...
When matched and
(
Tar. Col <> SRC. Col
Or not (tar. Col is null and SRC. Col is null)
Or ....
)
Update set Coly = SRC. Coly
...
You will notice that, there are some differences in merge implementation for Oracle and sqlserver.
Slqserver is more powerful on this.
IT support when matched and conditions but Oracle not support this, but you can add the filter at where clause.
Just update what you want to update.
Another thing is sqlserver can judge the not matched case is caused by target table or source table.
When not matched by target table, insert data from source table.
When not matched by source talbe, just delete or do other actions.
On clause in merge is also need take care.
On tar. Col = SRC. Col and (tar. Col is null and SRC. Col is null)
Maybe is useful for your query.
Merge compare columns when null