Deepanshu Mann
Deepanshu Mann

Reputation: 71

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.

Upvotes: 1

Views: 4930

Answers (2)

Deepak Mann
Deepak Mann

Reputation: 111

  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') ;

Upvotes: 1

Boneist
Boneist

Reputation: 23588

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.

Upvotes: 2

Related Questions