5
votes

Here's a function that provides a result of 2 columns.

In this function there's a Loop been used to return the result.

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;

Is there any possibilities of returning the rows without using loop?

If so please do share me on how we can do it.

And will I be able to write a function to insert records on to a table without using loop?

Help me out to solve this query.

Thanks in advance.

2
I don't which one to accept but both gave me the answer what i was expecting for. Hence +1 for both the answers.Unknown User
Note that your query is not valid: you group only by circle, but use label as a selected column. postgresql.org/docs/9.3/static/sql-select.html#SQL-GROUPBYpozs
That needs to label. That was a typo error. By the way the query will not run if i don't include label in the groupby.Unknown User
You should accept a_horse_with_no_name's answer if it answers your question.Kenny Evitt

2 Answers

13
votes

you don't need the extra type definition. And to return multiple rows, use return query:

Something like this:

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;

You don't even need a PL/pgSQL function, you can use a simple SQL function for this:

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
votes

You can insert values in the table using SELECT query as below:

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;