I have two tables, one in database db1
and another one in db2
. They both are identical and only have id
, name
(varchar) and data
(float).
I do this query to move the data update source table in db1
to target db2
:
MERGE [db1].[dbo].fake_table as target USING (
select
src.id,
src.data,src.name
from [db2].[dbo].fake_table
src where 1=1 ) as source (
id,
data,name
)
on (
target.id=source.id
)
WHEN MATCHED AND
(target.data<>source.data OR target.name<>source.name)
THEN
UPDATE SET target.data=source.data,target.name=source.name
WHEN NOT MATCHED BY target
THEN
INSERT (
id,
data,name
)
Values (id,
data,name
)
WHEN NOT MATCHED BY source
THEN DELETE;
It works for all kind of rows but not the ones that have NULL as a value
MERGE
because it's riddled with bugs.