简体   繁体   中英

Oracle MERGE: only NOT MATCHED is triggered

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM