1

I want a plpgsql function that returns the content of any table, given the name. The function below, although not working because of many reasons will gove you the general idea. Safety and coding practice aside, what's the easiest way to accomplish this?

In the end I want to get these results trough a Java CallableStatement.

CREATE OR REPLACE FUNCTION get_table(tablename VARCHAR)
RETURNS SETOF RECORD AS $PROC$
BEGIN
 RETURN QUERY SELECT * FROM tablename;
END;
$PROC$ LANGUAGE 'plpgsql';
m4tx
4,5765 gold badges40 silver badges63 bronze badges
asked May 10, 2012 at 11:31
0

1 Answer 1

3

You can get your function working like this:

CREATE OR REPLACE FUNCTION get_table(tablename VARCHAR)
RETURNS SETOF RECORD AS $PROC$
BEGIN
 RETURN QUERY EXECUTE 'SELECT * FROM ' || quote_ident(tablename);
END;
$PROC$ LANGUAGE 'plpgsql';

In order to call it, you must specify names and data types for all returned columns. If you want to list table "t" which has two columns, you could use your function like this:

SELECT * FROM get_table('t') x(id int, val text);

Which of course, is longer and a lot more trouble than either:

SELECT * FROM t;

or the equivalent:

TABLE t;

I really can't imagine a use-case where such a function makes anything better.

m4tx
4,5765 gold badges40 silver badges63 bronze badges
answered May 10, 2012 at 17:58
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the info, this is useful in my situation where we have different schemas set up for different users, but the reporting system that we have doesn't allow us to change the search_path properly. This allows the workaround of passing a query into a function, and the function sets the search_path appropriately, then runs the query and returns the result. (And the RETURN QUERY doesn't allow multiple queries or non select queries, helping to keep it safe.)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.