首页 新闻 会员 周边

转载:Oracle中Meger Into的用法

0
[待解决问题]

Oracle Meger into 函数
Oracle 在 9i 引入了 merge 命令, 通过这个 merge 能够在一个SQL 语句中对一个表同时执行 inserts 和 updates 操作。Merge into 可以实现用 B 表来更新 A 表数据(如果匹配上),如果 A 表中没有,则把 B 表的数据插入 A 表中。

管中窥豹

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 into new_products p using old_products op on (p.product_id = np.product_id) when matched then update set p.product_name = op.product_name when not matched then insert values( op.product_id, op.product_name, op.category)
使用 old_products 表中的输入插入 new_products 中,匹配关系为 on 后面的条件字句的内容。when matched then 就是根据匹配关系匹配上了,when not matched then 就是没有匹配上需要做的相应操作。网上的一般资料都显示在做 merge 的时候,这样同样的情况下,merge 的性能是优于同等功能的update/insert 语句的。

在Oracle 10g中MERGE有如下一些改进:
1、UPDATE 或 INSERT 子句是可选的
2、UPDATE 和 INSERT 子句可以加 WHERE 子句
3、UPDATE 子句后面可以跟 DELETE 子句来去除一些不需要的行

UPDATE 或 INSERT 子句是可选的

merge into new_products p using old_products op on (p.product_id = np.product_id) when matched then update set p.product_name = op.product_name
when matched then 和 when not matched then 都是可选则参数,可以根据具体的业务类型来进行数据库操作,而不用拘泥于原有特定的语法。

添加 WHERE 子句

merge into new_products p using old_products op on (p.product_id = np.product_id) when matched then update set p.product_name = op.product_name where op.name like '%co2fe%' when not matched then insert values( op.product_id, op.product_name, op.category) where op.name like '%co2fe%'
在添加了 where 条件之后我们的 update/insert 就会变得更加的灵活,能够满足更多的业务需求。

DELETE 子句来去除一些不需要的行

merge into new_products p using old_products op on (p.product_id = np.product_id) when matched then update set p.product_name = op.product_name delete where op.name like '%co2fe%' when not matched then insert values( op.product_id, op.product_name, op.category)
同样的,使用 delete 语句之后我们可以实现更多的功能和业务,扩展了 merge into 的使用面。

本文由个人 hexo 博客 co2fe.com 迁移
date: 2017-09-12 15:38:41

我是白小白的主页 我是白小白 | 菜鸟二级 | 园豆:202
提问于:2019-03-08 13:32
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册