使用嵌套表在Oracle PL / SQL中构建动态SQl

时间:2016-03-07 11:28:39

标签: arrays oracle plsql dynamic-sql

以下是我正在处理的pl / sql代码的一部分。我想生成dyamic sql,它查看i_emp嵌套表中的值,并将结果返回到CharArray中。以下代码无效,需要帮助修复代码

这只是示例代码,应该使用动态sql

完成
TYPE NestArray IS TABLE OF VARCHAR2(50);
TYPE CharArray IS TABLE OF VARCHAR2(255) INDEX BY BINARY_INTEGER;

PROCEDURE SAMPLE(i_emp IN NestArray)

v_emp_name CharArray;

v_sql := 'SELECT emp_name FROM emp ';
v_sql  := v_sql || ' WHERE empid IN (SELECT column_value FROM TABLE('||i_emp||'))';

EXECUTE IMMEDIATE v_sql BULK COLLECT INTO v_emp_name;

end;

2 个答案:

答案 0 :(得分:0)

  

请参阅下面的代码段。它将描述解决方案。希望它有所帮助

--Create schema level type object 

CREATE OR REPLACE TYPE NestArray IS TABLE OF VARCHAR2(50);

CREATE OR REPLACE PROCEDURE EMP_BULK(p_empni IN NestArray)
AS
TYPE CharArray
IS
  TABLE OF VARCHAR2(255) INDEX BY BINARY_INTEGER;
  v_emp_name CharArray;
--  emp_id NestArray:=NestArray(1,2,3);
--  v_sql LONG;
BEGIN
  SELECT ename BULK COLLECT
  INTO v_emp_name
  FROM emp
  WHERE EMPno IN
    (SELECT COLUMN_VALUE FROM TABLE(p_empni)
    );
END;

EXEC EMP_BULK(NestArray(1,2,3));


----------------------------OUTPUT-------------------------------------------

PL/SQL procedure successfully completed.

答案 1 :(得分:0)

您不需要动态SQL,嵌套选择可以替换为MEMBER运算符。你可以这样做:

CREATE TYPE NestArray IS TABLE OF VARCHAR2(50);
CREATE TYPE CharArray IS TABLE OF VARCHAR2(255);


CREATE OR REPLACE PROCEDURE SAMPLE(
 i_emp   IN  NestArray,
 o_names OUT Chararray
)
IS
BEGIN
  SELECT emp_name
  BULK COLLECT INTO o_names
  FROM   emp
  WHERE  empid MEMBER OF i_emp;
END;
/