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 allows single row.
How to return an entire query? I want to use functions as query templates.
Call like this:
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
OUTparameters (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: