Oracle merge into 详解(有则更新,无则插入)

1 概述

1.1 使用场景

  • 需求:源表 a 的数据 写入至 目标表 b 中
  • 规则
    • ① 若目标表 b 中 源表 a 的这条记录,则 更新
    • ② 若目标表 b 中 没有 源表 a 的这条记录,则 插入
  • 优势:执行效率高、语法简洁

1.2 常规写法

-- 如果不知道 merge into 这个语法,咱可能会这么写
select count(1)
  into v_count
  from ...;
 
if count(1) >= 1 then
   update ...; -- 有则更新
else
   insert ...; -- 无则插入

1.3 基础数据准备

-- 源表:source_table
create table source_table (
  sno   number(3),
  sname varchar2(30),
  sex   varchar2(2)
);

insert into source_table(sno, sname, sex) values(1, '瑶瑶', '女');
insert into source_table(sno, sname, sex) values(2, '优优', '男');
insert into source_table(sno, sname, sex) values(3, '倩倩', '女');
commit;

-- 目标表:target_table(仅表结构)
create table target_table as select * from source_table where 1 = 2;
insert into target_table (sno, sname, sex) values(1, '瑶瑶', '男');
commit;

2 示例

2.1 语法

merge into 目标表 b
using 源表 a
on (b.字段1 = a.字段1 and b.字段n = a.字段n) -- 必须带 '()'
when matched then -- 整体扫描,匹配时,执行此处
   update 子句
when not matched then -- 整体扫描,不匹配时,执行此处
   insert 子句;

commit; -- 记得提交哦

2.2 实操

实例: 将源表 source_table 的数据同步至目标表 target_table

merge into target_table b
using source_table a
on (b.sno = a.sno) -- 关联字段
when matched then
  update set b.sname = a.sname, b.sex = a.sex
when not matched then
  insert (b.sno, b.sname, b.sex) values (a.sno, a.sname, a.sex);

commit; -- 记得提交哦

查询结果:

select * from source_table t order by t.sno;
select * from target_table t order by t.sno;

在这里插入图片描述