Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plpgsql: calling a function with 2 OUT parameters

I'm trying to fetch to values from a plpgsql function with 2 OUT paramenters but I have some problem.

These are the functions:

CREATE OR REPLACE FUNCTION get_test(OUT x text, OUT y text)
AS $$
BEGIN
   x := 1;
   y := 2;
END;
$$  LANGUAGE plpgsql;
----------------------------------------------------------------

CREATE OR REPLACE FUNCTION get_test_read()
RETURNS VOID AS $$
DECLARE
   xx text;
   yy text;
BEGIN

   SELECT get_test() INTO xx, yy;
   
   RAISE INFO 'x: <%>', xx;
   RAISE INFO 'y: <%>', yy;

END;
$$  LANGUAGE plpgsql;

The output of the command:

select get_test_read();

INFO: x: <(1,2)

INFO: y: <>

get_test_read


So both the values go to the first parameter. I cannot find some example on how to call a function like this.

like image 493
marco Avatar asked May 14 '12 13:05

marco


People also ask

How do you call a function in plpgsql?

The normal syntax to call another PL/pgSQL function from within PL/pgSQL is to either reference the function in a SQL SELECT statement, or during the assignment of a variable. For example: SELECT function_identifier ( arguments ); variable_identifier := function_identifier ( arguments );

Can we use out and inout parameter in function?

If you have an OUT parameter in the function then it cannot be called from SQL expression.

What does := mean in plpgsql?

:= is the assignment operator in PL/pgSQL.

What is Inout in PostgreSQL?

The INOUT modeThe function changes the argument and returns the updated value. The following swap function accepts two integers and their values: create or replace function swap( inout x int, inout y int ) language plpgsql as $$ begin select x,y into y,x; end; $$;


2 Answers

As you have 2 OUT params, your function will return a record.

In order to get all values you should use function as the source of your data and put it into the FROM clause like this:

SELECT * FROM get_test() INTO xx, yy;
like image 135
vyegorov Avatar answered Oct 18 '22 15:10

vyegorov


SELECT * INTO xx, yy FROM get_test();

UPDATE:

Explanation:

Modifying the second function:

CREATE OR REPLACE FUNCTION get_test_read()
RETURNS VOID AS $$
DECLARE
   xx text;
   yy text;
BEGIN

   SELECT * INTO xx, yy FROM get_test();
   
   RAISE INFO 'x: <%>', xx;
   RAISE INFO 'y: <%>', yy;

END;
$$  LANGUAGE plpgsql;  

This is similar to SELECT INTO with TABLE, where only get 2 values:

SELECT "FIELD1", "FIELD2" INTO variable1, variable2 FROM "TABLE" WHERE ...

Npgsql Basic Usage

PL/pgSQL Function Parameter Modes: IN, OUT, INOUT

like image 33
Ejrr1085 Avatar answered Oct 18 '22 13:10

Ejrr1085