Does DB2 have an “insert or update” statement?

后端 未结 4 1707
春和景丽
春和景丽 2020-11-28 07:22

From my code (Java) I want to ensure that a row exists in the database (DB2) after my code is executed.

My code now does a select and if no result is re

4条回答
  •  庸人自扰
    2020-11-28 07:40

    This response is to hopefully fully answer the query MrSimpleMind had in use-update-and-insert-in-same-query and to provide a working simple example of the DB2 MERGE statement with a scenario of inserting AND updating in one go (record with ID 2 is updated and record ID 3 inserted).

    CREATE TABLE STAGE.TEST_TAB (  ID INTEGER,  DATE DATE,  STATUS VARCHAR(10)  );
    COMMIT;
    
    INSERT INTO TEST_TAB VALUES (1, '2013-04-14', NULL), (2, '2013-04-15', NULL); COMMIT;
    
    MERGE INTO TEST_TAB T USING (
      SELECT
        3 NEW_ID,
        CURRENT_DATE NEW_DATE,
        'NEW' NEW_STATUS
      FROM
        SYSIBM.DUAL
    UNION ALL
      SELECT
        2 NEW_ID,
        NULL NEW_DATE,
        'OLD' NEW_STATUS
      FROM
        SYSIBM.DUAL 
    ) AS S
      ON
        S.NEW_ID = T.ID
      WHEN MATCHED THEN
        UPDATE SET
          (T.STATUS) = (S.NEW_STATUS)
      WHEN NOT MATCHED THEN
        INSERT
        (T.ID, T.DATE, T.STATUS) VALUES (S.NEW_ID, S.NEW_DATE, S.NEW_STATUS);
    COMMIT;
    

提交回复
热议问题