postgresql 如何调用 Postgres 函数返回 SETOF 记录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2983501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-20 00:09:16  来源:igfitidea点击:

How to call Postgres function returning SETOF record?

postgresqlplpgsql

提问by Peter

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.

我不明白这个输出。我也尝试过使用 perform ,但我认为只有在函数不返回任何内容时才必须使用它。

回答by Frank Heikens

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:

编辑:您已将 OUT 参数或 RETURN TABLE() 与参数一起使用:

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();