ORACLE SQL:不止一个WHEN MATCHED条件INSIDE MERGE STATEMENT

时间:2016-10-05 08:48:07

标签: sql oracle merge

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

1 个答案:

答案 0 :(得分:0)

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;