PostgreSQL - 返回多列的函数

时间:2014-04-16 10:14:33

标签: database postgresql

这是一个提供2列结果的函数。

在此功能中,Loop用于返回结果。

功能:

Create Type Repeat_rs as (
label text,
count bigint
)

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;

是否有可能在不使用循环的情况下返回行?

如果是这样,请分享我们如何做到这一点。

我是否可以编写一个函数来将记录插入到表中而不使用循环?

帮我解决这个问题。

提前致谢。

2 个答案:

答案 0 :(得分:7)

您不需要额外的类型定义。要返回多行,请使用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)

您可以使用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;
相关问题