--To Merge Data of different tables we can use merge statement in sql which first checks the content of both the tables and adds the data in the Target table which are missing from Soucre Table.
Syntax:
MERGE INTO [TARGETTABLE] AS Target
USING [SOURCETABLE] AS SOURCE
ON
--unique key filtering condition
Target.COLUMN1=SOURCE.COLUMN1 AND
Target.COLUMN2=SOURCE.COLUMN2 AND
Target.COLUMN3 =SOURCE.COLUMN3 AND
Target.COLUMN4 =SOURCE.COLUMN4
WHEN MATCHED THEN
--update or delete query
UPDATE SET
Target.ColumnA=SOURCE.ColumnA,
Target.ColumnB=SOURCE.ColumnB,
Target.ColumnC=SOURCE.ColumnC
WHEN NOT MATCHED THEN
--INSERT QUERY
INSERT (COLUMNA, ColumnB, ColumnC, ColumnD)
VALUES(
SOURCE.ColumnA,
SOURCE.ColumnB,
SOURCE.ColumnC,
SOURCE.ColumnD )
;
USING [SOURCETABLE] AS SOURCE
ON
--unique key filtering condition
Target.COLUMN1=SOURCE.COLUMN1 AND
Target.COLUMN2=SOURCE.COLUMN2 AND
Target.COLUMN3 =SOURCE.COLUMN3 AND
Target.COLUMN4 =SOURCE.COLUMN4
WHEN MATCHED THEN
--update or delete query
UPDATE SET
Target.ColumnA=SOURCE.ColumnA,
Target.ColumnB=SOURCE.ColumnB,
Target.ColumnC=SOURCE.ColumnC
WHEN NOT MATCHED THEN
--INSERT QUERY
INSERT (COLUMNA, ColumnB, ColumnC, ColumnD)
VALUES(
SOURCE.ColumnA,
SOURCE.ColumnB,
SOURCE.ColumnC,
SOURCE.ColumnD )
;