1. 程式人生 > >Oracle 中MERGE語句的用法(轉載)

Oracle 中MERGE語句的用法(轉載)

同時 sdn ble reat nth merge type href detail

原文章出處(http://blog.csdn.net/lichkui/article/details/4306299)

MERGE語句是Oracle9i新增的語法,用來合並UPDATE和INSERT語句。通過MERGE語句,根據一張表或子查詢的連接條件對另外一張表進行查詢,連接條件匹配上的進行UPDATE,無法匹配的執行INSERT。這個語法僅需要一次全表掃描就完成了全部工作,執行效率要高於INSERT+UPDATE。

//表1
create table subs(msid number(9),
ms_type char(1),
areacode number(3)
);
//表2
create table acct(msid number(9),
bill_month number(6),
areacode number(3),
fee number(8,2) default 0.00);

//測試數據
insert into subs values(905310001,0,531);
insert into subs values(905320001,1,532);
insert into subs values(905330001,2,533);
commit;
一.下面先演示一下merge的基本功能
1) matched 和not matched clauses 同時使用
merge into acct a
using subs b on (a.msid=b.msid)
when MATCHED then
update set a.areacode=b.areacode
when NOT MATCHED then
insert(msid,bill_month,areacode)
values(b.msid,‘200702‘,b.areacode);
2) 只有not matched clause,也就是只插入不更新
merge into acct a
using subs b on (a.msid=b.msid)
when NOT MATCHED then
insert(msid,bill_month,areacode)
values(b.msid,‘200702‘,b.areacode);
3) 只有matched clause, 也就是只更新不插入
merge into acct a
using subs b on (a.msid=b.msid)
when MATCHED then
update set a.areacode=b.areacode

二.10g中增強一:條件操作
1) matched 和not matched clauses 同時使用
merge into acct a
using subs b on (a.msid=b.msid)
when MATCHED then
update set a.areacode=b.areacode
where b.ms_type=0
when NOT MATCHED then
insert(msid,bill_month,areacode)
values(b.msid,‘200702‘,b.areacode)
where b.ms_type=0;
2) 只有not matched clause,也就是只插入不更新
merge into acct a
using subs b on (a.msid=b.msid)
when NOT MATCHED then
insert(msid,bill_month,areacode)
values(b.msid,‘200702‘,b.areacode)
where b.ms_type=0;
3) 只有matched clause, 也就是只更新不插入
merge into acct a
using subs b on (a.msid=b.msid)
when MATCHED then
update set a.areacode=b.areacode
where b.ms_type=0;
三.10g中增強二:刪除操作
merge into acct a
using subs b on (a.msid=b.msid)
when MATCHED then
update set a.areacode=b.areacode
delete where (b.ms_type!=0);

註意:
1.MERGE語句的UPDATE不能修改用於連接的列,否則會報錯(on 後面的條件列就是聯接)
2.using 後面可以是(SELECT msid ,areacode FROM subs GROUP by msid )

Oracle 中MERGE語句的用法(轉載)