merge的使用

工作中,又遇到了merge这一个SQL用法

 

这是在oracle9i后才出现的用法

 

【介绍】

根据 源表 对 目标表 进行 匹配查询

匹配 --> 更新

不匹配 --> 插入

 

(个人理解: 就类似于去对比 两个表之间 , 有没有存在某个共同的字段{这个字段有特殊的含义,比如是代表着两个表都是员工的信息表},

如果存在(即匹配),那就将对于此表进行更新;

如果不存在(即不匹配),那就代表它们两个表没有共同点,那就只能针对某个地方进行插入)

 

【用法】

merge into 目标表 a

using 源表 b

on(a.条件字段1=b.条件字段1 and a.条件字段2=b.条件字段2 ……)  

when matched then update set a.更新字段=b.字段

when  not macthed then insert into a(字段1,字段2……)values(值1,值2……)

 

【变更用法】

- 只操作更新

 

merge into 目标表 a

using 源表 b

on(a.条件字段1=b.条件字段1 and a.条件字段2=b.条件字段2 ……)  

when matched then update set a.更新字段=b.字段

 

- 只操作插入

merge into 目标表 a

using 源表 b

on(a.条件字段1=b.条件字段1 and a.条件字段2=b.条件字段2 ……)  

when  not macthed then insert into a(字段1,字段2……)values(值1,值2……)

注:条件字段不可更新

 

【Oracle10g后加强用法】

-

merge into 目标表 a

using 源表 b

on(a.条件字段1=b.条件字段1 and a.条件字段2=b.条件字段2 ……)  

when matched then update set a.更新字段=b.字段  where 限制条件

when  not macthed then insert into a(字段1,字段2……)values(值1,值2……) where 限制条件

举例:

merge into test_merge a
using test b
on(a.no=b.no)
when matched then update set a.no2=b.no2 where a.no<>1
when not matched then insert values(b.no,b.no2)  where a.no<>100

 

-

②删除操作

merge into 目标表 a

using 源表 b

on(a.条件字段1=b.条件字段1 and a.条件字段2=b.条件字段2 ……)  

when matched then update set a.更新字段=b.字段

delete where b.字段=xxx

举例:

merge into test_merge a
using test b
on(a.no=b.no)
when matched then update set a.no2=b.no2 where a.no<>1
delete 
where b.no=14

 

posted @ 2017-11-10 15:19  Frankiee  阅读(478)  评论(0)    收藏  举报