如何使用ORACLE MERGE语句使用DECODE INSERT值?

时间:2014-12-02 03:39:18

标签: sql oracle11g merge decode insert-update

我试图将MERGE用于UPSERT。使用此MERGE语句,更新代码运行良好(我没有在此发布),但INSERT发出以下错误:

  • ORA-00963 ---缺少表达式(在INSERT-VALUES中提到SELECT时)
  • ORA-00917 ---缺少逗号(删除SELECT时)
  • 当我格式化此代码时,它要求在VALUES&附近进行语法检查。指向AS条款。

基本上我想写一个容纳DECODE语句的MERGE-INSERT语句。 请帮助我,因为我是甲骨文的新手。

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;

1 个答案:

答案 0 :(得分:0)

使用合并插入时不能使用select语句,因此对于值,您必须在使用'之后使用select语句。关键字然后将select的值传递给insert语句。

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