This question already has answers here:
Why WHEN MATCHED' cannot appear more than once in a 'UPDATE' clause of a MERGE statement?

(2个答案)


去年关闭。




SQL Server版本:Microsoft SQL Server 2012-11.0.2218.0(x64)

当我运行此查询时,出现以下异常。
异常:类型“WHEN MATCHED”的 Action 在MERGE语句的“UPDATE”子句中不能出现多次。

我知道异常是在Merge语句中多次执行Update语句。
您能否建议我我如何实现以下SQL查询逻辑?

基于一列,
当Matched和column不为null时,则仅更新一个不同的列。
当Matched和column为null时,则更新大多数列。
不匹配时插入。


完整的SQL是
MERGE TargetTable AS targetT
USING   SourceTable AS sourceT ON sourceT.Npi = targetT.Npi
WHEN    MATCHED AND IsNull(targetT.SPI, '') <> '' THEN
        UPDATE SET targetT.Taxonomy = sourceT.Taxonomy --Update Only One Column

WHEN    MATCHED AND IsNull(targetT.SPI,'')= '' THEN --Update Rest of the Columns
        UPDATE SET targetT.state_license_no = sourceT.state_license_no, targetT.NPI = sourceT.NPI, targetT.PrefixName = sourceT.PrefixName,targetT.last_name = sourceT.last_name,targetT.first_name = sourceT.first_name
               ,MiddleName = sourceT.MiddleName,targetT.SuffixName = sourceT.SuffixName, targetT.address_1 = sourceT.address_1,targetT.address_2 = sourceT.address_2,targetT.City = sourceT.City,targetT.State = sourceT.State
               ,zip = sourceT.zip,targetT.phone = sourceT.phone,targetT.Fax = sourceT.Fax,targetT.last_modified_date = sourceT.last_modified_date,targetT.Taxonomy = sourceT.Taxonomy

WHEN    NOT MATCHED BY TARGET --Insert New Row
        THEN
        INSERT (state_license_no, NPI, prefixname, last_name, first_name, MiddleName, SuffixName, address_1, address_2, City, State, zip, phone, Fax, last_modified_date, Taxonomy, Data_source)
                                    VALUES (sourceT.state_license_no, sourceT.NPI, sourceT.PrefixName, sourceT.last_name, sourceT.first_name, sourceT.MiddleName, sourceT.SuffixName,
                                    sourceT.address_1, sourceT.address_2, sourceT.City, sourceT.State, sourceT.zip,
                                    sourceT.phone, sourceT.Fax, sourceT.last_modified_date, sourceT.Taxonomy, sourceT.Data_source);

最佳答案

按照MSDN的规定,“如果有两个WHEN MATCHED子句,则一个必须指定UPDATE Action ,而一个必须指定DELETE Action ”。

WHEN MATCHED THEN <merge_matched>

指定根据子句更新或删除与ON <merge_search_condition>返回的行匹配并满足任何其他搜索条件的target_table的所有行。MERGE语句最多可以包含两个WHEN MATCHED子句。

如果指定了两个子句,则第一个子句必须带有AND <search_condition>子句。对于任何给定的行,仅当第一个WHEN MATCHED子句不适用时才应用第二个WHEN MATCHED子句。如果有两个UPDATE子句,则一个必须指定ojit_code Action ,而一个必须指定DELETE Action 。



资料来源:MSDN

希望这可以帮助。

关于sql - SQL Server MERGE中的多个更新语句,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25848219/

10-12 17:38
查看更多