日期:2014-05-16  浏览次数:20428 次

Oracle merge into 命令
原文:http://jayklin.iteye.com/blog/1669114

作用:merge into 解决用B表跟新A表数据,如果A表中没有,则把B表的数据插入A表;当处理大数据量是,该方法的效率很高。

语法:
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 ! ]

copy:http://blog.csdn.net/nsj820/article/details/5755685


Oracle9i引入了MERGE命令,你能够在一个SQL语句中对一个表同时执行inserts和updates操作. MERGE命令从一个或多个数据源中选择行来updating或inserting到一个或多个表.在Oracle10g中MERGE有如下一些改进:

1、UPDATE或INSERT子句是可选的

2、UPDATE和INSERT子句可以加WHERE子句

3、在ON条件中使用常量过滤谓词来insert所有的行到目标表中,不需要连接源表和目标表

4、UPDATE子句后面可以跟DELETE子句来去除一些不需要的行

语法:

MERGEHINTINTO SCHEMA .TABLE T_ALIAS

USINGSCHEMA . {TABLE | VIEW |SUBQUERY } T_ALIAS

ON (CONDITION)

WHENMATCHEDTHEN MERGE_UPDATE_CLAUSE

WHENNOTMATCHED THEN MERGE_INSERT_CLAUSE / MERGE_DELETE_CLAUSE;

联想:
merge into是特有的功能,相当于在 MSSQL中的

ifexists(...)

updatetable

else

Insertinto table.

mergeinto语法不仅没有if exists语法啰嗦,而且比if exists还要高效很多,常用来在oracle之间同步数据库表。

例子:

1、创建测试表及数据




[c-sharp] view plaincopyprint?
01.DROP TABLE PRODUCTS; 
02.DROP TABLE NEWPRODUCTS; 
03.create table PRODUCTS 
04.( 
05.PRODUCT_ID INTEGER, 
06.PRODUCT_NAME VARCHAR2(60), 
07.CATEGORY VARCHAR2(60) 
08.); 
09.insert into PRODUCTS values (1501, 'VIVITAR 35MM', 'ELECTRNCS'); 
10.insert into PRODUCTS values (1502, 'OLYMPUS IS50', 'ELECTRNCS'); 
11.insert into PRODUCTS values (1600, 'PLAY GYM', 'TOYS'); 
12.insert into PRODUCTS values (1601, 'LAMAZE', 'TOYS'); 
13.insert into PRODUCTS values (1666, 'HARRY POTTER', 'DVD'); 
14.commit; 
15.create table NEWPRODUCTS 
16.( 
17.PRODUCT_ID INTEGER, 
18.PRODUCT_NAME VARCHAR2(60), 
19.CATEGORY VARCHAR2(60) 
20.); 
21.insert into NEWPRODUCTS values (1502, 'OLYMPUS CAMERA', 'ELECTRNCS'); 
22.insert into NEWPRODUCTS values (1601, 'LAMAZE', 'TOYS'); 
23.insert into NEWPRODUCTS values (1666, 'HARRY POTTER', 'TOYS'); 
24.insert into NEWPRODUCTS values (1700, 'WAIT INTERFACE', 'BOOKS'); 
25.commit; 


2、匹配更新




[c-sharp] view plaincopyprint?
01.MERGE INTO PRODUCTS P 
02.USING NEWPRODUCTS NP 
03.ON (P.PRODUCT_ID = NP.PRODUCT_ID) 
04.WHEN MATCHED THEN 
05.  UPDATE 
06.     SET P.PRODUCT_NAME = NP.PRODUCT_NAME, 
07.         P.CATEGORY     = NP.CATEGORY; 
08. 
09.SELECT * FROM PRODUCTS; 
10.SELECT * FROM NEWPRODUCTS; 


3、不匹配插入




[c-sharp] view plaincopyprint?
01.MERGE INTO PRODUCTS P 
02.USING NEWPRODUCTS NP 
03.ON (P.PRODUCT_ID = NP.PRODUCT_ID) 
04.WHEN NOT MATCHED THEN 
05.  INSERT 
06.    (PRODUCT_ID 
07.    ,PRODUCT_NAME 
08.    ,CATEGORY) 
09.  VALUES 
10.    (NP.PRODUCT_ID 
11.    ,NP.PRODUCT_NAME 
12.    ,NP.CATEGORY); 
13. 
14.SELECT * FROM PRODUCTS; 
15.SELECT * FROM NEWPRODUCTS; 


4、匹配带where/on更新