Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres function: return multiple tables

Is it possible to return several result sets of different types from postgres function?

Something like:

CREATE OR REPLACE FUNCTION getUserById()
RETURNS setof ???
AS
$$
BEGIN

return query select id, name /* and other columns */ from users where id = 1;
return query select id, phone_number from user_phones where user_id = 1

END
$$
LANGUAGE plpgsql;

I don't want to use joins because several phones for user are possible. Also it would be great to avoid using cursors. It's possible in MS SQL and I want to do the same thing in postgres.

like image 572
user1820686 Avatar asked Apr 19 '16 11:04

user1820686


People also ask

How do I return multiple tables in PostgreSQL?

Defining the functionCREATE FUNCTION get_class(class integer) RETURNS SETOF students AS $$ BEGIN RETURN QUERY SELECT * FROM students WHERE students. class_id = class; END; $$ LANGUAGE plpgsql; This function, called get_class , has one argument class which represents the identifier for the class.

What is Refcursor in PostgreSQL?

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

Can Postgres stored procedure return 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. The following example illustrates the idea.


Video Answer


1 Answers

After the seek, could not find any better solutions as use of cursors.

CREATE FUNCTION load_page(_session INT) RETURNS setof refcursor AS
$$
DECLARE c_top_items refcursor;
DECLARE c_shopping_cart refcursor;
BEGIN
    OPEN c_top_items FOR
        SELECT t.name, t.description
        FROM top_item t
        ORDER BY t.popularity DESC
        LIMIT 10;
    RETURN NEXT c_top_items;
    OPEN c_shopping_cart FOR
        SELECT c.product_id, c.product_name, c.quantity
        FROM shopping_cart c
        WHERE c.session_id = _session
        ORDER BY c.id;
    RETURN NEXT c_shopping_cart;
END;
$$ LANGUAGE plpgsql;

And calling:

BEGIN;
SELECT load_page(mySession);
FETCH ALL IN "<server cursor 1>";
FETCH ALL IN "<server cursor 2>";
COMMIT;
like image 199
Janis S. Avatar answered Oct 13 '22 02:10

Janis S.