Return a query from a function?
I am using PostgreSQL 8.4 and I want to create a function that returns a query with many rows.
The following function does not work:create function get_names(varchar) returns setof record AS $$
declare
tname alias for $1;
res setof record;
begin
select * into res from mytable where name = tname;
return res;
end;
$$ LANGUAGE plpgsql;
The type record
only allo开发者_Go百科ws single row.
How to return an entire query? I want to use functions as query templates.
CREATE OR REPLACE FUNCTION get_names(_tname varchar)
RETURNS TABLE (col_a integer, col_b text) AS
$func$
BEGIN
RETURN QUERY
SELECT t.col_a, t.col_b -- must match RETURNS TABLE
FROM mytable t
WHERE t.name = _tname;
END
$func$ LANGUAGE plpgsql;
Call like this:
SELECT * FROM get_names('name')
Major points:
Use
RETURNS TABLE
, so you don't have to provide a list of column names with every call.Use
RETURN QUERY
, much simpler.Table-qualify column names to avoid naming conflicts with identically named
OUT
parameters (including columns declared withRETURNS TABLE
).Use a named variable instead of
ALIAS
. Simpler, doing the same, and it's the preferred way.A simple function like this could also be written in
LANGUAGE sql
:
CREATE OR REPLACE FUNCTION get_names(_tname varchar)
RETURNS TABLE (col_a integer, col_b text) AS
$func$
SELECT t.col_a, t.col_b --, more columns - must match RETURNS above
FROM mytable t
WHERE t.name = $1;
$func$ LANGUAGE sql;
精彩评论