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 with RETURNS 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;