Oracle MERGE: only NOT MATCHED is triggered

烈酒焚心 提交于 2019-12-10 12:26:33

问题


Database: Oracle

Table:

CREATE TABLE TABLE_FOR_TESTS (
    d DATE,
    t NUMBER(8)
)

MERGE:

MERGE INTO TABLE_FOR_TESTS
    USING DUAL
    ON ((SELECT COUNT(*) FROM TABLE_FOR_TESTS) = 1)
    WHEN MATCHED THEN
        UPDATE SET T = T+1
    WHEN NOT MATCHED THEN         
        INSERT (D, T) VALUES (sysdate, 1)

or

    ...
    ON ((SELECT T FROM TABLE_FOR_TESTS) is not null)
    ...

I will refer to the first version of MERGE, but the second one has the same effect.

1) I run that MERGE for the first time

  • result: expected (because there is no element, the ON condition is false => INSERT)

2) Here I run:

SELECT COUNT(*) FROM TABLE_FOR_TESTS

and it's output is "1".

3) I run that MERGE for the second time

  • result: unexpected (INSERT), expected: UPDATE (it works only on sqlfiddle)

Why is ON condition false at the N-th run (N>1) ? ( if it was "1" as output at 2) )

(just to test: if I change the condition to be ON (1=1) before the second run, it works well: UPDATE is done)


回答1:


I think you have misunderstood what merge is for.

I would expect your table to be something like:

CREATE TABLE TABLE_FOR_TESTS (
    d DATE,
    t NUMBER(8),
    CONSTRAINT TABLE_FOR_TESTS_PK PRIMARY KEY (d)
)

and then the merge statement could be:

MERGE INTO TABLE_FOR_TESTS t
  USING (SELECT trunc(sysdate) d FROM DUAL) s
    ON (s.d = t.d)
  WHEN MATCHED THEN
    UPDATE SET t = t+1
  WHEN NOT MATCHED THEN         
    INSERT (d, t) VALUES (trunc(sysdate), 1)

where the join is on the primary key of the table and either update or insert depending on whether the record for that PK value exists.

This would have a maximum of one record per day and t would hold the number of executions of this statement per day (assuming no other DML on TABLE_FOR_TESTS).

Note: sysdate by itself includes a time component. trunc(sysdate) removes it and sets the time to 00:00:00.



来源:https://stackoverflow.com/questions/25451727/oracle-merge-only-not-matched-is-triggered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!