1) Inserts records into target table if those records are in source table but not in target table.
2) Updates records in target table if those records are modified in source table.
3) Deletes records from target table if those records are deleted from source table
Example:
Source EMPLOYEE1 table and target EMPLOYEE2 table have the below records:

Merge command looks like:
MERGE EMPLOYEE2 AS TARGET
USING EMPLOYEE1 AS SOURCE
ON TARGET.Id = SOURCE.Id
WHEN MATCHED AND TARGET.Name <> SOURCE.Name
THEN
UPDATE SET TARGET.Name = SOURCE.Name /*updating if ids are same and names are different*/
WHEN NOT MATCHED BY TARGET
THEN
INSERT (Id,Name)
VALUES (SOURCE.Id,SOURCE.Name) /*inserting if record is not found in target*/
WHEN NOT MATCHED BY SOURCE
THEN DELETE /*deleting record if it is not found in source*/
-- optional lines
OUTPUT $action,
DELETED.Id,
DELETED.Name,
INSERTED.Id,
INSERTED.Name;
Here $action column is of NVARCHAR(10) variable, it uses to display type of operation performed on a particular row of a table like INSERT,DELETE or UPDATE. This is optional one. Remember MERGE statement should end with semicolon (;).
After execution of above statement we will have the following result set and respective source and target tables

But, this MERGE is not available in earlier versions of sql server mainly in sql server 2005. One can achieve this functionality by writing queries like.
UPDATE EMPLOYEE2 SET Name=E1.Name FROM EMPLOYEE2 E2
INNER JOIN EMPLOYEE1 E1 ON E2.Id = E1.Id
WHERE E1.Name <> E2.Name
INSERT INTO EMPLOYEE2(Id, Name)
SELECT Id, Name FROM EMPLOYEE1
WHERE Id NOT IN (SELECT Id FROM EMPLOYEE2)
DELETE EMPLOYEE2 WHERE Id NOT IN
(SELECT Id FROM EMPLOYEE1)
No comments:
Post a Comment