SQL Server合并WHEN NOT MATCHED子句自定义

时间:2015-05-27 19:57:50

标签: sql sql-server sql-merge

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

 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. 我可以自定义不匹配的条件来引发错误吗?

  3. 感谢。

1 个答案:

答案 0 :(得分:3)

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

You can raise an error using this hack.例如:

when not matched by target then
insert values (0/0 /*ASSERT*/, NULL);