1. 程式人生 > >ORACLE UPDATE FROM 寫法變通

ORACLE UPDATE FROM 寫法變通

最近更新資料用到upate set from 

查資料才知道oracle中沒有此寫法,所以只能變通。

網上的帖子這樣寫:

1) 最簡單的形式

SQL 程式碼
  1. --經確認customers表中所有customer_id小於1000均為'北京'
  2. --1000以內的均是公司走向全國之前的本城市的老客戶:)
  3. update customers
  4. set city_name='北京'
  5. where customer_id<1000

2) 兩表(多表)關聯update -- 僅在where字句中的連線

SQL 程式碼
  1. --這次提取的資料都是VIP,且包括新增的,所以順便更新客戶類別
  2. update customers a -- 使用別名
  3. set customer_type='01' --01 為vip,00為普通
  4. where exists (select 1
  5. from tmp_cust_city b
  6. where b.customer_id=a.customer_id
  7. )

3) 兩表(多表)關聯update -- 被修改值由另一個表運算而來

SQL 程式碼
  1. update customers a -- 使用別名
  2. set city_name=(select b.city_name from tmp_cust_city b where b.customer_id=a.customer_id)
  3. where exists (select
     1
  4. from tmp_cust_city b
  5. where b.customer_id=a.customer_id
  6. )
  7. -- update 超過2個值
  8. update customers a -- 使用別名
  9. set (city_name,customer_type)=(select b.city_name,b.customer_type
  10. from tmp_cust_city b
  11. where b.customer_id=a.customer_id)
  12. where exists (select 1
  13. from tmp_cust_city b
  14. where b.customer_id=a.customer_id
  15. )

注意在這個語句中,
=(
select b.city_name,b.customer_type from tmp_cust_city b
where b.customer_id=a.customer_id )

(
select from tmp_cust_city b
where b.customer_id=a.customer_id)
是兩個獨立的子查詢,檢視執行計劃可知,對b表/索引掃描了
2篇;
如果捨棄
where條件,則預設對A表進行全表
更新,但由於

SQL 程式碼
  1. select b.city_name from tmp_cust_city b where b.customer_id=a.customer_id

有可能不能提供"足夠多"值,因為tmp_cust_city只是一部分客戶的資訊,所以報錯(如果指定的列--city_name可以為NULL則另當別論):

SQL 程式碼
  1. 01407, 00000, "cannot update (%s) to NULL"
  2. // *Cause:
  3. // *Action:

一個替代的方法可以採用:

SQL 程式碼
  1. update customers a -- 使用別名
  2. set city_name=nvl((select b.city_name from tmp_cust_city b where b.customer_id=a.customer_id),a.city_name)

或者

SQL 程式碼
  1. 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帶來更好的效能:

SQL 程式碼
  1. set serveroutput on
  2. declare
  3. cursor city_cur is
  4. select customer_id,city_name
  5. from tmp_cust_city
  6. order by customer_id;
  7. begin
  8. for my_cur in city_cur loop
  9. update customers
  10. set city_name=my_cur.city_name
  11. where customer_id=my_cur.customer_id;
  12. /** 此處也可以單條/分批次提交,避免鎖表情況 **/
  13. -- if mod(city_cur%rowcount,10000)=0 then
  14. -- dbms_output.put_line('----');
  15. -- commit;
  16. -- end if;
  17. end loop;
  18. end;