不朽
不朽
发布于 2023-08-18 / 16 阅读
0
0

orcale 中 merge into

1.orcale 中 merge into

使用的是oracle数据库。对于merge into 的主要功能就是合并 insert into 以及update。如果存在即update、不存在 insert into。

2.merge into 语法

1.做添加也做修改

merge into 目标表 A
using 源表 B
on(A.条件1 = B.条件1 ) --可多个条件 and连接
when matched then --如果条件匹配就 update
update
set A.字段1 = B.字段1,
A.字段2 = B.字段2
when not matched then --不匹配就insert
insert values (B.字段1,B.字段2)

2.仅添加

merge into 目标表 A
using 源表 B
on(A.条件1 = B.条件1 ) --可多个条件 and连接
when not matched then --不匹配就insert
insert values (B.字段1,B.字段2)

3.仅修改

merge into 目标表 A
using 源表 B
on(A.条件1 = B.条件1 ) --可多个条件 and连接
when matched then --如果条件匹配就 update
update
set A.字段1 = B.字段1,
A.字段2 = B.字段2

4.扩展

当然,UPDATE和INSERT子句可以加WHERE子句(没贴代码),也可以在update后面跟进delete去除。delete只能和update配合,如:

merge into 目标表 A
using 源表 B
on(A.条件1 = B.条件1 ) --可多个条件 and连接
when matched then --如果条件匹配就 update
update
set A.字段1 = B.字段1
delete
where B.字段2 =’???’
-- 匹配的记录的 B.字段1 更新到 A.字段1 里,并且把 B.字段2 等于 ??? 删除掉
​

3.merge into 注意事项

  • 1.在update中的字段,不可以出现在on子句的条件中

  • 2.update和insert子句中可以不用写表名

  • 3、在一个同时存在Insert和Update语法的Merge语句中,总共Insert/Update的记录数,就是Using语句中alias2的记录数 4.源表中作为条件项的不能重复。(否则会报 ‘无法在源中获得一组稳定的行’


评论