declare@ source table(id int, name varchar(50))
declare@ target table(id int, name varchar(50), status varchar(10))
insert into@ source
values(1, 'abc'), (2, 'pqr'), (3, 'xyz')
insert into@ target(id, name)
values(1, 'abc'), (2, 'sdfdf'), (4, 'abc')
select * from@ target
merge@ target as a
using
(
select * from@ source
)
as b on a.id = b.id
when matched and a.name < > b.name then update set a.name = b.name, a.status = 'updated'
when not matched by target then insert(id, name, status) values(b.id, b.name, 'inserted')
when not matched by source then delete;
select * from@ targetMERGE statement allows you to perform INSERT, UPDATE & DELETE command with a single statement, and so is very efficient way to perform multiple DML operations.