https://blog.csdn.net/qq_34745941/article/details/81176140?utm_source=copy
1. 适用场景:'有则更新,无则插入' 2. 好处 (1) 执行 '效率高' (2) 语法简洁 3. 如果不知道 merge into 这个语法,咱可能会这么写 select count(1) into v_count from ...; if count(1) >= 1 then update ...; -- 有则更新 else insert ...; -- 无则插入 123456789101112131415
基础数据准备:
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; -- 目标表(表结构) create table target_table as select * from source_table where 1 = 2; 12345678910111213
merge into 目标表 b using 源表 a on (b.字段1 = a.字段1 and b.字段n = a.字段n) -- 必须带 '()' when matched then -- 整体扫描,匹配时,执行此处 update 子句 when not matched then -- 整体扫描,不匹配时,执行此处 insert 子句; 1234567
实例: 将源表 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; -- 记得提交哦 123456789
查询结果:
提示:咱也可以改变源表 source_table 的记录,测试同步后目标表 target_table 的变化哦
update source_table t set t.sname = 'aa' where t.sno = 1; commit; 12
符合某个条件时,修改A表数据, 根据B表的数据 。等同于 根据 pid 把B表数据拿出来 插入到A表pid 的行。