Re: Dynamic SQL in Function

From: Merlin Moncure <mmoncure(at)gmail(dot)com>
To: rwade(at)uci(dot)edu
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Dynamic SQL in Function
Date: 2009-04-23 19:21:03
Message-ID: b42b73150904231221r78e3778ey2758aa53ae9ece28@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Thu, Apr 23, 2009 at 11:36 AM, <rwade(at)uci(dot)edu> wrote:
>> On Wed, Apr 22, 2009 at 12:29 PM,  <rwade(at)uci(dot)edu> wrote:
>>> If I have built a dynamic sql statement in a function, how do i return
>>> it
>>> as a ref cursor?
>>
>> CREATE FUNCTION reffunc(_ref) RETURNS refcursor AS
>> $$
>> BEGIN
>>     OPEN _ref FOR execute 'SELECT * from foo';
>>     RETURN _ref;
>> END;
>> $$ LANGUAGE plpgsql;
>>
>> BEGIN;
>> SELECT reffunc('funccursor');
>> FETCH ALL IN funccursor;
>> COMMIT;
>>
> Is this possible without having to pass in the _ref parameter?

sure:
CREATE FUNCTION reffunc() RETURNS refcursor AS
$$
DECLARE
_ref REFCURSOR default 'merlin';
BEGIN
OPEN _ref FOR execute 'SELECT * from foo';
RETURN _ref;
END;
$$ LANGUAGE plpgsql;

one thing I also forgot: refcursors are limited to transaction
lifetime...make sure to wrap the function call with begin...end.

merlin

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Conrad Lender 2009-04-23 19:33:11 standard_conforming_strings and pg_escape_string()
Previous Message Tom Lane 2009-04-23 17:34:06 Re: how to search for relation by name?