Thursday, March 2, 2017

SQL MERGE statement to insert-update data

If you want copy data from one table to another you can use MERGE. In my case I need to Insert/update different database table with  some fields so you can check I made a condition in ON ( T.UserName = S.UserName  AND t.customerid = s.customerid   ) its means if the customerid and UserName is not match it will insert otherwise I will update the T.First_Name.


CREATE PROCEDURE [sp_name] 
AS 
  BEGIN 
    MERGE tcustomers                         AS t 
    using            a_database.dbo.customer AS s 
    ON ( 
                                      t.username = s.username 
                     AND              t.customerid = s.customerid ) 
    WHEN NOT matched BY target THEN 
    INSERT 
                 ( 
                              col 
                 ) 
                 VALUES 
                 ( 
                              s.col 
                 ) 
    WHEN matched THEN 
    UPDATE 
    SET    t.first_name = s.first_name , 
  end







No comments:

Post a Comment