Sunday, March 13, 2016

Merging Data of two tables in SQL Server

Keeping Data in sync can be challenging especially when there are different tables involved in Data collection process. Often we need to sync the data so that all the necessary tables provide accurate information. This scenario is prevalent among ticket bookings scenario or even match score where the data is changing  every minute.


Take an instance , here Display_booking and current_booking are two tables which are used to show information about orders placed by customers:





   Now, we can observe that data in both tables is not in sync, are our task is to display accurate information to customers and reduce ambiguity.

Now, Display_booking contains the latest data, so we need to get current_booking table in sync with display_booking table

So we use merge command:

Merge current_booking as c
using (select order_id , name, order_status from display_booking ) as d
on (c.order_id = d.order_id)
WHEN Matched then
update set c.name = d.name , c.order_status = d.order_status
when not matched by source then
delete
when not matched by target then
insert values ( d.name , d.order_status);


Now we can see that current_booking table is in sync with display_booking table.

No comments:

Post a Comment