How to call Postgres function returning SETOF record?
I have written the following function:
-- Gets stats for all markets
CREATE OR REPLACE FUNCTION GetMarketStats (
)
RETURNS SETOF record
AS
$$
BEGIN
SELECT 'R approved offer' AS Metric,
SUM(CASE WHEN M.MarketName = 'A+' AND M.Term = 24 THEN LO.Amount ELSE 0 end) AS MarketAPlus24,
SUM(CASE WHEN M.MarketName = 'A+' AND M.Term = 36 THEN LO.Amount ELSE 0 end) AS MarketAPlus36,
SUM(CASE WHEN M.MarketName = 'A' AND M.Term = 24 THEN LO.Amount ELSE 0 end) AS MarketA24,
SUM(CASE WHEN M.MarketName = 'A' AND M.Term = 36 THEN LO.Amount ELSE 0 end) AS MarketA36,
SUM(CASE WHEN M.MarketName = 'B' AND M.Term 开发者_如何转开发= 24 THEN LO.Amount ELSE 0 end) AS MarketB24,
SUM(CASE WHEN M.MarketName = 'B' AND M.Term = 36 THEN LO.Amount ELSE 0 end) AS MarketB36
FROM "Market" M
INNER JOIN "Listing" L ON L.MarketID = M.MarketID
INNER JOIN "ListingOffer" LO ON L.ListingID = LO.ListingID;
END
$$
LANGUAGE plpgsql;
And when trying to call it like this...
select * from GetMarketStats() AS (
Metric VARCHAR(50),
MarketAPlus24 INT,
MarketAPlus36 INT,
MarketA24 INT,
MarketA36 INT,
MarketB24 INT,
MarketB36 INT);
I get an error:
ERROR: query has no destination for result data
HINT: If you want to discard the results of a SELECT, use PERFORM instead.
CONTEXT: PL/pgSQL function "getmarketstats" line 2 at SQL statement
I don't understand this output. I've tried using perform too, but I thought one only had to use that if the function doesn't return anything.
Your function doesn't maken sense, it doesn't return anything. It looks like a VIEW, so why don't you create a view?
Edit: You have use the OUT parameters or RETURN TABLE() with the parameters:
CREATE OR REPLACE FUNCTION my_func(OUT o_id INT, OUT o_bar TEXT)
RETURNS SETOF RECORD AS
$$
BEGIN
RETURN QUERY SELECT id, bar FROM foo;
END;
$$
LANGUAGE plpgsql;
SELECT * FROM my_func();
精彩评论