Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL - Function to return multiple columns

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.

like image 433
Unknown User Avatar asked Apr 16 '14 10:04

Unknown User


1 Answers

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;
like image 79
a_horse_with_no_name Avatar answered Nov 13 '22 19:11

a_horse_with_no_name