4
MERGE  DestinationTable AS D 
USING @SourceTable AS S
ON D.Alternate_ID = S._ID

WHEN MATCHED AND
(
       D.Candidate_ID <> S.Candidate_ID  OR  ISNULL(D.Vacancy_ID,'') <> S.Vacancy_ID   
)
THEN
UPDATE SET  
    D.FName = S.FName,
    D.Department = S.Department,

WHEN NOT MATCHED BY TARGET
THEN INSERT  
(
    Alternate_ID,
    FName,
    Department
 ) 
  VALUES 
  (
    S.ID,
    S.FName,
    S.Department  
  ) 
 WHEN NOT MATCHED BY SOURCE
 --How to add a where clause to the delete statement here
 THEN  DELETE; --E.g WHERE  D.Department <> 'HR'

如果它们已从源中删除,我正在使用上面的 Merge 语句删除 DestinationTable 中的记录

有谁知道如何在 Delete 语句中添加 WHERE 条件?我只想从 ColA 等于特定常量字符串的目标中删除。

4

1 回答 1

16

是的,请参阅MSDN 文章了解MERGE.

[ WHEN NOT MATCHED BY SOURCE [ AND <clause_search_condition> ]
    THEN <merge_matched> ] [ ...n ]

以下是应用于NOT MATCHED BY SOURCE查询部分的文档(假设 CoIA 是目标表中的一列):

...
WHEN NOT MATCHED BY SOURCE AND D.CoIA = 'YourValue' THEN
DELETE;

但是,请务必注意以下事项:

MERGE 语句最多可以有两个 WHEN NOT MATCHED BY SOURCE 子句。如果指定了两个子句,则第一个子句必须伴随一个 AND <clause_search_condition > 子句。对于任何给定的行,仅当第一个不匹配时才应用第二个 WHEN NOT MATCHED BY SOURCE 子句。如果有两个 WHEN NOT MATCHED BY SOURCE 子句,则一个必须指定 UPDATE 操作,一个必须指定 DELETE 操作。<clause_search_condition> 中只能引用目标表中的列

于 2014-09-29T22:27:55.767 回答