PostgreSQL函数返回表

时间:2018-05-21 17:06:29

标签: sql postgresql function

我想在PostgreSQL上设置一个返回表的函数。这是函数的源代码:

   CREATE OR REPLACE FUNCTION feiertag(inDate Date) 
     RETURNS TABLE (eingabeDatum DATE, f_heute INT, f_1 INT, f_2 INT, f_3 INT, f_5 INT) 
    AS $$
            DECLARE
              f_heute integer := 0;
              f_1 integer := 0;
              f_2 integer := 0;
              f_3 integer := 0;
              f_5 integer := 0;
            BEGIN
                    SELECT 1 INTO f_heute FROM feiertage where datum = inDate;
                    SELECT 1 INTO f_1 FROM feiertage where datum = (inDate + interval '1' day);
                    SELECT 1 INTO f_2 FROM feiertage where datum = (inDate + interval '2' day);
                    SELECT 1 INTO f_3 FROM feiertage where datum = (inDate + interval '3' day);
                    SELECT 1 INTO f_5 FROM feiertage where datum = (inDate + interval '5' day);

   RETURN QUERY SELECT inDate as eingabeDatum, coalesce(f_heute, 0) as f_heute, coalesce(f_1,0) as f_1, coalesce(f_2,0) as f_2, coalesce(f_3,0) as f_3, coalesce(f_5,0) as f_5 ;
            END;
    $$ LANGUAGE plpgsql;

调用该函数只返回一个带有','分隔值的列:

psql (9.5.12)
Type "help" for help.

tarec=> select feiertag('2017-01-01');
        feiertag        
------------------------
 (2017-01-01,1,0,0,0,0)
(1 row)

我期望不同的列(每个值一个,因为在函数的开头指定了表),而不是只有一个具有所有值。有谁知道为什么会发生这种情况以及如何解决这个问题?

由于 蒂莫

1 个答案:

答案 0 :(得分:2)

使用

SELECT *
       FROM feiertag('2017-01-01');

而不是

SELECT feiertag('2017-01-01');

将结果作为表格。

(将该功能视为表格。)