简体   繁体   English

Oracle Stored Procedure返回表的集合

[英]Oracle Stored Procedure returning collection of table

I want to write a procedure using collections. 我想用集合编写一个过程。

I have a table - employee - and I want to return the following: 我有一张桌子 - employee - 我想要退回以下内容:

  • TEST1: count of employees whose sal < 10000 TEST1: sal <10000的员工人数
  • TEST2: count of employees whose dept > 10 TEST2:部门> 10的员工人数
  • TEST3: count of employees whose hiredate >(SYSDATE-60) TEST3:雇用的员工人数>(SYSDATE-60)
  • TEST4: count of employees whose grade = 1 TEST4:等级= 1的员工人数

My final recordset or array table should return below values. 我的最终记录集或数组表应返回低于值。 TEST1, TEST2, TEST3, TEST4 are description values residing in DESCRIPTION TABLE where as count values are from employee table. TEST1,TEST2,TEST3,TEST4是驻留在DESCRIPTION TABLE中的描述值,其中计数值来自employee表。

Description   COUNT
TEST1         10 
TEST2         15
TEST3         25
TEST4         50

Please help with implementation. 请帮助实施。

This solution won't use your DESCRIPTION table to calculate counts dynamically, as that would be rather hard to achieve. 此解决方案不会使用您的DESCRIPTION表动态计算计数,因为这很难实现。 So, here's a solution with hard-coded TESTn descriptions. 所以,这是一个带有硬编码TESTn描述的解决方案。

First, create the record type: 首先,创建记录类型:

CREATE TYPE count_t AS OBJECT (
  description varchar2(100),
  cnt NUMBER(10)
);

Then, create the table type: 然后,创建表类型:

CREATE TYPE count_tt AS TABLE OF count_t;

Now, write the function: 现在,编写函数:

CREATE OR REPLACE FUNCTION counts RETURN count_tt
IS
  v_result count_tt;
BEGIN
  SELECT count_t(description, cnt)
  BULK COLLECT INTO v_result
  FROM (
    SELECT 
      count(CASE WHEN sal < 10000 THEN 1 END) TEST1,
      count(CASE WHEN dept > 10 THEN 1 END) TEST2,
      count(CASE WHEN hiredate > SYSDATE - 60 THEN 1 END) TEST3,
      count(CASE WHEN grade = 1 THEN 1 END) TEST4
    FROM employees
  ) t
  -- Behold, the power of unpivot!
  UNPIVOT (
    cnt FOR description IN ("TEST1", "TEST2", "TEST3", "TEST4")
  );

  RETURN v_result;
END counts;
/

Now, call the function, eg from SQL: 现在,调用函数,例如从SQL:

SELECT * FROM TABLE(counts)

Enjoy. 请享用。

By the way, I've written up a blog post comparing this solution from a performance perspective with others that do not use UNPIVOT 顺便说一下,我写了一篇博文, 将这个解决方案从性能角度与不使用UNPIVOT其他人进行比较

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM