Re: Sending Results From One Function As Input into Another Function

From: "Albe Laurenz" <laurenz(dot)albe(at)wien(dot)gv(dot)at>
To: "Jeff Adams *EXTERN*" <Jeff(dot)Adams(at)noaa(dot)gov>, <pgsql-general(at)postgresql(dot)org>
Subject: Re: Sending Results From One Function As Input into Another Function
Date: 2011-09-26 11:49:45
Message-ID: D960CB61B694CF459DCFB4B0128514C206E9F88E@exadv11.host.magwien.gv.at
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Jeff Adams wrote:
> I need to send the results (SETOF RECORDS) from one function into
another
> function, to produce another result (SETOF RECORDS). I am not quite
sure how
> to do get this done. The first function filters a large table down a
more
> manageable dataset. I want to send the results of this first function
to
> another function, where computations are performed. I could combine
into a
> single function, but I would lose some flexibility that I would like
to
> maintain by keeping the two functions separate. Preliminary research
> suggests that cursors might be the way to go, but I am not too
experienced
> with the use of cursors and was unable to find good examples. Any help
would
> be greatly appreciated...

Here's an example:

SELECT * FROM test;

id | val
----+-------
1 | one
2 | two
3 | three
4 | four
(4 rows)

CREATE FUNCTION filter() RETURNS refcursor
LANGUAGE plpgsql STABLE STRICT AS
$$DECLARE
/* assignment gives the cursor a name */
curs refcursor := 'curs';
BEGIN
OPEN curs FOR
SELECT id, val FROM test WHERE id%2=0;
RETURN curs;
END;$$;

CREATE FUNCTION compute(curs refcursor) RETURNS text
LANGUAGE plpgsql STABLE STRICT AS
$$DECLARE
v test; -- row type for table
r text := '';
BEGIN
LOOP
FETCH curs INTO v;
EXIT WHEN v IS NULL;
r := r || v.val;
END LOOP;
RETURN r;
END;$$;

SELECT compute(filter());

compute
---------
twofour
(1 row)

Yours,
Laurenz Albe

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Edson Carlos Ericksson Richter 2011-09-26 12:16:40 Does postgresql 9.0.4 use index on PREFIX%SUFFIX queries?
Previous Message Harald Fuchs 2011-09-26 11:44:20 Re: New feature: accumulative functions.