1

我对 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'

我有自动提交,所以这些语句被提交。

4

1 回答 1

4

尝试加入trunc(JH.LOAD_DATE) = trunc(J.LOAD_DATE)

每次尝试更新时,您都会有不同的 sysdate,因为您正在执行Select Sysdate load_Date, ... from JOBS子查询,这与历史表中的日期不匹配。

检查这个SQL Fiddle它适用于 trunc

于 2012-12-20T06:43:11.887 回答