Oracle 的 merge 更新和插入操作

来源:互联网 发布:json对象转成java对象 编辑:程序博客网 时间:2024/06/04 19:44
使用merge比传统的先判断再选择插入或更新快很多。
1)主要功能
提供有条件地更新和插入数据到数据库表中
如果该行存在,执行一个UPDATE操作,如果是一个新行,执行INSERT操作
    — 避免了分开更新
    — 提高性能并易于使用
    — 在数据仓库应用中十分有用

2)MERGE语句的语法如下:

MERGE [hint] INTO [schema .] table [t_alias] USING [schema .]

{ table | view | subquery } [t_alias] ON ( condition )

WHEN MATCHED THEN merge_update_clause

WHEN NOT MATCHED THEN merge_insert_clause;

3)使用merge的注意事项:on子句的使用的字段不能够用于update,即Oracle不允许更新用于连接的列。
 
4)实例如下:
首先,我们创建一个测试表(create table t_userobject as select object_id,object_name from user_objects where rownum<=100),然后通过merge的方式来维护该表的数据。根据object_id来匹配,能匹配上的,若object_name 不同(本例中不可能有该情况),则更新object_name;不能匹配上的,则直接新增该记录。从而达到批量INSERT和UPDATE操作。
merge into t_userobject t
using (select object_id, object_name from user_objects) s
on (t.object_id = s.object_id)
when matched then
  update
     set t.object_name = s.object_name
   where t.object_name != s.object_name
when not matched then
  INSERT (object_id, object_name) VALUES (s.object_id, s.object_name);
 
 
 
merge into test t
using (select id,xm from aaa) s
on (t.id=s.id)
when matched then
update
set t.xm=s.xm
where t.xm!=s.xm
when not matched then
insert (id,xm) values (s.id,s.xm);
commit;
0 0