oracle数据库Merge应用

本文详细介绍了 Oracle 数据库中 MERGE 语句的使用方法及其变种写法,包括如何实现根据条件更新或插入记录,以及如何添加条件操作和删除操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


应用场景:

单张表

不知道数据库中是否存在要插入的数据,如果存在,则对其进行update,不存在,则进行insert操作。

示例:

MERGE INTO WX_MENU T1
USING (SELECT * FROM dual) T2
ON (T1.BANKCODE = '3004' AND T1.MENU_KEY = 'menu_subscribe')

WHEN MATCHED THEN
  UPDATE SET COMMENTS = '关注事件的图文推送'
WHEN NOT MATCHED THEN
insert
    (BANKCODE, MENU_KEY, COMMENTS)
  values
    ('3004', 'menu_subscribe', '关注事件的图文推送');


语法如下
MERGE INTO [your table-name] [rename your table here] 
	USING ( [write your query here] )[rename your query-sql and using just like a table] 
	ON ([conditional expression here] AND [...]...) 
WHEN MATHED 
	THEN [here you can execute some update sql or something else ] 
WHEN NOT MATHED 
	THEN [execute something else here ! ] 


Merge解说:

merge语法是根据源表对目标表进行匹配查询,匹配成功时更新,不成功时插入。

其基本语法规则是:

merge into 目标表 a

using 源表 b

on(a.条件字段1=b.条件字段1 and a.条件字段2=b.条件字段2 ……)  

when matched then update set a.更新字段=b.字段

when  not macthed then insert into a(字段1,字段2……)values(值1,值2……)

变种写法①,只更新:

merge into 目标表 a

using 源表 b

on(a.条件字段1=b.条件字段1 and a.条件字段2=b.条件字段2 ……)  

when matched then update set a.更新字段=b.字段,a.更新字段2=b.字段2……

变种写法②,只插入:

merge into 目标表 a

using 源表 b

on(a.条件字段1=b.条件字段1 and a.条件字段2=b.条件字段2 ……)  

when  not macthed then insert into a(字段1,字段2……)values(值1,值2……)

注:条件字段不可更新

对于Oracle来说,merge是9i新增的语法,在10g进行了一些增强,如下:

测试环境:Oracle Database 11g Enterprise Edition Release 11.2.0.1.0

①条件操作:

merge into 目标表 a

using 源表 b

on(a.条件字段1=b.条件字段1 and a.条件字段2=b.条件字段2 ……)  

when matched then update set a.更新字段=b.字段  where 限制条件

when  not macthed then insert into a(字段1,字段2……)values(值1,值2……) where 限制条件

举例:

merge into test_merge a
using test b
on(a.no=b.no)
when matched then update set a.no2=b.no2 where a.no<>1
when not matched then insert values(b.no,b.no2)  where a.no<>100

当然也支持变种①②的写法

②删除操作

merge into 目标表 a

using 源表 b

on(a.条件字段1=b.条件字段1 and a.条件字段2=b.条件字段2 ……)  

when matched then update set a.更新字段=b.字段

delete where b.字段=xxx

举例:

merge into test_merge a
using test b
on(a.no=b.no)
when matched then update set a.no2=b.no2 where a.no<>1
delete 
where b.no=14

备注:删除动作针对的也是目标表,并且必须在语句最后

基本上merge的用法就是以上这些,建议平常可以多用,比单独的update+insert的方式效率要更高,尤其是on条件下有唯一索引的时候,效率更高


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值