Oracle批量Update记录

工作中经常用到Oracle批量更新记录,做为老手也怕出错,总之要小心再小心,确保数据批量更新正确。

下面举一个例子:

1、创建两张结构类似的表,建表语句如下:

create table jayt1(
       id int,
       code varchar2(8)
);

create table jayt2(
       id int,
       code varchar2(8)
);
2、初始化数据,语句如下:

insert into jayt1 values(1,'1');
insert into jayt1 values(2,'B');
insert into jayt1 values(3,'3');
insert into jayt1 values(4,'4');

insert into jayt2 values(1,'A');
insert into jayt2 values(2,'B');
insert into jayt2 values(3,'C');
commit;

3、需求是这样的,通过jayt2表来更新jayt1表的code字段

A、错误的写法:

update jayt1 t1 set (id,code)=( select id,code from jayt2 t2 where t1.id=t2.id); 
这种写法,会更新t1表中的所有行:如果t1.id=t2.id,就更新t2中查出的记录进t1;如果t1.id<>t2.id,t1中的记录会被更新成空(null)。

更新结果如下,显示不是我们需要的。


B、正确的写法:

update jayt1 t1 
set (id,code)=( select id,code from jayt2 t2 where t1.id=t2.id) 
where exists(select 1 from jayt2 t2 where t1.id=t2.id and t1.code <> t2.code);  
正确的写法,就是在后面加了一句 where exists(select 1 from jayt2 t2 where t1.id=t2.id and t1.code <> t2.code);  
这句话的意思是:如果存在t1.id=t2.id且t1.code <> t2.code,就更新,否则,不更新,所以不会导致t1表中所有的记录都被更新。


总结:
update时,要弄清限定条件,要测试!


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值