2024年4月28日发(作者:)

Merge是一个非常有用的功能,类似于Mysql里的insert into on duplicate key.

Oracle在9i引入了merge命令,

通过这个merge你能够在一个SQL语句中对一个表同时执行inserts和updates操

作. 当然是update还是insert是依据于你的指定的条件判断的,Merge into可以实现用

B表来更新A表数据,如果A表中没有,则把B表的数据插入A表. MERGE命令从一个

或多个数据源中选择行来updating或inserting到一个或多个表

语法如下

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的用法

merge into products p using newproducts np on (t_id =

t_id)

when matched then

update set t_name = t_name

when not matched then

insert values(t_id, t_name, ry)

在这个例子里。前面的merger into products using newproducts 表示的用

newproducts表来merge到products表,merge的匹配关系就是on后面的条件子句

的内容,这里根据两个表的product_id来进行匹配,那么匹配上了我们的操作是就是when

matched then的子句里的动作了,这里的动作是update set t_name =

t_name, 很显然就是把newproduct里的内容,赋值到product的

product_name里。如果没有匹配上则insert这样的一条语句进去。 大家看看这个merget

inot的用法是不是一目了然了呀。这里merger的功能,好比比较,然后选择更新或者是

插入,是一系列的组合拳,在做merge的时候,这样同样的情况下,merge的性能是优

于同等功能的update/insert语句的。有人曾经分析merge是批量处理对性能贡献很大,

个人觉得这个是没有考据的。

我们也可以在using后面使用视图或者子查询。比如我们把newproducts换成

merge into products p using (select * from newproducts) np on (t_id

= t_id)