【问题标题】:Loop through plsql code for a number of tables循环遍历多个表的 plsql 代码
【发布时间】:2019-04-17 20:28:33
【问题描述】:

主表每天都会使用来自两个表中的两个来源的输入数据进行更新。处理这两个表的 plsql 代码实际上是相同的,只是表名不同。我们必须分别记录有关输入表中数据的可能错误,因此必须为两个输入表分别运行一次代码。

尝试的解决方案是将表名放在一个变量中,然后循环两次代码:

declare
   input_table varchar2(20);
begin
   for i in (select column_value as var from table(sys.ODCIvarchar2List('MIDGETS', 'GIANTS'))) loop
      if i.var = 'MIDGETS' then
         input_table := 'midget_table';
      elsif i.var = 'GIANTS' then
         input_table := 'giant_table';
      end if;

      for rec in (select col1, col2 from input_table) loop

         <the processing code>

      end loop;
end;
/

问题在于 plsql 似乎没有意识到 input_table 是一个变量。它“认为” input_table 是表的名称,并返回 (ORA-00942: table or view does not exist) 错误。

由于这是动态代码,因此尝试了 EXECUTE IMMEDIATE:

declare
   input_table varchar2(20);
begin
   for ... 'MIDGETS', 'GIANTS' ... loop
      input_table := ...
      ...
   end loop;

   for rec in ( EXECUTE IMMEDIATE 'select col1, col2 from ' || input_table ) loop
      <processing>
   end loop;
end;
/

但是在这种情况下,EXECUTE IMMEDIATE 也是不允许的。

有办法吗?还是将 .sql 文件复制两份,一份给 MIDGETS,一份给 GIANTS,这是唯一的出路?

【问题讨论】:

    标签: oracle plsql


    【解决方案1】:

    您可以使用如下动态查询

    declare
       type crs_type is ref cursor;
       c crs_type;
       v_query     varchar2(2000);
       input_table varchar2(20);
       v_col1      midgets.col1%type; -- assuming identical data types for common named columns
       v_col2      midgets.col2%type;
    begin
       for ... 'MIDGETS', 'GIANTS' ... loop
          input_table := ...
          ...
       end loop;
    
    
       v_query := 'select col1, col2 from ' || input_table;
       open c for v_query;
       loop
        fetch c into v_col1, v_col2;
        exit when c%notfound;
          <processing>
       end loop;
       close c;
    end;
    

    【讨论】:

    • 太棒了!这解决了我的问题。谢谢!为了向任何人澄清这可能具有参考价值,在解决我的问题时,光标循环应该嵌入在“for ...'MIDGETS','GIANTS'循环”中。那是我在原始帖子的第二个代码摘录中的错误。很抱歉。
    猜你喜欢
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多