Oracle 中用一個表的資料更新另一個表的資料

來源:互聯網
上載者:User

標籤:

Oracle 中用一個表的資料更新另一個表的資料分類: SQL/PLSQL2012-05-04 15:49 4153人閱讀 評論(1) 收藏 舉報oraclemergesubqueryinsertnull

 

有下面兩個表:將表tab1中id值與和表tab2中id值相同的行的val更新為tab2中val的值.
select * from tab1;

 

select * from tab2

 

最容易犯的錯誤是:update tab1 set val=(select val from tab2 where tab1.id=tab2.id);
更新完後的結果是:select * from tab1,在tab1中有的行,如果在tab2中沒有對應的行,值被更新為null

 

改正為:update tab1 set val=(select val from tab2 where tab1.id=tab2.id)
where exists (select 1 from tab2 where tab1.id=tab2.id)
但是如果tab2中有多條對應tab1中一條的情況也會出錯.
最好的方法是用merge文法:
[sql] view plaincopy 
  1. merge into tab1  
  2. using tab2  
  3. on(tab1.id=tab2.id)  
  4. when matched then  
  5. update set tab1.val = tab2.val  
同樣,如果tab2中有多條對應tab1中一條的情況也會出錯:ORA-30926: unable to get a stable set of rows in the source tables
比如在tab2中再插入一條 insert into tab2 values(2,‘xxxx‘)
可以通過在using中的subquery中將重複記錄過濾來避免這種錯誤,merge終極版:
[sql] view plaincopy 
  1. merge into tab1  
  2. using  (select * FROM tab2 X  WHERE  X.ROWID =  
  3. (SELECT MAX(Y.ROWID) FROM  tab2 Y  WHERE  X.ID = Y.ID)) tab2  
  4. on(tab1.id=tab2.id)  
  5. when matched then  
  6. update set tab1.val = tab2.val  

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Oracle 中用一個表的資料更新另一個表的資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.