T-SQL MERGE与条件不匹配?

时间:2018-05-27 11:41:38

标签: sql sql-server tsql

假设我做了一个与

之类的条件匹配的合并
MERGE TargetTable WITH(HOLDLOCK) AS target
USING SourceTable AS source
ON (target.ID = source.ID)
WHEN MATCHED AND (source.BitCondition = 0) THEN
    UPDATE TargetTable
WHEN NOT MATCHED -- what is not matched??
    INSERT INTO TargetTable

不匹配的记录是否不在两个表中,或者就像

NOT(MATCHED AND (source.BitCondition = 0))

N.B。我故意想忽略它匹配的情况和BitCondition = 1

2 个答案:

答案 0 :(得分:1)

根据MERGE documentationexport const fetchBeerWithComments =(parameter) => async dispatch => {... 的默认值为NOT MATCHED,表示该行存在于源{但不是NOT MATCHED BY TARGET的目标。

为避免使用MERGE插入不匹配的行,您可以添加source.BitCondition = 1条件:

AND

答案 1 :(得分:0)

简单地说,它只是记录不在两个表中的记录&#34;。从技术上讲,NOT MATCHED仅使用ON <merge_search_condition>子句中定义的条件进行评估。

换句话说,您可以将MATCHED视为<merge_search_condition>的别名。

因此您的查询可以写成(伪代码)

MERGE ...
ON (target.ID = source.ID)
WHEN (target.ID = source.ID) AND (source.BitCondition = 0) THEN
    UPDATE TargetTable
WHEN NOT (target.ID = source.ID) 
    INSERT INTO TargetTable