oracle中更新關鍵字merge和 with as關鍵字


merge是oracle特有的語句,兩表關聯操作(增、刪、改)就效率非常高

merge into table_name alias1 
using (table|view|sub_query) alias2
on (join condition) 
when matched then 
    update table_name 
    set col1 = col_val1,
col2 = col2_val
when not matched then insert ( column_list ) values (
    column_values
);

 

它的原理是在alias2中Select出來的數據,每一條都跟alias1進行 ON (join condition)的比較,如果匹配,就進行更新的操作(Update),如果不匹配,就進行插入操作(Insert)。執行merge不會返回影響的行數。Merge語句的寫法比較繁瑣,並且最多只能兩個表關聯,復雜的語句用merge更新法將力不從心且效率差。

也可以使用快速游標更新法

begin
for cr in (查詢語句) loop –-循環
   --更新語句(根據查詢出來的結果集合)
endloop; --結束循環
end;

oracle支持快速游標,不需要定義直接把游標寫到for循環中,這樣就方便了我們批量更新數據。再加上oracle的rowid物理字段(oracle默認給每個表都有rowid這個字段,並且是唯一索引),可以快速定位到要更新的記錄上。

 

 

with as 

with
cr as
(
    select CountryRegionCode from person.CountryRegion where Name like 'C%'
)
select * from person.CountryRegion  -- 應將這條SQL語句去掉
-- 使用CTE的SQL語句應緊跟在相關的CTE后面 --
select * from person.StateProvince where CountryRegionCode in (select * from cr)

這里可以將cr看做是一個視圖名。十分方便平時在工作中進行操作。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM