【问题标题】:ORACLE SQL:More than one WHEN MATCHED condition INSIDE MERGE STATEMENTORACLE SQL:多个 WHEN MATCHED 条件 INSIDE MERGE STATEMENT
【发布时间】:2017-02-13 15:02:03
【问题描述】:

我想在 pl/sql 中使用合并语句,并且必须在特定条件下更新目标表。我知道我们可以在带有 and 运算符的 sql server 中使用多个匹配条件,但我不确定 Oracle。我正在寻找 oracle 中的那种功能。

【问题讨论】:

  • oracle 中只能有一个when matched 部分,但可以在ON 部分中定义多个逻辑条件与OR 运算符连接
  • 你也可以在update部分使用where子句来指定条件
  • 是的,我可以在更新部分中使用 where 子句,但尽管更新部分中的 where 子句我可以在合并语句中有多个匹配条件,我可以在特定条件下更新某些行并更新某些行使用另一个条件并在不匹配时插入...

标签: sql oracle merge


【解决方案1】:
create table table1 (id number, text varchar2(20));
create table table2 (id number, text varchar2(20), text2 varchar2(20));

insert into table1 values (1,'');
insert into table1 values (2,'');
insert into table1 values (3,'');
insert into table2 values (1,'a','b');
insert into table2 values (2,'a','b');
insert into table2 values (3,'a','b');
insert into table2 values (4,'a','b');

我了解您希望获得类似下面带有注释行的代码

merge into table1 t1
using table2 t2
on (t1.id = t2.id)
when matched then update set
t1.text = t2.text where t1.id = 1
--t1.text = t2.text2 where t1.id = 2
when not matched then insert values (t2.id, t2.text);

我会这样做:

merge into table1 t1
using (select id, case id when 1 then text when 2 then text2 else null end as tt, text from table2) t2
on (t1.id = t2.id)
when matched then update set
t1.text = t2.tt where t2.tt is not null
--t1.text = t2.text2 where t1.id = 2
when not matched then insert values (t2.id, t2.text);

select * from table1;

【讨论】:

    猜你喜欢
    • 2016-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    相关资源
    最近更新 更多