Share via

insert / update Merged

Shambhu Rai 1,411 Reputation points
2022-08-24T18:19:53.78+00:00

Create table1
( id, region string,subregion string, value1 int,value2 int,value2 int,value3 int)
Insert into table1
values('1','west','coastal',22,34,44),
('2','north','northsea',23,14,24)

Create table2
( id, region string,subregion string, value1 int,value2 int,value2 int,,value3 int)
Insert into table2
values('1','west','coastal',21,34,44),
('2','north','northsea',23,15,24)

how we can use different methods in insert and update statement. means if values match then need not insert but update the records. and also expect scenario to maintain changes like history and also merge statement

SQL Server Integration Services
SQL Server Analysis Services
SQL Server Analysis Services

A Microsoft online analytical data engine used in decision support and business analytics, providing the analytical data for business reports and client applications such as Power BI, Excel, Reporting Services reports, and other data visualization tools.

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories


1 answer

Sort by: Most helpful
  1. LiHongMSFT-4306 31,621 Reputation points
    2022-08-25T01:40:53.143+00:00

    Hi @Shambhu Rai

    if values match then need not insert but update the records. and also expect scenario to maintain changes like history

    It seems you need a MERGE statement with OUTPUT clause, like this:

    MERGE #table1 T  
    USING #table2 S ON T.id=S.id  
       
    WHEN MATCHED THEN  
    UPDATE SET value1=S.value1, value2=S.value2, value3=S.value3  
      
    WHEN NOT MATCHED BY TARGET   
    THEN INSERT (id,region,subregion,value1,value2,value3)   
         VALUES (S.id,S.region,S.subregion,S.value1,S.value2,S.value3)  
      
    OUTPUT DELETED.*, $action AS [Action], INSERTED.* ;  
    

    Refer to this article for more details: SQL Server MERGE Statement overview and examples

    Best regards,
    LiHong

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.