当源表中不存在相关行时更新

时间:2013-01-10 10:29:26

标签: sql sql-server sql-server-2008-r2 merge-statement

我有这样的合并声明:

MERGE DESTINATION
USING SOURCE WHERE <Some_Conditions>
WHEN MATCHED AND <Some_Conditions> THEN DELETE
WHEN MATCHED UPDATE
WHEN NOT MATCHED INSERT 

这工作正常,但我还有一个条件,即我必须在源中没有条目时更新目标中的行。

实施例

来源

Column1 Column2 Column3
-----------------------
A        A       A
B        B       B

目标

Column1 Column2 Column3
-----------------------------------
B        B       <Some_Calculation>
D        D       <Some_Calculation>

现在,由于D的源代码中没有行,我必须通过一些计算修改目标中的Column 3。但是,当行匹配或不匹配时,合并仅提供deleteupdateinsert的三个选项。

如何在上述声明中实现此功能?

修改

使用以下评论编辑问题:

在我上面给出的上面示例中,它正在运行,它正在更新B并将A插入到目标表中。但即使源表中没有D,我也要更新{{1}}

1 个答案:

答案 0 :(得分:0)

也许请阅读MERGE的文档:

MERGE 
[ TOP ( expression ) [ PERCENT ] ] 
[ INTO ] <target_table> [ WITH ( <merge_hint> ) ] [ [ AS ] table_alias ]
USING <table_source> 
ON <merge_search_condition>
[ WHEN MATCHED [ AND <clause_search_condition> ]
    THEN <merge_matched> ] [ ...n ]
[ WHEN NOT MATCHED [ BY TARGET ] [ AND <clause_search_condition> ]
    THEN <merge_not_matched> ]
[ WHEN NOT MATCHED BY SOURCE [ AND <clause_search_condition> ]
    THEN <merge_matched> ] [ ...n ]
...
您需要

WHEN NOT MATCHED BY SOURCE