MERGE Command in SQL Server

visit: https://zonixsoft.com (our official website)

In SQL Server 2008, Microsoft introduces the MERGE functionality through the MERGE command. The MERGE command inserts rows that don’t exist and updates the rows that do exist.

    What MERGE Command works as,

        IF FOUND

           THEN UPDATE

        ELSE

           INSERT;

    Until now, this MERGE functionality could only be made available in SQL Server through stored procedures and cursors, etc.

    This article illustrates how to user MERGE command in SQL Server 2008.

    Suppose we have 2 tables with same field structure as ID, ProductName and SKU,

        MERGE INTO ProductTable1 AS Target

        USING  AS ProductTable2 AS Source

                ON Target.ID = Source.ID

        WHEN MATCHED THEN

                UPDATE SET Target.ProductName = Source.ProductName,

                Target.SKU = Source.SKU

        WHEN NOT MATCHED THEN

                INSERT (ID,ProductName,SKU) VALUES (Source.ID,Source.ProductName,Source.SKU);

 


Bookmark and Share