日期:2014-05-16  浏览次数:20390 次

Oracle MERGE INTO的使用

在时常操作数据库,我们会有一个批量的增量更新的动作。

一般来说,我们使用游标。

create cursor ....

然后读取每一条记录,看看表里面有没有记录,没有记录就插入,有记录就更新。

可是游标操作的效率让人凌乱。

?

于是乎,DB2和Oracle都支持的MERGE INTO语句发挥了用处。

?

先看一段代码。

  select depart, arrive, price from fares;

  merge into fares t
  using (select 'NJC' DEPART, 'CAN' ARRIVE, 1500 price from dual) tmp
  on (t.depart = tmp.depart
      and t.arrive = tmp.arrive)
  when matched then
    update set t.price = tmp.price
  when not matched then
    insert values (tmp.depart, tmp.arrive, tmp.price)
  ;

?

MERGE INTO语句的基本使用方式非常简单。

也就是将一个结果集与目标表进行合并。

也就是MERGE这个单词的意思。

?

那么目标表与结果集之间怎么构建关系呢?

看ON。

将2个结合进行表连接的方式进行匹配。

当匹配条件成功,就更新。

当匹配条件不成功,就插入。

?

例子中是一条数据的情况,如果是查询表格呢?

其实是一样的:

merge into fares t
  using (select DEPART, ARRIVE, price from my_table) tmp
  on (t.depart = tmp.depart
      and t.arrive = tmp.arrive)
  when matched then
    update set t.price = tmp.price
  when not matched then
    insert values (tmp.depart, tmp.arrive, tmp.price)
  ;

?

?