暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Oracle 关于使用包装外收集的问题

askTom 2017-06-16
360

问题描述

嗨,

我有这个要求,我需要在PL/SQL包中的集合中收集数据,并在SQL * Plus中的查询中使用该集合,如下面的脚本所示。但是我不想使用这个。有办法做到这一点吗?

在LiveSQL网址中,请参阅语句53、54和61了解这些步骤

create or replace package dfr_pkg as 
l_emp NUMBERLIST_TBL; -- a nested table  
end dfr_pkg;

create or replace package body dfr_pkg as 
procedure p1 as  
begin 
select empno bulk collect into dfr_pkg.l_emp 
from emp where rownum <=10; 
end; 
begin 
p1(); 
end dfr_pkg;


SQL> select column_name from table(cast(dfr_pkg.l_emp as NUMBERLIST_TBL));


谢谢,
吉里什

专家解答

简短的答案是你不能。

在SQL中使用PL/SQL数组仅在PL/SQL中工作:

create table emp (
  empno      number( 4,0 ),
  ename      varchar2( 10 ),
  job        varchar2( 9 ),
  mgr        number( 4,0 ),
  hiredate   date,
  sal        number( 7,2 ),
  comm       number( 7,2 ),
  deptno     number( 2,0 ),
  constraint pk_emp primary key ( empno )
);

insert into emp values (
  7839,  'KING',  'PRESIDENT',
  null,  to_date( '17-11-1981','dd-mm-yyyy' ),
  5000,  null,  10
);

create type numberlist_tbl as
  table of number;
/

create or replace package dfr_pkg as
  l_emp numberlist_tbl; -- a nested table  
  procedure p2;
end dfr_pkg;
/

create or replace package body dfr_pkg as

  procedure p1
    as
  begin
    select empno
    bulk collect into
      dfr_pkg.l_emp
    from emp
    where rownum <= 10;

  end;

  procedure p2
    is
  begin
    p1 ();
    for rws in (
      select *
      from table ( dfr_pkg.l_emp )
    ) loop
      dbms_output.put_line( rws.column_value );
    end loop;

  end p2;

begin
  p1 ();
end dfr_pkg;
/

exec dfr_pkg.p2;

7839

select *
from table ( cast( dfr_pkg.l_emp as numberlist_tbl ) );

SQL Error: ORA-06553: PLS-221: 'L_EMP' is not a procedure or is undefined


更长的答案是您可以创建一个流水线表函数来返回数据。

create or replace package dfr_pkg as
  l_emp numberlist_tbl; -- a nested table  
  procedure p2;
  function f return numberlist_tbl;
end dfr_pkg;
/

create or replace package body dfr_pkg as

  procedure p1
    as
  begin
    select empno
    bulk collect into
      dfr_pkg.l_emp
    from emp
    where rownum <= 10;

  end;

  procedure p2
    is
  begin
    p1 ();
    for rws in (
      select *
      from table ( dfr_pkg.l_emp )
    ) loop
      dbms_output.put_line( rws.column_value );
    end loop;

  end p2;

  function f return numberlist_tbl as
    retval   numberlist_tbl := numberlist_tbl();
  begin
    for rws in (
      select *
      from table ( dfr_pkg.l_emp )
    ) loop
      retval.extend;
      retval( retval.last )   := rws.column_value;
    end loop;

    return retval;
  end;

begin
  p1 ();
end dfr_pkg;
/
select * from table ( dfr_pkg.f );

Result Sequence
---------------
           7839

「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论