通过for循环执行Immediate到UPDATE

时间:2013-03-22 02:41:40

标签: sql oracle

我想按如下方式进行大量数据更新:

    CREATE OR REPLACE PROCEDURE PROC_MDM_RUN_DATA_MAPPING
     IS
        sqlString VARCHAR2(2000) := '';
        CURSOR csr_updates 
        IS
            SELECT  trim(table_name) AS table_name, 
                    trim(column_name) AS column_name, 
                    trim(old_value) AS old_value, 
                    trim(new_value) AS new_value 
            FROM C_MDM_MAPPING_TABLE 
            WHERE area = 'MDM' and rownum < 10
            AND run_update = 'Y' ;

    BEGIN
          FOR rec IN csr_updates 
          LOOP
             BEGIN
                sqlString := 'UPDATE ' || rec.table_name || 
                      ' SET ' || rec.column_name || ' = ''' || rec.new_value || '''
                      WHERE TRIM(' || rec.column_name || ') = ''' || rec.old_value || ''';'  ; 

                INSERT INTO C_MDM_ERROR_LOG  ( msg ) VALUES ( sqlString ); 

                dbms_output.put_line(sqlString) ; -- works, giving correct SQL
                execute immediate sqlString ;  -- fails

             END;
          END LOOP;
          COMMIT;

    END PROC_MDM_RUN_DATA_MAPPING;
    /

该过程为每个数据更新编译并生成正确的SQL - 例如:

    UPDATE S_CFM_UNIVERSITY_ALL SET MASTER_UNI_NAME = 'Chung-Ang University'
                      WHERE TRIM(MASTER_UNI_NAME) = 'Chung Ang University';

但是execute immediate语句给出了错误       “PLS-00103:在遇到以下情况之一时遇到符号”文件结束“:

符号“;”被替换为“文件结束”继续。“

我尝试排除尾随的分号,但是会返回错误

  ORA-00933: SQL command not properly ended

感谢任何帮助,谢谢。

2 个答案:

答案 0 :(得分:1)

尝试生成不带嵌入换行符的SQL,如:

CREATE OR REPLACE PROCEDURE PROC_MDM_RUN_DATA_MAPPING IS
  sqlString VARCHAR2(2000) := '';

  CURSOR csr_updates IS
    SELECT  trim(table_name) AS table_name, 
            trim(column_name) AS column_name, 
            trim(old_value) AS old_value, 
            trim(new_value) AS new_value 
      FROM C_MDM_MAPPING_TABLE 
      WHERE area = 'MDM' AND
            rownum < 10 AND
            run_update = 'Y';
  BEGIN
    FOR rec IN csr_updates LOOP
      sqlString := 'UPDATE ' || rec.table_name || 
                   ' SET ' || rec.column_name || ' = ''' || rec.new_value ||
                   ''' WHERE TRIM(' || rec.column_name || ') = ''' ||
                   rec.old_value || '''';

      INSERT INTO C_MDM_ERROR_LOG  ( msg ) VALUES ( sqlString ); 

      dbms_output.put_line(sqlString) ; -- works, giving correct SQL
      execute immediate sqlString ;
    END LOOP;

    COMMIT;
  END PROC_MDM_RUN_DATA_MAPPING;

我删除了生成的SQL中的分号,因为我认为它不需要,并且摆脱了循环中的BEGIN ... END对,这也是不需要的。

我希望这会有所帮助。分享并享受。

答案 1 :(得分:0)

感谢所有帮助 - 上面的答案是正确的,因为不需要尾随的分号,但作为后续行动 - 第二个问题是数据中的单引号。

按如下方式更改光标修复了该问题

    SELECT  trim(table_name) AS table_name, 
            trim(column_name) AS column_name, 
            REPLACE(trim(old_value),'''','''''') AS old_value, 
            REPLACE(trim(new_value),'''','''''') AS new_value 
    FROM C_MDM_MAPPING_TABLE 

表和列名称已经确定(它们来自系统),但它会回到“永不信任输入”。

由于