如何在合并条件中使用“或”“何时不与源匹配”

时间:2018-05-09 07:36:44

标签: sql sql-server-2008

我有以下声明:

MERGE dbo.SystemCustomer As TARGET
USING (Select * 
       From dbo.vClients 
       Where ClientNumber Is Not Null) As SOURCE
    On TARGET.CustNumber = SOURCE.ClientNumber
WHEN MATCHED And (TARGET.DisplayCustNumber<>SOURCE.VisualID Or 
                  TARGET.CustName<>ISNULL(SOURCE.CustName,'') 
             And IsNull(SOURCE.VisualID,'') <> '' And IsNull(TARGET.DisplayCustNumber,'') <> ''
THEN Update Set TARGET.DisplayCustNumber = SOURCE.VisualID,
                TARGET.CustName = ISNULL(SOURCE.CustName,'')    
WHEN NOT MATCHED BY TARGET
THEN Insert (CustNumber, DisplayCustNumber, CustName)
     Values (SOURCE.ClientNumber, SOURCE.VisualID, ISNULL(SOURCE.CustName,''))  
WHEN NOT MATCHED BY Source --or IsNull(TARGET.DisplayCustNumber,'') = ''
THEN Delete;

我想删除未与来源匹配的记录以及Target.DisplayCustNumber为空或null时的记录(在"WHEN NOT MATCHED BY Source"声明后的评论中说明) - 但显然不是可能的语法明智。 我该如何绕过这个?提前谢谢!

1 个答案:

答案 0 :(得分:3)

如果没有您的表格定义,我无法真正测试,但您可以保留WHEN NOT MATCHED BY SOURCE THEN DELETE并添加另一个WHEN MATCHED AND <condition> THEN DELETE

MERGE dbo.SystemCustomer As TARGET
USING (Select * 
       From dbo.vClients 
       Where ClientNumber Is Not Null) As SOURCE
    On TARGET.CustNumber = SOURCE.ClientNumber
WHEN MATCHED And (TARGET.DisplayCustNumber<>SOURCE.VisualID Or 
                  TARGET.CustName<>ISNULL(SOURCE.CustName,'') 
             And IsNull(SOURCE.VisualID,'') <> '' And IsNull(TARGET.DisplayCustNumber,'') <> ''
THEN Update Set TARGET.DisplayCustNumber = SOURCE.VisualID,
                TARGET.CustName = ISNULL(SOURCE.CustName,'')   

WHEN MATCHED AND IsNull(TARGET.DisplayCustNumber,'') = '' THEN DELETE -- Add this line

WHEN NOT MATCHED BY TARGET
THEN Insert (CustNumber, DisplayCustNumber, CustName)
     Values (SOURCE.ClientNumber, SOURCE.VisualID, ISNULL(SOURCE.CustName,''))  
WHEN NOT MATCHED BY Source --or IsNull(TARGET.DisplayCustNumber,'') = ''
THEN Delete;

多个MATCHED语句有一些限制,但它们适用于您的情况(如果您进一步编辑,请留意):

  

MERGE语句最多可以有两个WHEN MATCHED子句。如果两个   条款是指定的,那么第一个条款必须附有一个   AND条款。对于任何给定的行,仅第二个WHEN MATCHED子句   如果第一个不是,则应用。如果有两个WHEN MATCHED条款,   然后必须指定UPDATE操作,并且必须指定DELETE   行动。如果在子句中指定了UPDATE,则多行   匹配target_table中的一行,SQL Server返回错误。   MERGE语句不能多次更新同一行,或   更新并删除同一行。