PL/SQL - 该函数不 return 多行

PL/SQL - The function deosn't return multiple rows

我想从“employees”tableselect10 名高薪雇员,但函数只返回 1 行。在这种情况下如何获得多行?我对 selecting 员工的子查询运行良好,但是当我调用函数时 returns 1 行。

这是我的代码:

CREATE OR REPLACE FUNCTION f_sal
RETURN Varchar2

IS cursor c_emp is (select first_name, last_name from (select first_name, last_name, row_number() 
over(order by salary desc) as ranking from employees) where ranking <= 10);

v_first employees.first_name%type;
v_last employees.last_name%type;

begin
open c_emp;
fetch c_emp into v_first, v_last;
close c_emp;
return v_first || ' ' || v_last;

EXCEPTION
  WHEN NO_DATA_FOUND
  THEN
     dbms_output.put_line('Error');
     when others then dbms_output.put_line('Other Error');
END;
  
select f_sal from dual;

选项 1:使用集合

CREATE FUNCTION f_sal
RETURN SYS.ODCIVARCHAR2LIST
IS 
  v_names SYS.ODCIVARCHAR2LIST;
BEGIN
  SELECT first_name || ' ' || last_name
  BULK COLLECT INTO v_names
  FROM   employees
  ORDER BY salary DESC
  FETCH FIRST 10 ROWS ONLY;

  return v_names;
END;
/

然后:

SELECT * FROM TABLE(f_sal);

选项 2:使用流水线函数并将游标迭代到集合中

CREATE OR REPLACE FUNCTION f_sal
RETURN SYS.ODCIVARCHAR2LIST PIPELINED
IS
BEGIN
  FOR n IN (
    SELECT first_name || ' ' || last_name AS name
    FROM   employees
    ORDER BY salary DESC
    FETCH FIRST 10 ROWS ONLY
  )
  LOOP
    PIPE ROW (n.name);
  END LOOP;
END;
/

然后:

SELECT * FROM TABLE(f_sal);

选项 3:Return 光标

CREATE FUNCTION f_sal
RETURN SYS_REFCURSOR
IS 
  v_names SYS_REFCURSOR;
BEGIN
  OPEN v_names FOR
    SELECT first_name || ' ' || last_name AS name
    FROM   employees
    ORDER BY salary DESC
    FETCH FIRST 10 ROWS ONLY;

  return v_names;
END;
/

然后:

DECLARE
  v_names SYS_REFCURSOR := f_sal();
  v_name VARCHAR2(100);
BEGIN
  LOOP
    FETCH v_names INTO v_name;
    EXIT WHEN v_names%NOTFOUND;
    DBMS_OUTPUT.PUT_LINE( v_name );
  END LOOP;
END;
/

db<>fiddle here