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.
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.
PostgreSQL provides you with a special type called REFCURSOR to declare a cursor variable.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With