PostgreSQL - 返回多列的函数

6
以下是一个提供2列结果的函数。
在这个函数中,使用了循环来返回结果。
函数如下:
创建重复_rs类型: ``` Create Type Repeat_rs as ( label text, count bigint ) ```
创建Repeat函数: ``` CREATE OR REPLACE FUNCTION Repeat(fromDate date,toDate date) returns SETOF Repeat_rs AS $$ Declare someVariableName Repeat_rs; BEGIN For someVariableName in ( SELECT label, count(*) AS Cnt from test where date between fromDate and toDate group by circle ) Loop Return Next someVariableName; End Loop; Return; END; $$ LANGUAGE plpgsql; ```
有没有可能不使用循环返回行?
如果可以,请告诉我如何做到。
我能否编写一个函数将记录插入表中而不使用循环?
帮我解决这个问题。谢谢。

我不知道该接受哪一个,但两个答案都给了我期望的答案。因此,两个答案都加一分。 - Unknown User
2
请注意,您的查询无效:您仅按circle分组,但将label用作所选列。http://www.postgresql.org/docs/9.3/static/sql-select.html#SQL-GROUPBY - pozs
需要加标签。那是一个打字错误。顺便说一下,如果我不在 groupby 中包含标签,查询将无法运行。 - Unknown User
如果a_horse_with_no_name的回答解决了你的问题,那么你应该接受他的答案。 - Kenny Evitt
2个回答

19

你不需要额外的类型定义。要返回多行,请使用return query

像这样:

CREATE OR REPLACE FUNCTION Repeat(fromDate date,toDate date)
  returns table (label text, cnt bigint)
AS 
$$
BEGIN
    Return query 
       SELECT label, count(*) AS Cnt 
       from test 
       where date between fromDate and toDate
       group by label;
END;
$$
LANGUAGE plpgsql;

您甚至不需要一个PL/pgSQL函数,您可以使用一个简单的SQL函数来实现这个功能:

CREATE OR REPLACE FUNCTION Repeat(fromDate date, toDate date)
  returns table (label text, cnt bigint)
AS 
$$
   SELECT label, count(*) AS Cnt 
   from test 
   where date between fromDate and toDate
   group by label;
$$
LANGUAGE sql;

1
+1,但忘了加上“group by circle”子句。如果"label"不在"group by"子句中,则其不是有效列。 - pozs

-2

您可以使用以下SELECT查询将值插入表中:

CREATE OR REPLACE FUNCTION Repeat(fromDate date,toDate date)
returns VOID 
AS 
$$

BEGIN
    INSERT INTO TABLE_NAME
         SELECT label, count(*) AS Cnt from test where date between fromDate and toDate group by circle
END;
$$
LANGUAGE plpgsql;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接