使用变量参数在FOR..IN循环中选择

时间:2018-03-23 16:02:15

标签: oracle plsql

我试图在SELECT嵌套到FOR..IN循环的SELECT中使用游标数据,如下所示:

DECLARE 
        CURSOR c_table IS 
          SELECT a, 
                 b 
          FROM   test_table 
          WHERE  a LIKE 'XX%' 
                 AND b = 1 
          ORDER  BY a, 
                    b; 
        qty NUMBER; 
    BEGIN 
        FOR t IN c_table LOOP 
            SELECT count(*) 
            INTO   qty 
            FROM   t.a;
            DBMS_OUTPUT.PUT_LINE( qty );
        END LOOP; 
    END; 

    / 

此代码返回引用嵌套SELECT的错误:

PL/SQL: ORA-00942: table or view does not exist

如何在FOR..IN LOOP中的SELECT中使用来自游标的数据?

1 个答案:

答案 0 :(得分:2)

PL / SQL不允许您将一个查询或游标的结果列用作另一个查询中的表名。您需要动态构建查询:

DECLARE 
  CURSOR c_table IS 
    SELECT a, 
           b 
      FROM   test_table 
      WHERE  a LIKE 'XX%' 
             AND b = 1 
      ORDER  BY a, 
                b; 
  qty NUMBER; 
BEGIN 
  FOR t IN c_table LOOP 
    EXECUTE IMMEDIATE 'SELECT count(*) FROM ' || t.a
      INTO qty;

    DBMS_OUTPUT.PUT_LINE( qty );
  END LOOP; 
END; 

祝你好运。