简体   繁体   中英

How to use ORACLE MERGE statement to INSERT values using DECODE?

I'm trying to use MERGE for an UPSERT. The update code works well (I haven't posted here) with this MERGE statement but INSERT is giving the following errors:

  • ORA-00963 ---Missing expression (when SELECT is mentioned in INSERT-VALUES)
  • ORA-00917 ---Missing comma (when SELECT is removed)
  • When I format this code, it calls for a syntax check near VALUES & points towards the AS clause.

Basically I want to write the MERGE-INSERT statement that accommodates the DECODE statement as well. Please help me as I'm new to Oracle.

MERGE INTO Table1 t1
   USING(SELECT DISTINCT A_cd, F_str, a_pm, a_type 
        FROM Table2) t2
     ON(t1.C_Name=t2.A_cd)
WHEN NOT MATCHED 
THEN
 INSERT(C_type, C_name, C_value)
  VALUES (SELECT t3.C_type, t4.A_cd as C_name,
        DECODE(t3.c_type,
               'A COMP', t4.f_str,
               'A_PM', t4.a_pm,
               'A_TYPE' t4.a_type) as c_value)
 FROM(SELECT 'A_COMP' as c_type FROM DUAL
    UNION ALL
    SELECT 'A_PM' as c_type FROM DUAL
    UNION ALL
    SELECT 'A_TYPE' as c_type FROM DUAL)t3,
   (SELECT DISTINCT A_cd, F_str, a_pm, a_type
    FROM Table2 t2
    WHERE A_cd || F_str || a_pm || a_type
    IS NOT NULL
    AND NOT EXISTS
    (SELECT NULL
    FROM Table1 t1
    WHERE t2.A_cd=t1.c_name))t4;

You can't use select statement while inserting using merge,so for values you have to use your select statement after 'using' keyword and then passing the value of select into the insert statement .

  MERGE INTO Table1 t1
  USING (SELECT t3.C_type, t4.A_cd as C_name,
      DECODE(t3.c_type,
       'A COMP', t4.f_str,
       'A_PM', t4.a_pm,
       'A_TYPE' t4.a_type) as c_value)
    FROM(SELECT 'A_COMP' as c_type FROM DUAL
    UNION ALL
     SELECT 'A_PM' as c_type FROM DUAL
     UNION ALL
     SELECT 'A_TYPE' as c_type FROM DUAL)t3,
    (SELECT DISTINCT A_cd, F_str, a_pm, a_type
      FROM Table2 t2
      WHERE A_cd || F_str || a_pm || a_type
      IS NOT NULL
       AND NOT EXISTS
      (SELECT NULL
      FROM Table1 t1
        WHERE t2.A_cd=t1.c_name))t4
   ON(t1.C_Name=t4.A_cd)
  WHEN NOT MATCHED 
  THEN
  INSERT(C_type, C_name, C_value)
  values(t4.C_type, t4.C_name,t4.c_value);

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