Merge into函数用法详解及示例
(2017-03-28 09:26:32)
标签:
mergeinto用法详解oracle中merge用法oracle中merge示例mergeinto示例mergeinto用法 |
分类: Oracle数据库 |
一、merge函数语法
语法如下:
merge into [your table-name][rename your
table
here]
using ([write your query here] )[rename your
query-sql and using just like a table]
when not mathed then
二、在Oracle9i中使用示例
1、a表和b表比对匹配,进行更新和插入数据操作
merge into tmp_prod a
using tmp_prod_new b
on (a.product_id = b.product_id)
when matched then
when not matched then
示例说明:
update set a.product_name = b.product_name,
很显然就是把newproduct里的内容,赋值到product的product_name里。
2、b表采用视图或子查询
我们也可以在using后面使用视图或者子查询。比如我们把tmp_prod_new换成(select * from
tmp_prod_new),也是可以的。
merge into tmp_prod a
using (select * from tmp_prod_new) b
on (a.product_id = b.product_id)
when matched then
when not matched then
三、在Oracle 10g中特性及示例
在Oracle 10g中merge有如下一些改进:
1.update或insert子句是可选的;
2.update和insert子句可以加where子句;
3.在on条件中使用常量过滤谓词来insert所有的行到目标表中,不需要连接源表和目标表;
4.update子句后面可以跟delete子句来去除一些不需要的行。
我们通过实例,来看看如上的新特性:
1、update或insert子句是可选的
merge into tmp_prod a
using tmp_prod_new b
on (a.product_id = b.product_id)
when matched then
2、update和insert子句可以加where子句
merge into tmp_prod a
using (select * from tmp_prod_new) b
on (a.product_id = b.product_id)
when matched then
where b.product_name='book'
示例说明:
merge into tmp_prod a
using (select * from tmp_prod_new) b
on (a.product_id = b.product_id)
when matched then
when not matched then
这里注意比较一下,他们返回的结果行数,是有着差异的。
3、在on条件中使用常量过滤谓词来insert所有的行到目标表中,不需要连接源表和目标表
merge into tmp_prod a
using (select * from tmp_prod_new) b
on (1=0)
when matched then
when not matched then
个人觉得这个功能意义不大,我们的insert into本身就支持这样的功能,没有必要使用merge。
4、update子句后面可以跟delete子句来删除一些不需要的记录行
delete只能和update配合,从而达到删除满足where条件的子句的纪录
merge into tmp_prod a
using (select * from tmp_prod_new) b
on (a.product_id = b.product_id)
when matched then
when not matched then
示例说明:
这里我们达到的目的就是会把匹配的记录的prodcut_name更新到product里,并且把product_name中为'book'的删除掉。
四、总结
merge into 也是一个dml语句,和其他的dml语句一样需要通过rollback和commit
结束事务。
merge是一个非常强大的函数,在我们的日常的数据处理需求中经常会用到,希望大家在以后的工作中熟能生巧。
本文参考资料:https://wenku.baidu.com/view/e6f63d15964bcf84b9d57bcc.html
前一篇:Oracle 生成随机码详解

加载中…