1

I have this function:

CREATE OR REPLACE FUNCTION remote (_table_name text)
  RETURNS SETOF my_table AS
$func$
DECLARE
   sql text := format('SELECT * FROM %s WHERE id = 1', _table_name);
BEGIN
   RETURN QUERY EXECUTE sql
   USING _table_name;
END
$func$ LANGUAGE plpgsql;

select * from remote('my_table')

But I would like to have a dynamic RETURNS SETOF _table_name.

I get this error if I do so:

ERROR:  type "_table_name" does not exist

How can I achieve that?

Many thanks

1 Answer 1

3

Found the answer here: Refactor a PL/pgSQL function to return the output of various SELECT queries

CREATE OR REPLACE FUNCTION get_remote(_table_name anyelement)
  RETURNS SETOF anyelement AS
$func$
DECLARE
   sql text := format('SELECT * FROM %s WHERE id = 1', pg_typeof(_table_name));
BEGIN
   RETURN QUERY EXECUTE sql
   USING _table_name;
END
$func$ LANGUAGE plpgsql;

select * from get_remote(NULL::my_table)

That was a tricky one though ...

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.