Search code examples
postgresqlplpgsqlstored-functionsout-parameters

Manipulating OUT parameters from function


I have a function that has two OUT parameters. I want to call that function from another function and put those OUT parameters to two variables. Although I saw some similar questions here, I have some troubles with saving those two parameters to two variables.

Here is the code:

CREATE OR REPLACE FUNCTION some_function_2(OUT out_code2 integer, OUT out_message2 text)
  RETURNS RECORD AS
$BODY$
DECLARE
   --s_code integer;
   --s_message text;
BEGIN
    --Calling first function, return two out parameters and end function
    SELECT some_function_1() INTO out_code2, out_message2;

END
$BODY$
  LANGUAGE plpgsql VOLATILE

CREATE OR REPLACE FUNCTION some_function_1(OUT out_code1 integer, OUT out_message1 text)
  RETURNS RECORD AS
$BODY$
DECLARE
   --s_code integer;
   --s_message text;
BEGIN

   out_code1:= 1;
   out_message1:= 'TEST';

END
$BODY$
  LANGUAGE plpgsql VOLATILE

Solution

  • In some_function_2() you should use a query which returns two values, not a record:

    CREATE OR REPLACE FUNCTION some_function_2(OUT out_code2 integer, OUT out_message2 text)
      RETURNS RECORD AS
    $BODY$
    DECLARE
    BEGIN
        --Calling first function, return two out parameters and end function
        SELECT out_code1, out_message1 FROM some_function_1() INTO out_code2, out_message2;
    END
    $BODY$
      LANGUAGE plpgsql VOLATILE;