Upsert(合并)用于更新记录(如果存在),否则插入

Upsert (merge) for updating record if it exists and inserting otherwise

我正在尝试编写一个 DB2 查询,允许我更新一条记录(如果它已经存在)但如果它不存在则应该插入它。我写了下面的查询来完成这个:

MERGE INTO OA1P.TLZ712A1 AS PC
USING (
    SELECT * FROM OA1P.TLZ712A1 
    WHERE CALENDAR_ID=13 AND 
    "PACKAGE"='M2108'
) PC2
ON (PC.ID_PACKAGE_CALENDAR=PC2.ID_PACKAGE_CALENDAR)
WHEN MATCHED THEN 
    UPDATE SET ACT_DATE = '31.12.2021'
WHEN NOT MATCHED THEN 
    INSERT ("PACKAGE", ACT_DATE, CALENDAR_ID, PREPTA, MIXED) VALUES ('M2108', '31.12.2021', 13, 0, 0)

此查询应尝试检查选择条件的记录是否已存在。更新记录似乎工作正常,但我无法让“WHEN NOT MATCHED”部分工作并插入新记录。谁能提供一些帮助?

table用于保存某个软件包的激活日期。 PACKAGE 是对包 table 的引用,其中包含包的名称(例如“M2108”)。 CALENDAR_ID指的是要激活软件包的系统。实际日期存储在 ACT_DATE.

未能将 DDL 导入 SQLFiddle,因此我必须在此处提供:

CREATE TABLE OA1P.TLZ712A1 (
    ID_PACKAGE_CALENDAR INTEGER DEFAULT IDENTITY GENERATED BY DEFAULT NOT NULL,
    CALENDAR_ID INTEGER,
    "PACKAGE" VARCHAR(10) NOT NULL,
    ACT_DATE DATE NOT NULL,
    PREPTA SMALLINT DEFAULT 0 NOT NULL,
    MIXED SMALLINT DEFAULT 0 NOT NULL,
    "COMMENT" VARCHAR(60) NOT NULL,
    LAST_MODIFIED_PID CHAR(7) NOT NULL,
    ST_STARTID TIMESTAMP NOT NULL,
    ST_FROM TIMESTAMP NOT NULL,
    ST_TO TIMESTAMP NOT NULL,
    CONSTRAINT TLZ712A1_PK PRIMARY KEY (ID_PACKAGE_CALENDAR),
    CONSTRAINT CALENDAR FOREIGN KEY (CALENDAR_ID) REFERENCES OA1P.TLZ711A1(ID_CALENDAR) ON DELETE RESTRICT,
    CONSTRAINT "PACKAGE" FOREIGN KEY ("PACKAGE") REFERENCES OA1P.TLZ716A1(NAME) ON DELETE RESTRICT
);
CREATE UNIQUE INDEX ILZ712A0 ON OA1P.TLZ712A1 (ID_PACKAGE_CALENDAR);

如果您的目标是将 ACT_DATE 设置为 31.12.2021,如果找到包含 PACKAGE = M2108 和 CALENDAR_ID = 13 的行,并且如果没有找到包含这些值的行,则将其插入,那么这可能就是答案

MERGE INTO OA1P.TLZ712A1 AS PC
USING (
   VALUES ('M2108', 13, date '31.12.2021')
) PC2 ("PACKAGE", CALENDAR_ID, ACT_DATE)
ON (PC."PACKAGE", PC.CALENDAR_ID) = (PC2."PACKAGE", PC2.CALENDAR_ID)
WHEN MATCHED THEN 
    UPDATE SET ACT_DATE = PC2.ACT_DATE
WHEN NOT MATCHED THEN 
    INSERT ("PACKAGE", ACT_DATE, CALENDAR_ID, PREPTA, MIXED) VALUES (PC2."PACKAGE", PC2.ACT_DATE, PC2.CALENDAR_ID, 0, 0)