简体   繁体   中英

Multiple clauses in MERGE for Oracle SQL: UPSERT AND DELETE in a single statement

I have the query in the below form:

public static final String CLASS_UPSERT_QUERY = Joiner.on(" ").join(
    "MERGE INTO CLASS USING DUAL ON",
    "(<condition1>)",
    "WHEN MATCHED THEN",
    "UPDATE SET ()",
    "WHEN NOT MATCHED THEN",
    "INSERT () VALUES ()"
);

My doubt is whether it is possible to have multiple conditions in the same statement. I need to upsert based on certain condition and delete the entries on another.

Something on the lines of below:

public static final String CLASS_UPSERT_QUERY = Joiner.on(" ").join(
    "MERGE INTO CLASS USING DUAL ON",
    "(<condition1>)",
    "WHEN MATCHED THEN",
    "UPDATE SET ()",
    "WHEN NOT MATCHED THEN",
    "(",
    "MERGE INTO CLASS USING DUAL ON(<condition2>)",
    "WHEN MATCHED THEN",
    "DELETE ()",
    "WHEN NOT MATCHED THEN",
    "INSERT () VALUES ()",
    ")"
);

If you take out the java part from the question, this seems like a simple Merge statement in Oracle, where you can do either insert or update based on condition as below:

MERGE INTO tgt_tbl a
  USING src_tbl b
    ON (a.id = b.id)
  WHEN MATCHED THEN
    UPDATE SET a.status = b.status
    WHERE  b.status != 'VALID'
  WHEN NOT MATCHED THEN
    INSERT (id, status)
    VALUES (b.id, b.status)
    WHERE  b.status != 'VALID';

I am going to answer based on oracle's point of view.

When to use merge Statement : To select rows from one or more sources for update or insertion into a table or view. Or to combine insert/update/Delete within a single statement.

Syntax:

MERGE
INTO  target_table tgt
USING source_table src
ON  ( src.object_id = tgt.object_id )
WHEN MATCHED
THEN
UPDATE
SET   tgt.object_name = src.object_name,tgt.object_type = src.object_type
WHEN NOT MATCHED
THEN
INSERT ( tgt.object_id
    , tgt.object_name
    , tgt.object_type )
    VALUES ( src.object_id
    , src.object_name
    , src.object_type );

Please provide your tables and the sample data for us to make you better understand the problem. You haven't provided us with any sample data or tables.

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