---
title: "OracleMergeinto详细介绍"
author: "wiseboyloves"
date: "2012-12-03T00:16:13Z"
tags: []
categories: ["数据库"]
slug: "oraclemergeinto"
draft: false
lastmod: "2012-12-03T00:18:56Z"
id: 1739906
url: "https://wiseboyloves.iteye.com/blog/1739906"
---

/\*Merge into 详细介绍

　　MERGE语句是Oracle9i新增的语法，用来合并UPDATE和INSERT语句。

　　通过MERGE语句，根据一张表或子查询的连接条件对另外一张表进行查询，

　　连接条件匹配上的进行UPDATE，无法匹配的执行INSERT。

　　这个语法仅需要一次全表扫描就完成了全部工作，执行效率要高于INSERT＋UPDATE。

　　\*/

 

　　/\*语法：

　　MERGE \[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;

　　\*/

 

　　语法：

　　MERGE INTO \[your table-name] \[rename your table here]

　　USING ( \[write your query here] )\[rename your query-sql and using just like a table]

　　ON (\[conditional expression here] AND \[...]...)

　　WHEN MATHED THEN \[here you can execute some update sql or something else ]

　　WHEN NOT MATHED THEN \[execute something else here ! ]

 

　　/*

　　我们还是以《sql中的case应用》中的表为例。在创建另两个表fzq1和fzq2

　　\*/

 

　　--全部男生记录

　　create table fzq1 as select * from fzq where sex=1;

　　--全部女生记录

　　create table fzq2 as select * from fzq where sex=0;

　　/\*涉及到两个表关联的例子\*/

　　--更新表fzq1使得id相同的记录中chengji字段＋1，并且更新name字段。

　　--如果id不相同，则插入到表fzq1中.

　　--将fzq1表中男生记录的成绩＋1，女生插入到表fzq1中

　　merge into fzq1  aa     --fzq1表是需要更新的表

　　using fzq bb            -- 关联表

　　on (aa.id=bb.id)        --关联条件

　　when matched then       --匹配关联条件，作更新处理

　　update set

　　aa.chengji=bb.chengji+1,

　　aa.name=bb.name         --此处只是说明可以同时更新多个字段。

　　when not matched then    --不匹配关联条件，作插入处理。如果只是作更新，下面的语句可以省略。

　　insert values( bb.id, bb.name, bb.sex,bb.kecheng,bb.chengji);

 

      --可以自行查询fzq1表。

 

　　/\*涉及到多个表关联的例子，我们以三个表为例，只是作更新处理，不做插入处理。当然也可以只做插入处理\*/

 

　　--将fzq1表中女生记录的成绩＋1，没有直接去sex字段。而是fzq和fzq2关联。

　　merge into fzq1  aa     --fzq1表是需要更新的表

　　using (select fzq.id,fzq.chengji

　　from fzq join fzq2

　　on fzq.id=fzq2.id) bb  -- 数据集

　　on (aa.id=bb.id)        --关联条件

　　when matched then       --匹配关联条件，作更新处理

　　update set

　　aa.chengji=bb.chengji+1

　　--可以自行查询fzq1表。

 

　　/\*不能做的事情\*/

　　merge into fzq1  aa

　　using fzq bb

　　on (aa.id=bb.id)

　　when matched then

　　update set

　　aa.id=bb.id+1

 

　　/\*系统提示：

　　ORA-38104: Columns referenced in the ON Clause cannot be updated: "AA"."ID"

　　我们不能更新on (aa.id=bb.id)关联条件中的字段\*/

　　update fzq1

　　set  id=(select id+1 from fzq where fzq.id=fzq1.id)

　　where id in

　　(select id from fzq)

 

　　--使用update就可以更新，如果有更好的方法，谢谢反馈！