【发布时间】:2015-05-27 19:57:50
【问题描述】:
在 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');
匹配时更新,但插入失败。我有两个问题:
有没有办法在上述情况下不匹配时插入?
我可以自定义不匹配条件以引发错误吗?
谢谢。
【问题讨论】:
-
我不明白为什么使用 JDBC 连接会影响您的代码。我会把它变成一个存储过程,然后你如何连接它并不重要,你的代码与数据分离。至于为此使用合并,请阅读我发布的文章,然后您决定死锁的风险是否值得。如果是我的系统,我不会为此使用合并。而且由于我之前没有回答,因此您不能使用合并来引发异常。 Merge 是单条语句,不是流控机制。
标签: sql sql-server sql-merge