2

在 SQL Server 中使用合并子句时,我需要在它不可用时插入一行。这是我尝试过的:

 drop table test;
create table test (col1 int, col2 varchar(20));
insert into test values(1, 'aaa');
insert into test values(2, 'bbb');
insert into test values(3, 'ccc');
--insert into test values(4, 'eee');

merge test as target
using (SELECT * from test where col1=4) as source
on (target.col1 = source.col1)
when matched then
    update set target.col2='ddd'
when not matched by target then
    insert values (4, 'ddd');

这会在匹配时更新,但无法插入。我有两个问题:

  1. 在上述情况下,有没有办法在不匹配时插入?

  2. 我可以自定义不匹配的条件来引发错误吗?

谢谢。

4

1 回答 1

3

合并有效,只是您的源 ( SELECT * from test where col1=4) 为空。没有这样的行。

您可以使用此 hack 引发错误。例如:

when not matched by target then
insert values (0/0 /*ASSERT*/, NULL);
于 2015-05-27T23:26:00.767 回答