首页 文章

PostgreSQL - 返回多列的函数

提问于
浏览
0

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

在这个函数中,有一个 Loop 用于返回结果 .

Function :

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 回答

  • 3

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

    您可以使用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;
    

相关问题