MERGE ステートメントに問題があります。行は更新されず、古い行が再び挿入されます。HR スキーマを使用した簡単なコード例を次に示します。
--CREATES A SEQUENCE FOR A HISTORY TABLE
CREATE SEQUENCE JOBHIS_SEQ
START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 999999999999999999999999999
NOCACHE
NOORDER
NOCYCLE;
--CREATES A HISTORY TABLE
CREATE TABLE JOBHIS (
ID NUMBER(10) NOT NULL,
LOAD_DATE DATE,
JOB_ID VARCHAR2(10) NOT NULL ENABLE,
JOB_TITLE VARCHAR2(35) NOT NULL ENABLE,
MIN_SALARY NUMBER(6,0),
MAX_SALARY NUMBER(6,0),
CONSTRAINT JOBHIS_ID_PK PRIMARY KEY (ID) ENABLE
)
--this inserts 19 rows into jobhis
MERGE INTO JOBHIS JH
USING ( SELECT SYSDATE AS LOAD_DATE, JOB_ID, JOB_TITLE, MIN_SALARY, MAX_SALARY
FROM JOBS
) J
ON (JH.JOB_ID = J.JOB_ID AND JH.LOAD_DATE = J.LOAD_DATE)
WHEN MATCHED THEN UPDATE SET JH.MIN_SALARY = J.MIN_SALARY
WHERE JH.MIN_SALARY != J.MIN_SALARY
WHEN NOT MATCHED THEN INSERT (JH.ID, JH.LOAD_DATE, JH.JOB_ID, JH.JOB_TITLE, JH.MIN_SALARY, JH.MAX_SALARY)
VALUES(JOBHIS_SEQ.NEXTVAL, SYSDATE, J.JOB_ID, J.JOB_TITLE, J.MIN_SALARY, J.MAX_SALARY)
--lets update jobs to get a row update into jobhis
UPDATE JOBS
SET MIN_SALARY = 10000
WHERE JOB_ID = 'AC_ACCOUNT'
--lets merge again
MERGE INTO JOBHIS JH
USING ( SELECT SYSDATE AS LOAD_DATE, JOB_ID, JOB_TITLE, MIN_SALARY, MAX_SALARY
FROM JOBS
) J
ON (JH.JOB_ID = J.JOB_ID AND JH.LOAD_DATE = J.LOAD_DATE)
WHEN MATCHED THEN UPDATE SET JH.MIN_SALARY = J.MIN_SALARY
WHERE JH.MIN_SALARY != J.MIN_SALARY
WHEN NOT MATCHED THEN INSERT (JH.ID, JH.LOAD_DATE, JH.JOB_ID, JH.JOB_TITLE, JH.MIN_SALARY, JH.MAX_SALARY)
VALUES(JOBHIS_SEQ.NEXTVAL, SYSDATE, J.JOB_ID, J.JOB_TITLE, J.MIN_SALARY, J.MAX_SALARY)
--> 19 rows are inserted, no updates, why? Somehow LOAD_DATE does not seem to work
--lets update jobs to back its original state
UPDATE JOBS
SET MIN_SALARY = 4200
WHERE JOB_ID = 'AC_ACCOUNT'
これらのステートメントがコミットされるように、自動コミットをオンにしています。