有沒有辦法使用oracle merge插入和刪除而不是更新?Oracle sql合併插入並刪除但不更新
我有一個表格表示一組與另一個表中的單行相關的值。我可以通過全部刪除它們並添加新的集合,或者通過有選擇地刪除一些並添加其他集合來更改這組值,但如果可能,我有興趣將它作爲單個語句。
以下是更新的一個工作示例。爲了使這項工作,我不得不添加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。
我相當確定沒有比虛擬列更好的方法,但我不打算爲此添加虛擬列。好吧。 – drawnonward