SQL 服务器合并 WHEN NOT MATCHED 子句自定义
SQL Server Merge WHEN NOT MATCHED clause customizations
在SQL服务器中使用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');
匹配但插入失败时更新。我有两个问题:
有没有办法在上述情况下不匹配时插入?
我可以自定义不匹配条件来报错吗?
谢谢。
合并有效,只是您的源 (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);
在SQL服务器中使用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');
匹配但插入失败时更新。我有两个问题:
有没有办法在上述情况下不匹配时插入?
我可以自定义不匹配条件来报错吗?
谢谢。
合并有效,只是您的源 (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);