打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Oracle 中用一个表的数据更新另一个表的数据

Oracle 中用一个表的数据更新另一个表的数据
 
Oracle有下面两个表:将表tab1中id值与和表tab2中id值相同的行的val更新为tab2中val的值.
select * from tab1;

id  val
1  x11
2  x12
2  x12

select * from tab2
id  val
2  x22
3  x23

 

最容易犯的错误是:update tab1 set val=(select val from tab2 where tab1.id=tab2.id);
更新完后的结果是:select * from tab1,在tab1中有的行,如果在tab2中没有对应的行,值被更新为null

id  val
1  
2  x22
2  x22

改正为: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语法:
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终极版:
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 

本篇文章来源于 Linux公社网站(www.linuxidc.com)  原文链接:http://www.linuxidc.com/Linux/2012-05/59698.htm

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
oracle merge into用法及例子
数据查询中取前几行,网上收集而来。
Oracle merge into的优势
Merge Into 语句代替Insert/Update在Oracle中的应用实战
Oracle 把一个表中的数据插入到另外一个表中
Sql Server2005 实现Oracle10g的hash表分区功能
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服