Oracle中用一個表的資料更新另一個表的資料
Oracle中用一個表的資料更新另一個表的資料
有下面兩個表:將表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]
merge into tab1
using tab2
on(tab1.id=tab2.id)
when matched then
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]
merge into tab1
using (select * FROM tab2 X WHERE X.ROWID =
(SELECT MAX(Y.ROWID) FROM tab2 Y WHERE X.ID = Y.ID)) tab2
on(tab1.id=tab2.id)
when matched then
update set tab1.val = tab2.val
轉http://soft.chinabyte.com/database/48/12342048.shtml