2012-12-20 95 views
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' 

我有autocommit所以這些語句提交。

回答

4

嘗試加入上trunc(JH.LOAD_DATE) = trunc(J.LOAD_DATE)

每次嘗試更新,因爲你正在做Select Sysdate load_Date, ... from JOBS在你子查詢時,您都會有不同的SYSDATE,這將不匹配記錄表日期。

檢查這個SQL Fiddle它適用於trunc

+0

謝謝,是的,這是原因! – jrara