在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');
在匹配时更新,但无法插入。我有两个问题:
在上述情况下,有没有办法在不匹配时插入?
我可以自定义不匹配的条件来引发错误吗?
感谢。
答案 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);