简体   繁体   中英

MERGE Statement SQL with several conditions

I have data that looks like this, and I can't seem to figure out how to get the MERGE statement to work as it has limited # of condition:

When doing the merge everything is working except for the Purge Record

Source:

AccountID = 123, Name = Mike, Balance = 100 (This should result in UPDATE - Matched Condition)
AccountID = 234, Name = Smith, Balance = 50 (This should result in New - Not Matched Condition)

Target:

AccountID = 123, Name = Mike, Balance = 150
AccountID = 12345, Name = john, Balance = 200 (This record needs to be marked as purged)

Any thoughts?

If I understand your question correctly, then you want to use the following conditions:

  • when not matched by target then
  • when not matched by source then

A rough example:

merge ExistingTable as dest
using   ( values 
             ('123','Mike', '100')
            ,('234','Smith', '50')
        ) as src([AccountID], [Name], [Balance] )
    on src.[AccountID] = dest.[AccountID]
when matched then
    update set
        [Name] = src.[Name],
        [Balance] = src.[Balance]
when not matched by target then 
    insert ([AccountID],[Name],[Balance])
        values (src.[AccountID],src.[Name],src.[Balance])
when not matched by source then
    delete;

Reference: MERGE (Transact-SQL)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM