有没有办法使用 oracle 合并插入和删除但不更新?
我有一个表,表示与另一个表中的单行相关的一组值。我可以通过将它们全部删除并添加回新集,或者通过有选择地删除一些并添加其他值来更改值集,但如果可能的话,我有兴趣将其设为单个语句。
这是一个更新的工作示例。为了完成这项工作,我必须添加dummy
一个列,以便更新不在on
条件中的列。有没有办法只删除和插入而没有要更新的虚拟列?
条件中的任何列on
都可能update set
不在列表中,即使它实际上没有更新。
create table every_value ( the_value varchar2(32) );
create table paired_value ( the_id number, a_value varchar2(32) , dummy number default 0 );
-- the_id is a foreign_key to a row in another table
insert into every_value ( the_value ) values ( 'aaa' );
insert into every_value ( the_value ) values ( 'abc' );
insert into every_value ( the_value ) values ( 'ace' );
insert into every_value ( the_value ) values ( 'adg' );
insert into every_value ( the_value ) values ( 'aei' );
insert into every_value ( the_value ) values ( 'afk' );
-- pair ace and afk with id 3
merge into paired_value p using every_value e
on ( p.the_id = 3 and p.a_value = e.the_value )
when matched then update set dummy=dummy+1
delete where a_value not in ('ace','afk')
when not matched then insert (the_id,a_value)
values (3,e.the_value)
where e.the_value in ('ace','afk');
-- pair ace and aei with id 3
-- should remove afk, add aei, do nothing with ace
merge into paired_value p using every_value e
on ( p.the_id = 3 and p.a_value = e.the_value )
when matched then update set dummy = dummy+1
delete where a_value not in ('ace','aei')
when not matched then insert (the_id,a_value)
values (3,e.the_value)
where e.the_value in ('ace','aei');
-- pair aaa and adg with id 4
merge into paired_value p using every_value e
on ( p.the_id = 4 and p.a_value = e.the_value )
when matched then update set dummy = dummy+1
delete where a_value not in ('aaa','adg')
when not matched then insert (the_id,a_value)
values (4,e.the_value)
where e.the_value in ('aaa','adg');
select * from paired_value;
我已经在 oracle 10g 和这个sqlfiddle中尝试过这个,oracle 11g。