之前做資料移轉時候有用過,今天翻了下SQL發現有點陌生,記錄下基本使用好了。oracle10g預設scott使用者下建立了測試表及欄位(略)
MERGE INTO MERGEDEPT M USING (SELECT * FROM DEPT)D ON (M.DEPTNOM = D.DEPTNO) WHEN NOT MATCHED THEN INSERT( M.DEPTNOM,M.DNAMEM,M.LOCM )VALUES( D.DEPTNO,D.DNAME,D.LOC )
說明:insert,update都有相應的文法。做個記錄,有在用到的時候在詳細補充。
參考資料:http://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_9016.htm
---------2012.11.27補充-----------------------------------------
今天使用merge初始化資料,資料總數40W+不到50W。因為之前看到代碼中有用JDBC在初始化,結果可想而知,因為有業務慢的一塌糊塗。分析業務後,使用merge。建立DB_LINK和同義字後,起初的代碼如下
MERGE INTO base_rent_info bUSING( SELECT CZF.*, TO_DATE(SUBSTR(CZF.DJRQ, 0, 4) || '-' || SUBSTR(CZF.DJRQ, 5, 2) || '-' || SUBSTR(CZF.DJRQ, 7, 2), 'yyyy-MM-dd') AS RENT_START, TO_DATE(SUBSTR(CZF.CJSJ, 0, 4) || '-' || SUBSTR(CZF.CJSJ, 5, 2) || '-' || SUBSTR(CZF.CJSJ, 7, 2), 'yyyy-MM-dd') AS CREATE_DATE FROM TEMPORARYRESIDENTHOUSE CZF WHERE CZF.ZXBZ = '0' AND SUBSTR(CZF.DJRQ, 5, 2) IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))cON (b.pid = c.dah)WHEN NOT MATCHED THENINSERT(b.BASE_RENT_INFO_ID,b.COUNTY_CODE,b.POLICE_CODE,b.ZONE_CODE,b.STREET_CODE,b.HOUSE_PROPERTY, b.ADDRESS,b.RENT_STATE,b.HOUSE_TYPE,b.HOUSE_STRUCTURE,b.ROOM_NUMBER,b.HOUSE_AREA,b.RENT_START,b.RENT_END,b.HOST_NAME, b.HOST_PHONE,b.HOST_ADDRESS,b.MEMO,b.IS_DELETED,b.CREATE_DATE,b.CREATE_DEPT,b.CREATE_USER,b.UPDATE_DATE,b.UPDATE_DEPT, b.UPDATE_USER,b.PID) VALUES(base_rent_info_SEQ.NextVal, c.XZDQH,c.PCS,C.JWH,C.JD,C.FWXZ,C.CZFWDZ,C.ZT,C.FWLB,C.FWJG,C.FJS,C.MJ,C.RENT_START,NULL,C.XM, C.LXDH,C.GLRDZ,NULL,'0',C.CREATE_DATE,c.PCS,NULL,NULL,NULL, NULL,c.dah );
但是oracle10g卻報“ora-02064不支援分散式交易操作”。但是在以前使用時都沒報這種錯誤。後來google查了下,好多人都遇到類似問題。解決方案就是按照文檔嚴格文法(但是文檔中沒找到相應BUG的說明)。修改後代碼如下。紅色部分為格式化文法用的,欄位找了個無關的不需更新的欄位。
MERGE INTO base_rent_info bUSING( SELECT CZF.*, TO_DATE(SUBSTR(CZF.DJRQ, 0, 4) || '-' || SUBSTR(CZF.DJRQ, 5, 2) || '-' || SUBSTR(CZF.DJRQ, 7, 2), 'yyyy-MM-dd') AS RENT_START, TO_DATE(SUBSTR(CZF.CJSJ, 0, 4) || '-' || SUBSTR(CZF.CJSJ, 5, 2) || '-' || SUBSTR(CZF.CJSJ, 7, 2), 'yyyy-MM-dd') AS CREATE_DATE FROM TEMPORARYRESIDENTHOUSE CZF WHERE CZF.ZXBZ = '0' AND SUBSTR(CZF.DJRQ, 5, 2) IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))cON (b.pid = c.dah)WHEN MATCHED THEN UPDATE SET b.COUNTY_CODE = c.XZDQHWHEN NOT MATCHED THENINSERT(b.BASE_RENT_INFO_ID,b.COUNTY_CODE,b.POLICE_CODE,b.ZONE_CODE,b.STREET_CODE,b.HOUSE_PROPERTY, b.ADDRESS,b.RENT_STATE,b.HOUSE_TYPE,b.HOUSE_STRUCTURE,b.ROOM_NUMBER,b.HOUSE_AREA,b.RENT_START,b.RENT_END,b.HOST_NAME, b.HOST_PHONE,b.HOST_ADDRESS,b.MEMO,b.IS_DELETED,b.CREATE_DATE,b.CREATE_DEPT,b.CREATE_USER,b.UPDATE_DATE,b.UPDATE_DEPT, b.UPDATE_USER,b.PID) VALUES(base_rent_info_SEQ.NextVal, c.XZDQH,c.PCS,C.JWH,C.JD,C.FWXZ,C.CZFWDZ,C.ZT,C.FWLB,C.FWJG,C.FJS,C.MJ,C.RENT_START,NULL,C.XM, C.LXDH,C.GLRDZ,NULL,'0',C.CREATE_DATE,c.PCS,NULL,NULL,NULL, NULL,c.dah );