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

[英]SQL Server Merge WHEN NOT MATCHED clause customizations


When merge clause is used in SQL Server, I need to insert a row when it is not available. This is what I have tried:

在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');

This updates when upon matching but fails to insert. I have got two questions:

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

  1. Is there a way to insert upon not matching in the above case?

    在上述情况下是否有一种方法可以插入不匹配?

  2. Can I customize the not matching criteria to raise an error?

    我可以自定义不匹配的标准来引发错误吗?

Thanks.

谢谢。

1 个解决方案

#1


3  

The merge works, it's just that your source (SELECT * from test where col1=4) is empty. There is no such row.

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

You can raise an error using this hack. For example:

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

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/05/27/e8fbfbb66d21bc9b5c486345beb2f977.html



 
  © 2014-2022 ITdaan.com 联系我们: