SQL MERGE Query to Insert, Update and delete records in the destination table

In the Data warhousing application, we have to update Data warehouse according to the source data. In the SQL Server wecan use the Merge query take changes from source to data warehouse.
In this example I will take a Sale table as target table and LatestSales as a source table containing updated list of Sales. I will then use the MERGE SQL command to synchronize the target table with the source table.
DDl For Sales table
CREATE TABLE Sales
(
SalesID INT PRIMARY KEY,
ProductName VARCHAR(100),
Amount MONEY
)
Insert few records to Sales table.
INSERT INTO Sales
values
(1, 'Bulk', 10.00),
(2, 'retail', 20.00),
(3, 'WS', 30.00),
(4, 'foreign', 40.00)
Destination Table structure
CREATE TABLE LatestSales
(
SalesID INT PRIMARY KEY,
ProductName VARCHAR(100),
Amount MONEY
)
Insert few records to LatestSales table.
INSERT INTO LatestSales
VALUES
(1, 'Bulk', 10.00),
(2, 'retail', 25.00),
(3, 'WS', 35.00),
(5, 'foreign', 60.00)
once we upload data you can se the data as below.
image
Write  merge Query as below.
MERGE LatestSales AS TARGET
USING Sales AS SOURCE ON (TARGET.SalesID = SOURCE.SalesID)
WHEN MATCHED AND TARGET.ProductName <> SOURCE.ProductName
OR TARGET.Amount <> SOURCE.Amount THEN
UPDATE SET TARGET.ProductName = SOURCE.ProductName,
TARGET.Amount = SOURCE.Amount
WHEN NOT MATCHED BY TARGET THEN 
INSERT (SalesID, ProductName, Amount)
VALUES (SOURCE.SalesID, SOURCE.ProductName, SOURCE.Amount)
WHEN NOT MATCHED BY SOURCE THEN
DELETE;
image
Then you can see changes in the LatestSales table as below.
image
Thank You!!!
SQL MERGE Query to Insert, Update and delete records in the destination table SQL MERGE Query to Insert, Update and delete records in the destination table Reviewed by Pubudu Dewagama on 10:37:00 PM Rating: 5

No comments: