关于merge函数的使用

来源:互联网 发布:福禄克435下载数据 编辑:程序博客网 时间:2024/06/05 23:00

关于merge函数的使用

1、语句介绍

MERGE语句是用来合并UPDATE和INSERT语句,由于仅需要一次全表扫描就完成了全部工作,所以执行效率要高于INSERTUPDATE 。 其作用 简单来说,就是:“有则更新,无则插入”从这句话里,应该可以理解到,merge into 操作一个对象'A'的时候,要有另外一个结果集做为源数据 'B'.
         ‘merge into’  将B中的数据与A中的数据按照一定条件'C'进行对比,如果 A中数据满足C条件,则进行update操作,如果不满足条件'C',则进行insert操作。(请注意这种对应关系)

2、 语法结构
          MERGE [INTO][schema.]table [alias]
       USING {[schema.]table|views|query} [alias]
       ON {condition}
       WHEN MATCHED THEN UPDATE SET {clause}
       WHEN NOT MATCHED THEN INSERT VALUES{clause}

 

3、使用注意事项

先来创建测试表

Create table  m_retail1 (id number,docnovarchar2(10),amount number(10,4));

Create table  m_retail1 (id number,docnovarchar2(10),amount number(10,4));

 

 

在表中插入数据

Insert into m_retail1 values(1,5,99999.0000);

Insert into m_retail   values(1,666,99999.0000);

 


 进行merge操作

Merge into m_retail  a

Using  m_retail1

On (a.id=b.id)

When  matched   then

Update set  a.docno=b.docno,a.mount=b.mount

When not  matched   then

Insert  values  (b.id,b.docno,b.amount)

以上是成功示范

错误示范如下

1.

Merge into m_retail  a

Using  m_retail1

On (a.id=b.id)

When  matched   then

Update set  a.docno=b.docno,a.mount=b.mount,a.id=b.id

When not  matched   then

Insert  values  (b.id,b.docno,b.amount)


 

原因是on子句的使用的字段不能够用于update,即Oracle不允许更新用于连接的列

2.  Insert  into m_retail1  values(1,6,99999.0000);

Merge into m_retail  a

Using  m_retail1

On (a.id=b.id)

When  matched   then

Update set  a.docno=b.docno,a.mount=b.mount

When not  matched   then

Insert  values  (b.id,b.docno,b.amount)

 

报错原因是因为,源表中作为判断条件的m_retail1.id有重复,那么如何获取重复的记录呢

因为是m_retail1有重复,所以键入语句;

Select  id,count(id) from  m_retail1  having  count(id)>1  group  by id 


可以看出id为1 的记录有两行;

Select * from  m_retail1  where  id=1



0 0
原创粉丝点击