Oracle merge into 通过一个表字段,更新另一个表字段

时间:2024-04-17 20:32:18

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...语句,想想也知道为啥有很多可选项了。

 

总结:方法二虽然功能更强大,但是用的少。