Re: PL/pgSQL: How to return two columns and multiple rows

From: Raymond O'Donnell <rod(at)iol(dot)ie>
To: Sven Geggus <lists(at)fuchsschwanzdomain(dot)de>, pgsql-general(at)postgresql(dot)org
Subject: Re: PL/pgSQL: How to return two columns and multiple rows
Date: 2015-06-18 12:54:42
Message-ID: 5582BF92.5070009@iol.ie
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 18/06/2015 13:36, Sven Geggus wrote:
> Hello,
>
> I supose this is simple, but I did not find a solution in the documentation.
>
> I would like to be able to do something like this:
>
> select myfunc('foo','bar');
> or
> select myfunc(foo, bar) from foobartable;
> or even
> select myfunc(foo, bar), 'baz' as baz from foobartable;
>
> Which should return something like this:
> foo | bar
> ------+------
> foo1 | bar1
> foo2 | bar2
> foo3 | bar3
> foo4 | bar4
> (4 rows)
>
> So the output should be at least two columns and (usually) more than one row.
>
> What I currently have is the following, which is mostly it. Unfortunately
> it gives me only one column (I really need two) and I would have to create a
> custom type:
>
> CREATE TYPE t_foobar AS (foo text, bar text);
>
> CREATE or REPLACE FUNCTION myfunc(foo text, bar text)
> returns SETOF t_foobar as $$
> BEGIN
> FOR i IN 1..4 LOOP
> RETURN NEXT (foo || i::text, bar || i::text);
> END LOOP;
> RETURN;
> END;
> $$ language 'plpgsql';
>
> mydb=> select myfunc('foo','bar');

You need to do:

select * from myfunc('foo','bar');

Ray.

--
Raymond O'Donnell :: Galway :: Ireland
rod(at)iol(dot)ie

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2015-06-18 13:03:01 Re: PL/pgSQL: How to return two columns and multiple rows
Previous Message Raymond O'Donnell 2015-06-18 12:53:40 Re: My postgres is not logging anymore