Oracle 中MERGE語句的用法____Oracle

來源:互聯網
上載者:User

       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 )

 

 【轉載】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.