合并语句插入行,但不更新

时间:2012-12-20 06:19:39

标签: sql oracle

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

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

1 个答案:

答案 0 :(得分:4)

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

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

选中此SQL Fiddle,它适用于截断