2

我在 PL/SQL 中编写了以下代码,它可以工作:

declare 
type deliveryStat_o IS record  (
       warehouseName varchar2(20), shipMode char(30), thirty_days number, sixty_days number,
        ninety_days number, oneTwenty_days number, veryLate number
   );
type deliveryStat_t is TABLE OF deliveryStat_o;

statTable deliveryStat_t;

begin

        SELECT w_warehouse_name, sm_type, 1 AS thirty_days, 1 AS sixty_days, 1 AS ninety_days, 
               1 AS oneTwenty_days, 1 AS veryLateDelivery
        bulk collect into statTable
        FROM   catalog_sales, warehouse, ship_mode, date_dim 
        WHERE   cs_ship_date_sk = d_date_sk 
               AND cs_warehouse_sk = w_warehouse_sk 
               AND cs_ship_mode_sk = sm_ship_mode_sk 
        GROUP  BY w_warehouse_name, 
                  sm_type ;
end;

如何在返回嵌套集合 statTable的表函数中执行此操作。我知道这可能可以使用显式游标来完成;但是,是否可以在不使用光标的情况下做到这一点?

4

1 回答 1

3

对于上下文,我从这个作为基础开始

SQL> set serverout on
SQL> declare
  2    type deliveryStat_o IS record  (
  3           empno number, ename varchar2(20)
  4       );
  5    type deliveryStat_t is TABLE OF deliveryStat_o;
  6
  7    statTable deliveryStat_t;
  8
  9  begin
 10
 11          SELECT empno, ename
 12          bulk collect into statTable
 13          FROM   emp;
 14    dbms_output.put_line('recs='||statTable.count);
 15  end;
 16  /
recs=14

PL/SQL procedure successfully completed.

要将其转换为允许表函数,那么这些类型需要是 SQL 类型,因此

SQL> create or replace
  2  type deliveryStat_o as object (
  3  empno number, ename varchar2(20)
  4       );
  5  /

Type created.

SQL> create or replace
  2  type deliveryStat_t as table of deliveryStat_o
  3  /

Type created.

现在完成了,查询必须返回一个对象表,所以

SQL> set serverout on
SQL> declare
  2    statTable deliveryStat_t;
  3  begin
  4
  5          SELECT deliveryStat_o(empno, ename)
  6          bulk collect into statTable
  7          FROM   emp;
  8    dbms_output.put_line('recs='||statTable.count);
  9  end;
 10  /
recs=14

PL/SQL procedure successfully completed.

现在可以很容易地转换为表函数

SQL> create or replace
  2  function my_func return deliveryStat_t is
  3    statTable deliveryStat_t;
  4  begin
  5
  6          SELECT deliveryStat_o(empno, ename)
  7          bulk collect into statTable
  8          FROM   emp;
  9          return statTable;
 10  end;
 11  /

Function created.

SQL>  select * from my_func();

     EMPNO ENAME
---------- --------------------
      7369 SMITH
      7499 ALLEN
      7521 WARD
      7566 JONES
      7654 MARTIN
      7698 BLAKE
      7782 CLARK
      7788 SCOTT
      7839 KING
      7844 TURNER
      7876 ADAMS
      7900 JAMES
      7902 FORD
      7934 MILLER

14 rows selected.

如果您要返回很多行,请考虑使用流水线函数来避免将所有行收集到嵌套表中的内存开销

于 2020-10-13T04:10:19.453 回答