2014-04-16 52 views
0

這是一個提供2列結果的函數。PostgreSQL - 返回多列的函數

在這個函數中有一個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; 

是否有返回行,而不使用循環的任何可能性?

如果是這樣,請分享我如何做到這一點。

而且我能否編寫一個函數來將記錄插入到表中而不使用循環?

幫我解決這個問題。

在此先感謝。

+0

我不接受哪一個但兩者給我的回答我期待的東西。因此,這兩個答案+1。 –

+2

請注意,您的查詢無效:您僅通過'circle'進行分組,但使用'label'作爲選定的列。 http://www.postgresql.org/docs/9.3/static/sql-select.html#SQL-GROUPBY – pozs

+0

需要標註。這是一個錯字錯誤。順便說一下,如果我不在'groupby'中包含標籤,查詢就不會運行。 –

回答

2

你不需要額外的類型定義。並返回多行,使用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; 
+0

+1,但忘了'group by circle'子句。如果'label'不在'group by'子句中,'label'也不是有效的列。 – pozs

+0

@pozs:謝謝,糾正(複製和粘貼錯誤) –

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;