简体   繁体   English

MERGE 语句 SQL 有几个条件

[英]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:我有看起来像这样的数据,我似乎无法弄清楚如何让 MERGE 语句工作,因为它的条件有限:

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)参考: MERGE (Transact-SQL)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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