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

ocacle中用一个表的数据更新另一个表的数据 有下面两个表:将表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中一条的情况也会出错.

如果select出的数据为上万条,效率很低,用下面方法

最好的方法是用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 

转自:http://www.2cto.com/database/201205/130987.html

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值