【轉載】oracle更新語法

魔豆發表於2017-06-30

oracle更新語法:
1.一般語法
   update tab set col = .... [where ...]   =後可以有子查詢,但是必須對於tab的每一列返回唯一一行與之對應,where是需要更新的表,部分更新必須加,否則相關子查詢的更新會把沒有匹配的更新為null,如
  update tab a set a.col=(select b.col from b where a.id=b.id) where exists (select 1 from b where a.id=b.id) 類似地寫了多遍

2.改進語法merge
  merge into tab
  using (表|檢視|子查詢等)  --子查詢需要加括號  on (條件)
  when match then
   do update
  when no match then
  do insert                               

insert語法和update語法有所不同,詳細參考文件,10g還支援update,insert的有條件更新和插入,支援update的delete where,支援只有update或insert的
不能修改using裡的關聯列,同樣,必須每一行有唯一與之對應的

上面兩種語法如果找不到唯一對應的,需要改進語句,比如加rownum=1

3.update inline view的用法
   update (select ...........關聯查詢) set 目標=源
  如 update(select a.name,b.name from a,b where a.id=b.id) set a.name=b.name;
      需要unique建保證唯一對應,比如上面的必須要b.id有唯一鍵,也就是preserved key,比如唯一索引什麼的都可以,11g之前可以用hint: bypass_ujvc,這樣不需要唯一鍵,但是可能有問題,一對多會更新多次,11g這個hint失效
  delete (select ....) 也可以,有很多要求,可以看sql文件,insert (select ...)限制更多
  第3種方法來源於可更新的檢視


oracle更新基本有3種sql寫法,後面兩種往往優化中會使用到,特別第一種的更新關聯子查詢中源表不走索引,那麼更新很多,相當於 nested loop,肯定慢,而且還有個where過濾,多次訪問源表

相關文章