Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return 2 values from a PL-SQL function

Tags:

oracle

plsql

How can i return 2 values from a PL-SQL function?

like image 489
shirel Avatar asked Aug 17 '10 07:08

shirel


3 Answers

I would not advocate creating a function with an OUT parameter for the second value, because I like to think of functions as a pure concept: a function performs an operation on one or more inputs to produce one output. It shouldn't change any of its arguments or have any other "side effects".

So if you need two outputs, write a procedure instead:

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;
like image 154
Tony Andrews Avatar answered Nov 20 '22 12:11

Tony Andrews


A function can only return a single SQL type, but that can be a user-defined type with multiple values. I'd need to know more about the actual end requirements before I'd recommend this as a solution, but it is a possibility.

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;
like image 45
Gary Myers Avatar answered Nov 20 '22 12:11

Gary Myers


You can return one value directly and another one as an OUT parameter. Or you return a record that contains both values. The first option is, in most cases, simpler to do.

like image 31
Erich Kitzmueller Avatar answered Nov 20 '22 13:11

Erich Kitzmueller