Friday, July 5, 2013

Merge Syntax



-- merge TABLEB with the details form table TABLEA
MERGE TABLEB                              
AS TARGET USING  
          (
                   --select querry for merge
                   SELECT
                   ColumnName1,
                   ColumnName2,
                   ColumnName3,
                   ColumnName4,
                   ColumnName5
                   FROM TABLEA
          ) as mer
ON (TARGET.ColumnName=mer.ColumnName)
WHEN MATCHED AND     
          (        TARGET.ColumnName1<>mer.ColumnName1              
                   OR TARGET.ColumnName2<>mer.ColumnName2)
THEN              
     UPDATE SET     TARGET.ColumnName1=mer.ColumnName1,             
                                                          TARGET.ColumnName2=mer.ColumnName2
WHEN NOT MATCHED BY TARGET              
THEN INSERT  
   (
                   ColumnName1,
                   ColumnName2,
                   ColumnName3,
                   ColumnName4,
                   ColumnName5 
   )  
 
VALUES
  (                mer.ColumnName1,
                   mer.ColumnName2,
                   mer.ColumnName3,
                   mer.ColumnName4,
                   mer.ColumnName5
  )                  

No comments:

Post a Comment