Tuesday, 15 July 2014

sql - Return set of records with unknown table_name -



sql - Return set of records with unknown table_name -

i want homecoming row table function (i don't know name of table, it's random)

create function foo( text ) returns setof record $$ declare table_name alias $1; begin select * table_name ; end $$ language plpgsql;

and want this:

select col1,col2 foo('bar');

any ideas?

sql demands know homecoming type @ phone call time. , functions require define homecoming type well. after not trivial.

if don't know homecoming type @ call time, out of luck. cannot solve problem single function call.

if know type @ phone call time, there alternative polymorphic types , dynamic sql execute:

create or replace function f_data_of_table(_tbl_type anyelement) returns setof anyelement $func$ begin homecoming query execute 'select * ' || pg_typeof(_tbl_type); end $func$ language plpgsql;

call:

select * f_data_of_table(null::my_table_name);

details in related answer: refactor pl/pgsql function homecoming output of various select queries

be wary of sql injection: table name postgresql function parameter

only makes sense if more select * tbl, or you'd utilize sql command.

aside: not utilize alias attach names parameter values. that's outdated , discouraged. utilize named parameters instead.

sql postgresql plpgsql

No comments:

Post a Comment