首页 > 解决方案 > 在“当匹配时”上使用插入和更新 // 合并

问题描述

是否可以在 上使用 INSERT 和 UPDATE When matched then?? 我在网上看到它是可能的所以我的问题是:我怎样才能做类似下面的事情?

create table target_table(a, b, c, d, e) as (
   select 1, 2, 'NO',  100,'MDE' from dual union all
   select 1, 3, 'NO',  100,'AGC' from dual union all
   select 1, 4, 'NO',  100,'MDE' from dual union all
   select 1, 6, 'YES',  100,'MDE' from dual union all
   select 1, 5, 'NO',  100,'MDE' from dual );


create table source_table(a, b, c, d, e) as (
   select 1, 0, 'NO',  200,'AGC'  from dual union all
   select 1, 1, 'NO',  200,'MDE'  from dual union all
   select 1, 3, 'YES', 200,'AGC'  from dual union all
   select 1, 4, 'NO',  200,'MDE'  from dual union all
   select 1, 5, 'YES', 200,'MDE'  from dual );


merge into target_table t
using source_table s
on (t.a = s.a and t.b = s.b)
when matched then 
case 
      when t.c = 'NO' and s.c = 'YES' and t.e = 'MDE' and s.e = 'MDE' then update set t.d = s.d, t.c = s.c
      when t.e <> 'MDE' and s.e <> 'MDE' then insert values (s.a, s.b, s.c, s.d, s.e)
end 
when not matched then insert values (s.a, s.b, s.c, s.d, s.e);

标签: sqloracle

解决方案


让我们整理一下。首先https://docs.oracle.com/en/database/oracle/oracle-database/12.2/sqlrf/MERGE.html#GUID-5692CCB7-24D9-4C0E-81A7-A22436DC968F

  • 匹配 -> 更新/删除
  • 不匹配 -> 插入

不允许混合。

所以你想在 te 和 se 为 != 'MDE' 或 (ta = sa and tb = sb) 时插入并且仅在 tc = 'NO' 和 sc = 'YES' 和 te = 'MDE' 和 se = 时更新'MDE'

所以你尝试过:

merge into target_table t
using source_table s
on (t.a = s.a and t.b = s.b and not ( t.e <> 'MDE' and s.e <> 'MDE'))
when matched then 
    update set t.d = s.d, t.c = s.c 
    where t.c = 'NO' and s.c = 'YES' and t.e = 'MDE' and s.e = 'MDE' 
when not matched then insert values (s.a, s.b, s.c, s.d, s.e)

推荐阅读