简体   繁体   中英

SQL MERGE to update or insert values into same table

"MERGE INTO NT_PROPERTY ntProp USING ( "  +
                            "SELECT * FROM NT_PROPERTY ) " +
                            "VALUES " +
                                    "('minDPTObjectId'," + minDPTObjectId + ", 'Starting DPT Object Id') " +
                                    "('maxDPTObjectId', " + maxDPTObjectId + ", 'Ending DPT Object Id') " +
                            "vt (NAME, VALUE, NOTE) " +
                            "ON ( ntProp.NAME = vt.NAME ) " +
                            "WHEN MATCHED THEN " +
                            "UPDATE SET VALUE = vt.VALUE "+
                            "WHEN NOT MATCHED THEN " +
                            "INSERT (NAME, VALUE, NOTE) VALUES (vt.NAME, vt.VALUE, vt.NOTE)";

Well I'm getting a missing ON keyword error and with no clue what so ever, also is there any other way to make it less clumsy

Help is very much appreciated.

The problem is that your MERGE syntax is incorrect. Your statement takes the form of:

MERGE INTO nt_property ntprop
  USING (SELECT * FROM nt_property)
    VALUES (...)
    vt (...)
  ON (ntprop.name = vt.name)
WHEN MATCHED THEN
  UPDATE ...
WHEN NOT MATCHED THEN
  INSERT ...;

but it should be of the form:

MERGE INTO target_table tgt_alias
  USING source_table_or_subquery src_alias
    ON (<JOIN conditions>)
WHEN MATCHED THEN
  UPDATE ...
WHEN NOT MATCHED THEN
  INSERT ...;

Why do you have the VALUES and vt clauses between your using and your on clauses? That's the incorrect syntax. Also, whilst you can use select * from tablename in the using clause, you could just use the tablename directly, since you're selecting all columns and all rows.

  MERGE INTO NT_PROPERTY D  
      USING (SELECT * FROM DUAL ) S  
      ON (D.NAME = 'minDPTObjectId')  
      WHEN MATCHED THEN UPDATE SET D.VALUE =   '1234' 
      WHEN NOT MATCHED THEN INSERT (NAME, VALUE, NOTE) 
      VALUES ('maxDPTObjectId', '1111', 'Ending DPT Object Id') ;

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