简体   繁体   English

创建函数返回 sys_refcursor

[英]Create function returns sys_refcursor

How to create a function to display all employees of one department?如何创建一个功能来显示一个部门的所有员工? I'd tried this code but it returns only "cursor" value.我试过这段代码,但它只返回“光标”值。

CREATE OR REPLACE FUNCTION emp_dept (dept_id IN NUMBER)
RETURN SYS_REFCURSOR
IS 
emp_name SYS_REFCURSOR;

BEGIN
OPEN emp_name
FOR SELECT last_name
     FROM employees
    WHERE department_id = dept_id;

RETURN emp_name;
END emp_dept;

You may use these options to read and display output from the cursor that's returned from your function.您可以使用这些选项来读取和显示从您的函数返回的光标的输出。

Use a simple select使用简单的选择

select emp_dept(10) from dual;

Result结果

EMP_DEPT(10)        
--------------------
CURSOR STATEMENT : 1

CURSOR STATEMENT : 1

LAST_NAME                
-------------------------
Whalen

Use DBMS_SQL.RETURN_RESULT ( Oracle 12c and above)使用DBMS_SQL.RETURN_RESULT (Oracle 12c 及以上)

DECLARE
l_cur SYS_REFCURSOR := emp_dept(10) ;
BEGIN
   DBMS_SQL.RETURN_RESULt(l_cur);
END;
/

Result结果

PL/SQL procedure successfully completed.

ResultSet #1


LAST_NAME                
-------------------------
Whalen

FETCH from the cursor into a local collection.从游标FETCH到本地集合。 A slight variation could be also be used to fetch into a scalar variable.也可以使用轻微的变化来获取标量变量。

DECLARE
l_cur SYS_REFCURSOR := emp_dept(10) ;
TYPE l_last_name_tab IS TABLE OF employees.last_name%TYPE;
l_lnt l_last_name_tab;
BEGIN
   FETCH l_cur BULK COLLECT INTO l_lnt;

   for i in 1..l_lnt.count
   loop
    dbms_output.put_line(l_lnt(i));
   end loop;
END;
/

Result结果

Whalen


PL/SQL procedure successfully completed.

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

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