案列场景:更新员工表(sec.sec_staff)的short_name字段值,short_name的值由甲方人员提供(Excel表格)。为实现通过SQL修改,创建临时表sec.sec_staff_temp,sec.sec_staff表结构及Excel详细数据此处略过,sql如下:
--1.修改SQL update sec.sec_staff a set a.short_name = (select b.staffnew from sec.sec_staff_temp b where to_char(a.staff_id) = b.staffold) where exists (select b.staffold from sec.sec_staff_temp b where to_char(a.staff_id) = b.staffold); --2.校验修改行数 select count(1) from sec.sec_staff a,sec.sec_staff_temp b where to_char(a.staff_id) = to_char(b.staffold); --3.对比差异数据 select b.staffnew,b.staffold from sec.sec_staff_temp b left join sec.sec_staff a on b.staffold = to_char(a.staff_id);
SQL详解:
T1表 结构
id name school
1 ming1 清华大学
2 ming2 北京大学
3 ming3 复旦大学
T2表 结构
id student school
11 ming1 牛津大学
12 ming3 剑桥大学
T1表的name 和 T2表的 student 值是 1对1 的对应。
需求:这两个字段的值相同时,根据B表的school更新A表的school。
语句:
update t1 set school = (select school from t2 where name=student) where exists (select * from t2 as b where name = b.student);
结果:
T1表 结构
id name school
1 ming1 牛津大学
2 ming2 北京大学
3 ming3 剑桥大学