如何从plsql存储过程返回集合类型

时间:2013-01-09 22:38:35

标签: oracle plsql

我在PL / SQL中有以下存储过程:

CREATE OR REPLACE PROCEDURE sample_procedure AS 
DECLARE 
    TYPE list_of_names_t 
      IS TABLE OF emp.emp_index%TYPE; 
    ignoreIndexes LIST_OF_NAMES_T := List_of_names_t();
BEGIN
-- Logic here which fills the values in the collection ignoreIndexes   
END;

从外部调用此存储过程时如下所示:

    SET SERVEROUTPUT ON
    EXEC sample_procedure
    -- Line YY

@Eline YY,我想从emp表中检索记录不存在于存储过程中准备的ignoreindexes集合中的记录。

1)如何将在存储过程中创建的嵌套表ignoreindexes返回给外界,以便我可以使用该表中的索引

先谢谢

1 个答案:

答案 0 :(得分:8)

首先,需要在过程外声明它们的类型,以使类型定义对过程外的代码可见。您可以在SQL

中声明类型
CREATE TYPE list_of_names_t
    AS TABLE OF NUMBER;

或者您可以在PL / SQL中声明它

CREATE OR REPLACE PACKAGE types_package
AS
  TYPE list_of_names_t
    IS TABLE OF emp.emp_index%type;
END;

您的程序必须使用并返回SQL类型

CREATE OR REPLACE PROCEDURE sample_procedure( 
  p_ignore_indexes OUT list_of_names_t 
) 
AS 
BEGIN
  -- Logic here which fills the values in the collection p_ignore_indexes 
END;

或PL / SQL类型

CREATE OR REPLACE PROCEDURE sample_procedure( 
   p_ignore_indexes OUT types_package.list_of_names_t 
) 
AS 
BEGIN
  -- Logic here which fills the values in the collection p_ignore_indexes 
END;

当然,如果你的代码的目的是返回一个集合,那么编写一个函数比一个过程更有意义

CREATE OR REPLACE FUNCTION sample_function
  RETURN types_package.list_of_names_t
AS 
  ignore_indexes types_package.list_of_names_t;
BEGIN
  -- Logic here which fills the values in the collection ignore_indexes 
  RETURN ignore_indexes;
END;

当您调用该程序时,您会执行类似

的操作
DECLARE
  l_ignore_indexes types_package.list_of_names_t;
BEGIN
  l_ignore_indexes := sample_function; 
  -- Do something with l_ignore_indexes
END;

DECLARE
  l_ignore_indexes types_package.list_of_names_t;
BEGIN
  sample_procedure( l_ignore_indexes );
  -- Do something with l_ignore_indexes
END;