是否可以从 postgres 函数返回多个不同类型的结果集?
类似于:
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;
我不想使用连接,因为用户可以使用多个电话。避免使用游标也很好。 这在 MS SQL 中是可能的,我想在 postgres 中做同样的事情。
最佳答案
经过查找,没有找到更好的使用游标的解决方案。
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;
并调用:
BEGIN;
SELECT load_page(mySession);
FETCH ALL IN "<server cursor 1>";
FETCH ALL IN "<server cursor 2>";
COMMIT;
关于postgresql - Postgres 函数 : return multiple tables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36717138/