SQL MERGE将值更新或插入到同一个表中

时间:2017-05-11 06:52:05

标签: java sql oracle jdbc merge

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

好吧,我收到了一个缺少ON关键字的错误,并且根本没有任何线索,还有其他方法可以让它不那么笨拙

非常感谢帮助。

2 个答案:

答案 0 :(得分:2)

问题是您的MERGE语法不正确。您的陈述采用以下形式:

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 ...;

但它应该是以下形式:

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 ...;

为什么VALUESvt条款之间有usingon条款?那是不正确的语法。此外,虽然您可以在select * from tablename子句中使用using,但您可以直接使用表名,因为您选择了所有列和所有行。

答案 1 :(得分:1)

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