How to Use the SQL MERGE Statement for Effective Account Management
1.Merge the data in a temporary customer table with that of the existing Customers table for updating purposes in the case of an already existing customer and inserting new records if the customer does not exist. Merge data from a temporary TempCustomers table into the existing Customers table.
MERGE INTO Customers c
USING TempCustomers t
ON (c.CustomerID = t.CustomerID)
WHEN MATCHED THEN
UPDATE SET c.Email = t.Email, c.Phone = t.Phone
WHEN NOT MATCHED THEN
INSERT (CustomerID, Name, Email, Phone, Address)
VALUES (t.CustomerID, t.Name, t.Email, t.Phone, t.Address);
Explanation
To begin with, we have the MERGE INTO statement which merges data from the table TempCustomers t and places it into the Customers table c. Matching is done based on the CustomerID field. When an identical CustomerID value is found in the two tables implying that the customer already exists within the Customers table the query updates the Email and Phone fields with corresponding values in the TempCustomers table. If there was no match meaning that the customer was not present in the Customers table, a new record would have been created in the Customers table . Such procedure ensures the update of the modification and new entries about Customers from the table TempCustomers.