Oracle批量Update記錄
阿新 • • 發佈:2019-01-07
工作中經常用到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、正確的寫法:
正確的寫法,就是在後面加了一句where exists(select 1 from jayt2 t2 where t1.id=t2.id and t1.code <> t2.code);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);
這句話的意思是:如果存在t1.id=t2.id且t1.code <> t2.code,就更新,否則,不更新,所以不會導致t1表中所有的記錄都被更新。
總結:
update時,要弄清限定條件,要測試!