views:

390

answers:

1

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.

+1  A: 

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();
Frank Heikens
I come from a SQL Server world. I expected similar behaviour where any SELECT statement is returned. I'll try changing to a view. Thanks
Peter
Assuming I did want to pass a parameter, how do I go about returning the result of my SQL query?
Peter
See example, RETURNS TABLE(int, text) would be another option.
Frank Heikens
The point that addresses the actual question is the use of "RETURN QUERY" to make the following SELECT's result set the result of the function. The OUT parameters/RETURNS TABLE just make invocation a lot easier.
araqnid