Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL function returning multiple result sets

Tags:

Is it possible to return multiple result sets from a Postgres function, like in MSSQL:

CREATE PROCEDURE test

AS

SELECT * FROM first_table

SELECT * FROM second_table
like image 393
Markus Avatar asked Apr 16 '09 15:04

Markus


People also ask

Can PostgreSQL stored procedure return resultset?

Both stored procedures and user-defined functions are created with CREATE FUNCTION statement in PostgreSQL. To return one or more result sets (cursors in terms of PostgreSQL), you have to use refcursor return type.

What is Refcursor in PostgreSQL?

PostgreSQL provides you with a special type called REFCURSOR to declare a cursor variable.

Can a PostgreSQL function return a table?

PostgreSQL returns a table with one column that holds the array of films. In practice, you often process each individual row before appending it in the function's result set.


1 Answers

A simpler way has been around since PostgreSQL 8.3:

CREATE FUNCTION test()
  RETURNS SETOF first_table AS
$func$
BEGIN

RETURN QUERY
SELECT * FROM first_table;

RETURN QUERY
SELECT * FROM second_table;   -- has to return same rowtype as first_table!

END
$func$ LANGUAGE plpgsql;

Call:

SELECT * FROM test();

Both result sets are appended to a single set returned from the function.
See the manual for RETURN QUERY.

like image 53
Erwin Brandstetter Avatar answered Sep 21 '22 06:09

Erwin Brandstetter