We can modify data using (INSERT, Update and delete ) using merge statement based on conditional logic. The format is little different as follows :
We use the target table name in MERGE clause .
And source table in USING clause .
We define merge condition by specifying a predicate in ON clause like as we do in join .
The merge condition defines which of the rows in source table matches with the rows in target table.
In WHEN MATCHED THEN clause we define the action to be taken when rows are matched.
And In WHEN NOT MATCHED THEN we define the action when the rows are not matched.
For example :
MERGE INTO dbo.targettable AS TGT
USING dbo.sourcetable AS SRC
ON TGT.custid = SRC.custid
WHEN MATCHED THEN
UPDATE SET
TGT.personname = SRC.personname,
TGT.phone = SRC.phone,
TGT.address = SRC.address
WHEN NOT MATCHED THEN
INSERT (personid, personname , phone, address)
VALUES (SRC.personid, SRC.personname , SRC.phone, SRC.address);
The MERGE statement defines an UPDATE action when a match is found, setting the target personname , phone, and address values to those of the matched rows from the source table.
The MERGE statement defines an INSERT action when a match is not found, it inserts the rows from the source to the target table
