標籤:into merge orancle
1、MERGE INTO 的用途:
MERGE INTO 是Oracle 9i新增的文法,在10g時得到補充,用來合并UPDATE和INSERT語句,根據一張表或子查詢與另一張表進行串連查詢,串連條件匹配就進行
UPDATE,不匹配就進行INSERT,這個文法僅需要一次全表掃描就可以完成全部工作,執行效率會比單純的UPDATE+INSERT高,具體應用可用於表之間的同步。
2、MERGE INTO 的文法:
文法結構:
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 [表名] [別名] --需要更新的目標表
USING ( 子查詢/表名/視圖)[別名] --源表
ON ([串連條件] AND [...]...) --串連條件/更新條件
WHEN MATHED THEN UPDATE SET [...] --如果匹配,更新表記錄,若只作更新出來,下面的INSERT部分可以去掉
WHEN NOT MATHED THEN INSERT VALUES() [...] --如果不匹配,插入表記錄
3、MERGE INTO 示範:
1> 建立測試表及資料:
--以表YAG1作為源表,表YAG2作為更新的目標表
CREATE TABLE YAG1 AS SELECT OBJECT_NAME,oOBJECT_ID FROM USER_OBJECTS WHERE ROWNUM<=10;
CREATE TABLE YAG2 AS SELECT OBJECT_NAME,oOBJECT_ID FROM USER_OBJECTS WHERE ROWNUM<=5;
--修改表YAG1中某條記錄的OBJECT_NAME,創造符合UPDATE的條件,
SQL> UPDATE YAG1 SET OBJECT_NAME=‘AAAAA‘ WHERE OBJECT_NAME=‘T_CAT‘;
2>MERGE INTO 更新前兩表的記錄對比:
SQL> SELECT A.OBJECT_ID,A.OBJECT_NAME,B.OBJECT_NAME FROM YAG1 A,YAG2 B WHERE A.OBJECT_ID=B.OBJECT_ID(+) ORDER BY 1;
A.OBJECT_ID A.OBJECT_NAME B.OBJECT_NAME
------------ ---------------- -----------------
46366 AAAAA T_CAT
46367 SUM_STRING SUM_STRING
46368 ARRAYLIST ARRAYLIST
46369 TYSKZ_SJDX TYSKZ_SJDX
46370 TYSKZ_SJXMGX TYSKZ_SJXMGX
46371 PARAOBJECT
46372 T_LINK
46373 STR_SPLIT
46374 SPLIT_TYPE
46375 SYS_PLSQL_95487_9_1
3> 執行下面MERGE INTO 語句:
MERGE INTO YAG2 A
USING YAG1 B
ON (A.OBJECT_ID = B.OBJECT_ID)
WHEN MATCHED THEN
UPDATE SET A.OBJECT_NAME = B.OBJECT_NAME
WHEN NOT MATCHED THEN
INSERT VALUES (B.OBJECT_NAME, B.OBJECT_ID);
COMMIT;
4> MERGE INTO 更新後兩表的記錄對比:
SQL> SELECT A.OBJECT_ID,A.OBJECT_NAME,B.OBJECT_NAME FROM YAG1 A,YAG2 B WHERE A.OBJECT_ID=B.OBJECT_ID(+) ORDER BY 1;
A.OBJECT_ID A.OBJECT_NAME B.OBJECT_NAME
------------ ---------------- -----------------
46366 AAAAA AAAAA
46367 SUM_STRING SUM_STRING
46368 ARRAYLIST ARRAYLIST
46369 TYSKZ_SJDX TYSKZ_SJDX
46370 TYSKZ_SJXMGX TYSKZ_SJXMGX
46371 PARAOBJECT PARAOBJECT
46372 T_LINK T_LINK
46373 STR_SPLIT STR_SPLIT
46374 SPLIT_TYPE SPLIT_TYPE
46375 SYS_PLSQL_95487_9_1 SYS_PLSQL_95487_9_1
.
本文出自 “QYtag (Upspringing)” 部落格,請務必保留此出處http://qytag.blog.51cto.com/6125308/1530015