Oracle merge into 通過一個表字段,更新另一個表字段


Oracle 通過一個表字段,更新另一個表字段:

方法一:通過update實現

update g_sn_status A
    set A.out_process_time = (select B.rec_time from g_sn_defect B where B.serial_number = A.serial_number and B.rp_status is null)
where A.serial_number in
(
    select distinct A.serial_number from g_sn_status A
    inner join g_sn_defect B on A.serial_number = B.serial_number
    where A.out_process_time <> B.rec_time and B.rp_status is null and A.process_id = B.process_id and A.current_status = 1
)

  如果沒有where約束部分,A表的out_process_time字段將會全部更新。【A表存在、B表不存在serial_number時,A表的out_process_time字段會更新成null】

 

方法二:通過merge into實現 

merge into g_sn_status A
    using g_sn_defect B on (A.serial_number = B.serial_number)
when matched then
    update set A.out_process_time = B.rec_time where A.serial_number like '2018%'
when not matched then
    insert (A.serial_number,A.out_process_time) values (B.serial_number,B.rec_time) where
 B.rec_time between to_date('2020051008','YYYYMMDDHH24') and to_date('2020052020','YYYYMMDDHH24');

作用:判斷B表和A表是否滿足ON中條件,如果滿足則用B表去更新A表,如果不滿足,則將B表數據插入A表但是有很多可選項,如下:
1.正常模式

2.只update或者只insert

3.帶條件的update或帶條件的insert

4.帶delete的update【雞肋,而且會增加SQL語言的復雜度】

  該SQL類似SQLPLUS的case when...語句,想想也知道為啥有很多可選項了。

 

總結:方法二雖然功能更強大,但是用的少。

 


免責聲明!

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



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