Re: cursors and function question

From: Adrian Klaver <adrian(dot)klaver(at)aklaver(dot)com>
To: armand pirvu <armand(dot)pirvu(at)gmail(dot)com>, "pgsql-general(at)postgresql(dot)org" <pgsql-general(at)postgresql(dot)org>
Subject: Re: cursors and function question
Date: 2018-02-13 18:54:35
Message-ID: 83c954ba-4d14-ac71-f4ea-30ce25b9a310@aklaver.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 02/13/2018 10:22 AM, armand pirvu wrote:
> Hi
>
> Is there any elegant way not a two steps way I can output the cursor value at each step?
>
>
> testtbl table has this content
>
> col1 | col2 | col3
> ------------+------------+------
> E1 | CAT1 | 0
> E1 | CAT2 | 0
> E1 | CAT3 | 0
> E4 | CAT1 | 0
> E5 | CAT1 | 0
> E6 | CAT1 | 0
> E7 | CAT1 | 0
>
>
> This works
> BEGIN WORK;
> DECLARE fooc CURSOR FOR SELECT * FROM testtbl;
> FETCH ALL FROM fooc;
> CLOSE fooc;
> COMMIT WORK;
>
> col1 | col2 | col3
> ------------+------------+------
> E1 | CAT1 | 0
> E1 | CAT2 | 0
> E1 | CAT3 | 0
> E4 | CAT1 | 0
> E5 | CAT1 | 0
> E6 | CAT1 | 0
> E7 | CAT1 | 0
>
>
> But
> CREATE OR REPLACE FUNCTION foofunc()
> RETURNS text AS $$
> DECLARE
> var2 RECORD;
> cur CURSOR FOR SELECT * from testtbl;
> BEGIN
> OPEN cur;
> LOOP
> FETCH cur INTO var2;
> return var2;
> END LOOP;
> CLOSE cur;
> END; $$
> LANGUAGE plpgsql;

CREATE OR REPLACE FUNCTION public.foofunc()
RETURNS SETOF testtbl
LANGUAGE sql
AS $function$
SELECT * FROM testtbl;
$function$

test=> select * from foofunc();
col1 | col2 | col3
------+------+------
E1 | CAT1 | 0
E1 | CAT2 | 0
E1 | CAT3 | 0
E4 | CAT1 | 0
E5 | CAT1 | 0
E6 | CAT1 | 0
E7 | CAT1 | 0
(7 rows)

>
>
> select foofunc();
> foofunc
> -------------------------------
> ("E1 ","CAT1 ",0)
>
> But I am looking to get
>
> foofunc
> -------------------------------
> ("E1 ","CAT1 ",0)
> ("E1 ","CATs ",0)
> etc
>
>
>
> Many thanks
> — Armand
>

--
Adrian Klaver
adrian(dot)klaver(at)aklaver(dot)com

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2018-02-13 19:02:33 Re: Multiple postmasters running from same directory
Previous Message Vikas Sharma 2018-02-13 18:53:41 Re: Multiple postmasters running from same directory