Create a custom type which describes the structure of the rows returned:
CREATE TYPE func_return_type AS (column_name column_type, ...);
Then create the function:
CREATE OR REPLACE FUNCTION some_func (param_type, ...) RETURNS SETOF func_return_type AS ' SELECT columns FROM table WHERE condition; ' LANGUAGE 'SQL';
customfunctionsplpgsqlpostgresqlsqltypes
You can use RETURNS SETOF record in your plpgsql functions to return a set of rows. Here is an example of using pgsql to build a query using a table name parameter:
CREATE OR REPLACE FUNCTION test(text) RETURNS SETOF record AS '
DECLARE
_table ALIAS FOR $1;
_mycursor refcursor;
_row record;
BEGIN
OPEN _mycursor FOR EXECUTE ''SELECT * FROM '' || _table;
FETCH _mycursor INTO _row;
WHILE FOUND LOOP
RETURN NEXT _row;
FETCH _mycursor INTO _row;
END LOOP;
RETURN;
END
' LANGUAGE plpgsql;
Here is an example of calling such a function (the names and types of the result columns are required when returning SETOF record):
mydb=> SELECT * FROM test('mytable') AS (col1 integer, col2 text, col3 date);
functionsobscureplpgsqlpostgresqlpsqlsetofsql