在 SQL 合并中,如果“不匹配且 <condition>”失败,会发生什么行为
In a SQL merge, what would be behavior in case `when not matched and <condition>` fails
考虑以下 merge
:
merge tgtTable tgt
using ( <record from srcTable> ) src
on ( tgt.id = src.id )
when matched
and ('sha1', isnull(tgt.field, '')) != hash('sha1', isnull(src.field, ''))
then update
set tgt.otherFields = src.otherFields
when not matched by target
then insert
(id, field) values (src.id, src.field)
这不是一个非常困难的查询,但我需要对 when matched and <condition>
和 when not matched
进行一些说明。
例如,在我的来源table中,我有这样一条记录:
------- SRC Table --------
ID | FIELD | OTHERFIELDS
------------------------
5 | a_value | ...
假设 目标 table 有一个非常相似的记录:
------- TGT Table --------
ID | FIELD | OTHERFIELDS
------------------------
5 | value_b | ...
当合并语句运行时,它们是一个匹配项 (tgt.id = src.id
),但它们将无法满足 and
条件 (('sha1', isnull(tgt.field, '')) != hash('sha1', isnull(src.field, ''))
.
示例中实际失败的是 and
条件,而不是匹配本身。这样的话,not matched by target
中的insert会被执行吗?
没有。这与 CASE 子句完全一样。
请参阅此处的示例 B:
https://msdn.microsoft.com/en-us/library/bb510625.aspx
考虑以下 merge
:
merge tgtTable tgt
using ( <record from srcTable> ) src
on ( tgt.id = src.id )
when matched
and ('sha1', isnull(tgt.field, '')) != hash('sha1', isnull(src.field, ''))
then update
set tgt.otherFields = src.otherFields
when not matched by target
then insert
(id, field) values (src.id, src.field)
这不是一个非常困难的查询,但我需要对 when matched and <condition>
和 when not matched
进行一些说明。
例如,在我的来源table中,我有这样一条记录:
------- SRC Table --------
ID | FIELD | OTHERFIELDS
------------------------
5 | a_value | ...
假设 目标 table 有一个非常相似的记录:
------- TGT Table --------
ID | FIELD | OTHERFIELDS
------------------------
5 | value_b | ...
当合并语句运行时,它们是一个匹配项 (tgt.id = src.id
),但它们将无法满足 and
条件 (('sha1', isnull(tgt.field, '')) != hash('sha1', isnull(src.field, ''))
.
示例中实际失败的是 and
条件,而不是匹配本身。这样的话,not matched by target
中的insert会被执行吗?
没有。这与 CASE 子句完全一样。 请参阅此处的示例 B: https://msdn.microsoft.com/en-us/library/bb510625.aspx