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.
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;
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With