sql - 在“当匹配时”上使用插入和更新 // 合并
问题描述
是否可以在 上使用 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);
解决方案
- 匹配 -> 更新/删除
- 不匹配 -> 插入
不允许混合。
所以你想在 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)
推荐阅读
- python - 在 AzureML 中部署模型时如何将参数传递给评分文件
- c# - 我在 jquery 数据表中有重复的行问题
- javascript - 使用 MediaRecorder 将文件另存为 GIF
- xamarin - 如何在 Xamarin.ios 本机应用程序上验证 Microsoft Auth 以获得对 MS 帐户的访问权限?
- sql - SQL 连接语句中的列顺序是否重要?
- android - 样式谷歌登录按钮?
- algorithm - 数值微分算法中没有除法
- r - 删除 R 表中自动生成的索引行号
- git - 詹金斯删除 bin\ssh.exe
- xamarin.forms - Xamarin Forms - 每 10 秒获取一次设备位置(当应用程序在前台/后台运行时)