postgresql returns the result set

Single result set

(1) use return query to create a function

CREATE OR REPLACE FUNCTION get_one_record()
 RETURNS SETOF RECORD as
$$
DECLARE
    v_rec RECORD;
BEGIN
   
   return query ( SELECT * FROM public.config );
   return;
END;
$$
LANGUAGE PLPGSQL;

Query results:

postgres=# SELECT * FROM get_one_record() t(code varchar,name VARCHAR);
 code |      name
------+----------------
 200  | Successful connection
 404  | Server not found
 500  | Server internal error
 401  | Unauthorized
 503  | Server not available
(5 rows)

(2) use cursor mode

CREATE OR REPLACE FUNCTION public.get_one_refcursor(refcursor)
RETURNS refcursor AS $body$
BEGIN
OPEN $1 for SELECT * FROM public.config;
RETURN $1;
END;
$body$
LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER;

Query results:

postgres=# begin;
BEGIN
kf8193=# select * from get_one_refcursor('aa');
 get_one_refcursor
-------------------
 aa
(1 row)

postgres=# fetch all in "aa";
 code |      name
------+----------------
 200  | Successful connection
 404  | Server not found
 500  | Server internal error
 401  | Unauthorized
 503  | Server not available
(5 rows)

postgres=# commit;
COMMIT

Multiple result sets

Multiple result sets can only be returned in cursor mode

CREATE OR REPLACE FUNCTION public.get_more_refcursor(refcursor,refcursor)
RETURNS SETOF refcursor AS $body$
BEGIN
OPEN $1 for SELECT * FROM public.config limit 5;
RETURN NEXT $1;
OPEN $2 for SELECT * FROM public.flink;
RETURN NEXT $2;
END;
$body$
LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER;

Query results:

postgres=# select * from get_more_refcursor('a','b');
 get_more_refcursor
--------------------
 a
 b
(2 rows)

postgres=# fetch all from a;
 code |      name
------+----------------
 200  | Successful connection
 404  | Server not found
 500  | Server internal error
 401  | Unauthorized
 503  | Server not available
(5 rows)

postgres=# fetch all from b;
 word | count |     update_time
------+-------+---------------------
 aa   |     1 | 2019-05-09 10:56:10
 bb   |     3 | 2019-05-09 10:56:10
 bb   |     3 | 2019-05-09 10:56:15
 aa   |     3 | 2019-05-09 10:56:15
 aa   |     2 | 2019-05-09 10:56:20
(5 rows)

postgres=# commit;
COMMIT

Contrast:

return query is easy to operate, but you must specify the type of the returned result.
The cursor returns the result set randomly, but it can't get the result directly. You need to query in a transaction. But you can return more than one result set at a time.

Added by Mythic Fr0st on Wed, 30 Oct 2019 21:49:53 +0200