ITPub博客

首页 > Linux操作系统 > Linux操作系统 > Oracle 的 merge 更新和插入操作

Oracle 的 merge 更新和插入操作

原创 Linux操作系统 作者:xz43 时间:2011-01-14 14:01:32 0 删除 编辑
使用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);

 

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/9399028/viewspace-683827/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
鱼儿的学习空间

注册时间:2010-11-16

  • 博文量
    433
  • 访问量
    1863733