HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Untyped functions that return tables

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
tablesuntypedreturnthatfunctions

Problem

I would like to write a PostgreSQL stored function that essentially behaves like the stored procedures I know and love from MSSQL and MySQL where I can just wrap a query that takes no parameters and have it return that resultset without having to specify the format of the output and change that definition every time I update the query. Is this even possible in PostgreSQL ?

I've tried the following using PostgreSQL 9.2:

CREATE OR REPLACE FUNCTION test()
RETURNS SETOF record


Which gives me the following error:


ERROR: a column definition list is required for functions returning "record"

I've also tried:

CREATE OR REPLACE FUNCTION test()
RETURNS table ()


but apparently that's invalid syntax.

Solution

This is a misunderstanding. A function like this is perfectly valid:

CREATE OR REPLACE FUNCTION test()
 RETURNS SETOF record AS
$func$
VALUES (1, 2), (3, 4);  -- 2 rows with 2 integer columns
$func$ LANGUAGE sql;


However, since it returns anonymous records, you are required to provide a column definition list with every call , just like the error message told you. SQL demands to know what to expect from a function up front. The call would work like this:

SELECT * FROM test() AS f(a int, b int);


Functions returning anonymous records have their uses. I try to avoid them mostly, because the call is rather unwieldy. Depending on your exact requirements, there are a couple of ways around it. I wrote a comprehensive answer for that on SO recently.

Code Snippets

CREATE OR REPLACE FUNCTION test()
 RETURNS SETOF record AS
$func$
VALUES (1, 2), (3, 4);  -- 2 rows with 2 integer columns
$func$ LANGUAGE sql;
SELECT * FROM test() AS f(a int, b int);

Context

StackExchange Database Administrators Q#41252, answer score: 5

Revisions (0)

No revisions yet.