如何使用oracle从存储的函数中检索多行

前端之家收集整理的这篇文章主要介绍了如何使用oracle从存储的函数中检索多行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试在oracle中创建一个返回多行的存储函数.

我的问题非常类似于this one,除了我想获取select *查询

简而言之,我想创建一个返回此查询结果的函数

select * from t_email_queue

我试过的是这个:

create or replace
PACKAGE email_queue AS 

  type t_email_queue_type is table of T_EMAIL_QUEUE%ROWTYPE;  

  FUNCTION lock_and_get return t_email_queue_type;

END email_queue;

create or replace
PACKAGE BODY email_queue AS 

    FUNCTION lock_and_get RETURN t_email_queue_type AS 
      queue_obj t_email_queue_type;

      cursor c (lockid in varchar2) is select * from t_email_queue where lockedby = lockid;
      lockid varchar2(100) := 'alf';
    BEGIN

      OPEN c(lockid);
      FETCH c bulk collect INTO queue_obj;

      return queue_obj;

    END lock_and_get;

END email_queue;

包编译得很好,但是当我尝试使用此查询调用它时

select * from table(email_queue.lock_and_get);

Oracle抛出以下错误

ORA-00902: invalid datatype
00902. 00000 -  "invalid datatype"
*Cause:    
*Action:
Error at Line: 1 Column: 20

我想Oracle希望我在架构级别创建我的返回类型,但是当我尝试时

create type t_email_queue_type is table of T_EMAIL_QUEUE%ROWTYPE;

甲骨文抱怨道

Type IMAIL.T_EMAIL_QUEUE_TYPE@imail dev
Error(1): PL/sql: Compilation unit analysis terminated
Error(2,37): PLS-00329: schema-level type has illegal reference to IMAIL.T_EMAIL_QUEUE

有人能指出我正确的方向吗?我在这里错过了什么?

谢谢阅读!

解决方法

对于sql类型,您不能执行%ROWTYPE,您必须键入每个列以匹配表*.

* sys.anydataset放在一边.但是沿着那条路走下去会有更复杂的编码.

例如如果你的桌子是

create table foo (id number,cola varchar2(1));

然后

create type email_queue_type is object (id number,cola varchar2(1));
/
create type t_email_queue_type as table of email_queue_type;
/

并使用该表email_queue_type_tab作为函数输出.

但我建议使用流水线功能,因为您当前的代码不可扩展.

例如:

sql> create table foo (id number,cola varchar2(1));

Table created.

sql>
sql> create type email_queue_type is object (id number,cola varchar2(1));
  2  /

Type created.

sql> create type t_email_queue_type as table of email_queue_type;
  2  /

Type created.

sql> insert into foo select rownum,'a' from dual connect by level <= 10;

10 rows created.

sql>
sql> create or replace PACKAGE email_queue AS
  2
  3
  4    FUNCTION lock_and_get return t_email_queue_type pipelined;
  5
  6  END email_queue;
  7  /

Package created.

sql> create or replace PACKAGE BODY email_queue AS
  2
  3      FUNCTION lock_and_get RETURN t_email_queue_type pipelined AS
  4        queue_obj t_email_queue_type;
  5
  6      BEGIN
  7
  8       for r_row in (select * from foo)
  9              loop
 10                pipe row(email_queue_type(r_row.id,r_row.cola));
 11              end loop;
 12
 13      END lock_and_get;
 14
 15  END email_queue;
 16  /

Package body created.

sql> select * from table(email_queue.lock_and_get());

        ID C
---------- -
         1 a
         2 a
         3 a
         4 a
         5 a
         6 a
         7 a
         8 a
         9 a
        10 a

10 rows selected.

sql>

猜你在找的Oracle相关文章