工作中经常用到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时,要弄清限定条件,要测试!