【问题标题】:SQL Server Merge WHEN NOT MATCHED clause customizationsSQL Server Merge WHEN NOT MATCHED 子句自定义
【发布时间】: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');

匹配时更新,但插入失败。我有两个问题:

  1. 有没有办法在上述情况下不匹配时插入?

  2. 我可以自定义不匹配条件以引发错误吗?

谢谢。

【问题讨论】:

  • 我不明白为什么使用 JDBC 连接会影响您的代码。我会把它变成一个存储过程,然后你如何连接它并不重要,你的代码与数据分离。至于为此使用合并,请阅读我发布的文章,然后您决定死锁的风险是否值得。如果是我的系统,我不会为此使用合并。而且由于我之前没有回答,因此您不能使用合并来引发异常。 Merge 是单条语句,不是流控机制。

标签: sql sql-server sql-merge


【解决方案1】:

合并有效,只是您的源 (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);

【讨论】:

  • 我的意图是当 col1=4 的行不存在时,插入它。我正在使用相同的源表和目标表并尝试这样做。可以这样做还是创建临时表是唯一的解决方案?
猜你喜欢
  • 1970-01-01
  • 2017-02-13
  • 1970-01-01
  • 2014-10-16
  • 1970-01-01
  • 2016-04-30
  • 2016-01-15
  • 2022-07-06
  • 2017-01-24
相关资源
最近更新 更多