最近更新数据用到upate set from
查资料才知道oracle中没有此写法,所以只能变通。
网上的帖子这样写:
1) 最简单的形式
- --经确认customers表中所有customer_id小于1000均为'北京'
- --1000以内的均是公司走向全国之前的本城市的老客户:)
- update customers
- set city_name='北京'
- where customer_id<1000
2) 两表(多表)关联update -- 仅在where字句中的连接
- --这次提取的数据都是VIP,且包括新增的,所以顺便更新客户类别
- update customers a -- 使用别名
- set customer_type='01' --01 为vip,00为普通
- where exists (select 1
- from tmp_cust_city b
- where b.customer_id=a.customer_id
- )
3) 两表(多表)关联update -- 被修改值由另一个表运算而来
- update customers a -- 使用别名
- set city_name=(select b.city_name from tmp_cust_city b where b.customer_id=a.customer_id)
- where exists (select 1
- from tmp_cust_city b
- where b.customer_id=a.customer_id
- )
- -- update 超过2个值
- update customers a -- 使用别名
- set (city_name,customer_type)=(select b.city_name,b.customer_type
- from tmp_cust_city b
- where b.customer_id=a.customer_id)
- where exists (select 1
- from tmp_cust_city b
- where b.customer_id=a.customer_id
- )
注意在这个语句中,
=(select b.city_name,b.customer_type from tmp_cust_city b
where b.customer_id=a.customer_id )
与
(select 1 from tmp_cust_city b
where b.customer_id=a.customer_id)
是两个独立的子查询,查看执行计划可知,对b表/索引扫描了2篇;
如果舍弃where条件,则默认对A表进行全表
更新,但由于
- select b.city_name from tmp_cust_city b where b.customer_id=a.customer_id
有可能不能提供"足够多"值,因为tmp_cust_city只是一部分客户的信息,所以报错(如果指定的列--city_name可以为NULL则另当别论):
- 01407, 00000, "cannot update (%s) to NULL"
- // *Cause:
- // *Action:
一个替代的方法可以采用:
- update customers a -- 使用别名
- set city_name=nvl((select b.city_name from tmp_cust_city b where b.customer_id=a.customer_id),a.city_name)
或者
- set city_name=nvl((select b.city_name from tmp_cust_city b where b.customer_id=a.customer_id),'未知')
--以上写法我试了一下,总是行不通,报子查询返回多行的值 错误。无奈只能用游标这种写法。
以下游标的写法,需要在sql plus command windows 中执行,普通的SQL窗口执行报错。切记
4) 上述3)在一些情况下,因为B表的纪录只有A表的20-30%的纪录数,
考虑A表使用INDEX的情况,使用cursor也许会比关联update带来更好的性能:
- set serveroutput on
- declare
- cursor city_cur is
- select customer_id,city_name
- from tmp_cust_city
- order by customer_id;
- begin
- for my_cur in city_cur loop
- update customers
- set city_name=my_cur.city_name
- where customer_id=my_cur.customer_id;
- /** 此处也可以单条/分批次提交,避免锁表情况 **/
- -- if mod(city_cur%rowcount,10000)=0 then
- -- dbms_output.put_line('----');
- -- commit;
- -- end if;
- end loop;
- end;