sql select 语句作为动态 plsql 块的绑定变量

sql select statement as bind variable for dynamic plsql block

我正在尝试 运行 plsql 匿名块使用立即执行并且 plsql 块包含一个绑定变量,其值为 sql select 语句。但似乎这不起作用。有没有解决这个问题的方法。 例如

BEGIN
  V_SQL:='SELECT emp_id FROM  emp  WHERE  dept_id=10;
  PLSQL_BLOCK:='DECLARE
    type emp_type
    IS
    TABLE OF NUMBER;
    emp_id emp_type;
    BEGIN
        EXECUTE IMMEDIATE :1 BULK COLLECT INTO emp_id;  
    END';
EXECUTE IMMEDIATE PLSQL_BLOCK USING V_SQL;

请尝试 this.Hope 这有帮助。

    set serveroutput on;
    set define on;
    DECLARE
  V_SQL varchar2(1000):='SELECT emp_id from emp where deptno = 10';
  PLSQL_BLOCK varchar2(1000):='DECLARE    
                                type emp_type    
                                IS    
                                TABLE OF NUMBER;    
                                emp_id emp_type;   
                                BEGIN        
                                EXECUTE IMMEDIATE :1 BULK COLLECT INTO emp_id;      
                                END;';
BEGIN
  EXECUTE IMMEDIATE PLSQL_BLOCK USING V_SQL;
END;

您必须首先声明要在执行块中使用的变量。

试试这个:

DECLARE
    V_SQL VARCHAR2(1000) := 'SELECT emp_id FROM  emp  WHERE  dept_id=10';
    PLSQL_BLOCK varchar2(1000) :='DECLARE type emp_type IS TABLE OF integer; emp_id emp_type;'
        || ' BEGIN EXECUTE IMMEDIATE :1 BULK COLLECT INTO emp_id; END;';
BEGIN
    EXECUTE IMMEDIATE PLSQL_BLOCK USING V_SQL;
END;
/

如果我理解得很好,您需要使用 as SQL 查询作为绑定变量来 运行 整个动态 PLSQL 块;如果是这样,你可以这样试试:

SQL> declare
  2      vPlSqlBlock varchar2(10000);
  3      vSQL        varchar2(1000);
  4  BEGIN
  5    vSQL:='SELECT 1 from dual';
  6    --
  7    vPlSqlBlock:='DECLARE
  8      type emp_type IS TABLE OF NUMBER;
  9      emp_id   emp_type;
 10      vSQLDyn  varchar2(1000) := :1;
 11      BEGIN
 12          EXECUTE IMMEDIATE vSQLDyn BULK COLLECT INTO emp_id;
 13          --
 14          /* whatever you need to do in your block */
 15          for i in emp_id.first .. emp_id.last loop
 16              dbms_output.put_line(emp_id(i));
 17          end loop;
 18      END;';
 19
 20      EXECUTE IMMEDIATE vPlSqlBlock USING vSQL;
 21  end;
 22  /
1

PL/SQL procedure successfully completed.

SQL> declare
  2      vPlSqlBlock varchar2(10000);
  3      vSQL        varchar2(1000);
  4  BEGIN
  5    vSQL:='SELECT 1 from dual';
  6    --
  7    vPlSqlBlock:='DECLARE
  8      type emp_type IS TABLE OF NUMBER;
  9      emp_id   emp_type;
 10      vSQLDyn  varchar2(1000) := :1;
 11      BEGIN
 12          EXECUTE IMMEDIATE vSQLDyn BULK COLLECT INTO emp_id;
 13          /* this does nothing */
 14      END;';
 15
 16      EXECUTE IMMEDIATE vPlSqlBlock USING vSQL;
 17  end;
 18  /

PL/SQL procedure successfully completed.

SQL>