Chinaunix首页 | 论坛 | 博客
  • 博客访问: 72231
  • 博文数量: 25
  • 博客积分: 2000
  • 博客等级: 大尉
  • 技术积分: 215
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-08 09:35
文章分类

全部博文(25)

文章存档

2011年(1)

2009年(18)

2008年(6)

我的朋友

分类: Oracle

2009-02-20 09:35:22

使用Merge Into可以让你实现如下功能:
   
     在插入数据时,如果目标数据表中,该数据已经存在(当然是指某些字段值相同),则执行更新操作,否则执行插入操作。

Merge Into的这个强大功能,常常用于两个数据表之间的数据同步。

使用示例:

   table_1(id,c1,c2,c3,c4);
   table_2(id,c1,c2,c3,c4);

Merge Into table_2 t2
using (select id,c1,c2,c3,c4 from table_1) t1
   on (t2.c1 = t1.c1 and t2.c2 = t1.c2)
when matched then
     update set t2.c3 = t1.c3
when not matched then
     insert (t2.id,t2.c1,t2.c2,t2.c3,t2.c4)
     values (t1.id,t1.c1,t1.c2,t1.c3,t1.c4)

注意,这里不能更新on条件中使用到的字段。
另外,可以使用常量过滤器on(0=1),来实现无条件插入所有源数据。

补充:
   --update部分可以包含一个delete子句(有自己的where子句),用来删除符合on条件并且被update后的、并且符合delete自带where子句的过滤条件的行。
   
Merge Into table_2 t2
using (select id,c1,c2,c3,c4 from table_1) t1
   on (t2.c1 = t1.c1 and t2.c2 = t1.c2)
when matched then
     update set t2.c3 = t1.c3
     delete where (t2.c4 is null)
when not matched then
     insert (t2.id,t2.c1,t2.c2,t2.c3,t2.c4)
     values (t1.id,t1.c1,t1.c2,t1.c3,t1.c4)
阅读(1285) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~