From: | "Albe Laurenz" <laurenz(dot)albe(at)wien(dot)gv(dot)at> |
---|---|
To: | "Derek Liang *EXTERN*" <derek(dot)liang(dot)ca(at)gmail(dot)com>, <pgsql-general(at)postgresql(dot)org> |
Subject: | Re: return X number of refcursors from a function |
Date: | 2008-12-31 09:08:30 |
Message-ID: | D960CB61B694CF459DCFB4B0128514C202EA75C4@exadv11.host.magwien.gv.at |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-general |
Derek Liang wrote:
> I tried to use the following code to retrieve the content of table1 4
> times (in my application, the total number of refcursors that will be
> returned is determined by the data in the database). I am getting the
> error message says "ERROR: cursor "<unnamed portal 2>" already in
> use".
>
> Thank you in advance!
>
> dl
>
> --Start of the code
> --DROP FUNCTION myfunc(int);
>
> CREATE FUNCTION myfunc(int) RETURNS SETOF refcursor AS $$
> DECLARE i int;
> r refcursor;
> BEGIN
> i := $1;
> WHILE i>0 LOOP
> RAISE NOTICE 'loop count %;', i;
> i := i-1;
>
> OPEN r FOR SELECT * FROM table1;
> RETURN NEXT r;
> END LOOP;
>
> RETURN;
> END;
> $$ LANGUAGE plpgsql;
>
> BEGIN;
> SELECT * FROM myfunc(4);
> COMMIT;
The problem is that the name of the cursor "r" remains the same
throughout the execution of your function, while the name of a
cursor is unique per session.
You can name a cursor by assigning a string to the refcursor variable.
Your function will work if you add for example the following line
immediately before the "OPEN" statement:
r := 'cursor' || ($1 - i);
Yours,
Laurenz Albe
From | Date | Subject | |
---|---|---|---|
Next Message | Albe Laurenz | 2008-12-31 09:17:26 | Re: Load Image File From PostgreSQL DB |
Previous Message | Reg Me Please | 2008-12-31 08:39:59 | Re: [PGSQL 8.3.5] Use of a partial indexes |