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
Write merge Query as below.
Then you can see changes in the LatestSales table as below.
Thank You!!!
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 SalesInsert few records to Sales table.
(
SalesID INT PRIMARY KEY,
ProductName VARCHAR(100),
Amount MONEY
)
INSERT INTO SalesDestination Table structure
values
(1, 'Bulk', 10.00),
(2, 'retail', 20.00),
(3, 'WS', 30.00),
(4, 'foreign', 40.00)
CREATE TABLE LatestSalesInsert few records to LatestSales table.
(
SalesID INT PRIMARY KEY,
ProductName VARCHAR(100),
Amount MONEY
)
INSERT INTO LatestSalesonce we upload data you can se the data as below.
VALUES
(1, 'Bulk', 10.00),
(2, 'retail', 25.00),
(3, 'WS', 35.00),
(5, 'foreign', 60.00)
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;
Then you can see changes in the LatestSales table as below.
Thank You!!!
SQL MERGE Query to Insert, Update and delete records in the destination table
Reviewed by Pubudu Dewagama
on
10:37:00 PM
Rating:
No comments: