0

I want to return a row from a table with this function (I don't know the name of the table, it's random)

CREATE FUNCTION foo( text ) RETURNS setof record AS $$
 DECLARE
  table_name ALIAS FOR $1;
 BEGIN 
  SELECT *  from table_name ;
 END
$$ LANGUAGE plpgsql;

and then I want to do this:

select col1,col2 from foo('bar');

Any ideas?

3
  • I'll ignore the oddness of random table names just popping up and try to help with what I can. When does the table get created? At some point you must capture the random table name. And at least pass the name into your function and use dynamic sql to execute a select statement using that table name parameter to build your query on the fly. Commented Jun 18, 2014 at 14:26
  • Is it just the name of the table that's random or names and types of columns as well? In this case you need polymorphic types. Look to the last chapter of this related answer. Commented Jun 18, 2014 at 14:37
  • no. All the tables are different and formed by different types of columns (also the number of columns varies). Commented Jun 18, 2014 at 15:10

1 Answer 1

1

SQL demands to know the return type at call time. And functions require you to define a return type as well. What you are after is not trivial.

If you don't know the return type at call time, you are basically out of luck. You cannot solve the problem with a single function call.

If you know the type at call time, there is an option with polymorphic types and dynamic SQL with EXECUTE:

CREATE OR REPLACE FUNCTION f_data_of_table(_tbl_type anyelement)
  RETURNS SETOF anyelement AS
$func$
BEGIN

RETURN QUERY EXECUTE 
'SELECT * FROM ' || pg_typeof(_tbl_type);

END
$func$ LANGUAGE plpgsql;

Call:

SELECT * FROM f_data_of_table(NULL::my_table_name);

Details in this related answer:
Refactor a PL/pgSQL function to return the output of various SELECT queries

Be wary of SQL injection:
Table name as a PostgreSQL function parameter

Only makes sense if you do more than just SELECT * FROM tbl, or you'd simply use the SQL command.

Aside:
Do not use ALIAS to attach names to parameter values. That's outdated and discouraged. Use named parameters instead.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.