我想从更新语句编写动态查询以合并合并语句

时间:2019-07-29 08:10:56

标签: oracle plsql dynamic-sql

我想从更新语句编写动态查询以合并合并语句

    'UPDATE ' || T1_TABLENAME || ' t1 ' || 'SET ( ' ||
             v_t1_fields || ' ) =  (SELECT ' || v_t2_fields || ' FROM ' ||
             T2_TEMPTABLE_NAME || ' tmp WHERE ' || v_con || ' ) ' ||
             ' WHERE EXISTS ( SELECT 1 FROM ' ||  T2_TEMPTABLE_NAME ||
             ' tmp WHERE ' || v_con || ' )';

           --  HERE v_con = t1.D=t2.D,
               v_t1_fields-it can store dynamically-A,B,C
               v_t2_fields-it can store dynamically-A,B,C

------------

    MERGE INTO TABLE1 t1
USING TABLE2 t2 
ON(t1.D=t2.D)
WHEN MATCHED THEN
  UPDATE 
   SET 
   t1.A=t2.A,
   t1.B=t2.B,  //update set (t1.A,t1.B,t1.C =t2.A,t2.B,t2.C) not work 
   t1.C=t2.C;


 ------------------  

    'MERGE INTO ' TABLE1 || ' t1 ' ||
' USING ' TABLE2 || ' t2 ' ||
' ON ( '  || v_cons || ' )   
 when matched then update set ('
  || v_t1_fields || ') = '( || v_t2_fields || ' );'  // Its not work--ORA-01747: invalid user.table.column, table.column, or column specification

然后我使用reg_exp拆分列

  ---------------------------

    v_Sql :=  'MERGE INTO ' TABLE1 || ' t1 ' ||
' USING ' TABLE2 || ' t2 ' ||
' ON ( '  || v_cons || ' )   
 when matched then update set ('
                ( ' || regexp_substr(v_t1_fields, '[^,]+', 1, 1) || ' ) = ( ' || regexp_substr(v_t2_fields, '[^,]+', 1, 1) || ' )
                ( ' || regexp_substr(v_t1_fields, '[^,]+', 1, 2) || ' ) = ( ' || regexp_substr(v_t2_fields, '[^,]+', 1, 2) || ' )
                ( ' || regexp_substr(v_t1_fields, '[^,]+', 1,3)  || ' ) = ( ' || regexp_substr(v_t2_fields, '[^,]+', 1,3) || ' ) ';

这一项也不起作用---- ORA-01747:无效的user.table.column,table.column或列规范 动态更新为动态合并 在更改与更新语句合并时 不起作用

1 个答案:

答案 0 :(得分:0)

MERGE语句的连接和使用中几乎没有错误。

尝试以下动态查询:

     'MERGE INTO '
     || TABLE1
     || ' t1 '
     || ' USING '
     || TABLE2
     || ' t2 '
     || ' ON ( '
     || V_CONS
     || ' ) when matched then update set '
     || REGEXP_SUBSTR(V_T1_FIELDS, '[^,]+', 1, 1)
     || ' = '
     || REGEXP_SUBSTR(V_T2_FIELDS, '[^,]+', 1, 1)
     || ', '
     || REGEXP_SUBSTR(V_T1_FIELDS, '[^,]+', 1, 2)
     || ' = '
     || REGEXP_SUBSTR(V_T2_FIELDS, '[^,]+', 1, 2)
     || ', '
     || REGEXP_SUBSTR(V_T1_FIELDS, '[^,]+', 1, 3)
     || ' = '
     || REGEXP_SUBSTR(V_T2_FIELDS, '[^,]+', 1, 3);

我认为

  • TABLE1TABLE2是有效的表名
  • V_CONS是表上的有效条件
  • V_T1_FIELDSV_T2_FIELDS包含表的有效列名

干杯!