SQL选择语句作为动态PLSQL块的绑定变量



我正在尝试使用execute立即运行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;

如果我了解很好,则需要通过将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>

plz尝试一下。

    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;
/

相关内容

  • 没有找到相关文章

最新更新