如何从PL-SQL函数返回2个值?
答案 0 :(得分:13)
我不主张为第二个值创建一个带OUT参数的函数,因为我喜欢将函数视为一个纯概念:函数对一个或多个输入执行操作以生成一个输出。它不应该改变任何论点或任何其他“副作用”。
因此,如果您需要两个输出,请改为编写过程:
procedure get_sqrt_and_half
( p_input number
, p_sqrt OUT number
, p_half OUT number
)
is
begin
p_sqrt := sqrt(p_input);
p_half := p_input/2;
end;
答案 1 :(得分:6)
函数只能返回单个SQL类型,但可以是具有多个值的用户定义类型。在我建议将其作为解决方案之前,我需要了解更多有关实际最终要求的信息,但这是可能的。
create or replace type a_b is object (a number, b number);
/
create or replace function ret_a_b return a_b is
begin
return a_b(1,2);
end;
/
select ret_a_b from dual;
select d.rab.a, d.rab.b from (select ret_a_b rab from dual) d;
答案 2 :(得分:4)
您可以直接返回一个值,另一个值作为OUT参数。或者,您返回包含两个值的记录。在大多数情况下,第一种选择更容易。
答案 3 :(得分:1)
**If you are wanting to use it in SQL, then you would need a pipelined function e.g.**
CREATE OR REPLACE TYPE myemp AS OBJECT
( empno number,
ename varchar2(10),
job varchar2(10),
mgr number,
hiredate date,
sal number,
comm number,
deptno number
);
CREATE OR REPLACE TYPE myrectable AS TABLE OF myemp ;
enter code here
CREATE OR REPLACE FUNCTION pipedata(p_min_row number, p_max_row number) RETURN myrectable PIPELINED IS
v_obj myemp := myemp(NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
BEGIN
FOR e IN (select *
from (
select e.*
,rownum rn
from (select * from emp order by empno) e
)
where rn between p_min_row and p_max_row)
LOOP
v_obj.empno := e.empno;
v_obj.ename := e.ename;
v_obj.job := e.job;
v_obj.mgr := e.mgr;
v_obj.hiredate := e.hiredate;
v_obj.sal := e.sal;
v_obj.comm := e.comm;
v_obj.deptno := e.deptno;
PIPE ROW (v_obj);
END LOOP;
RETURN;
END;
SQL> select * from table(pipedata(1,5));
答案 4 :(得分:0)
尝试使用OUT
参数:
create or replace function f(a IN NUMBER, b OUT NUMBER) RETURN NUMBER IS
BEGIN
b := a;
RETURN a;
END f;