Below is one function which has one query ,
Now I want to convert into dynamic query. I want one table name parameter so query return data from multiple tables.
This is basic PL/PgSQL. Use PL/PgSQL's EXECUTE .. USING statement and format
function with the %I
format-specifier.
create or replace function get_sometable(tablename regclass)
returns setof whatever_type as
BEGIN
RETURN QUERY EXECUTE format('select * from %I";', tablename);
END;
language 'plpgsql';
This will only work if all tablenames you might pass return compatible result types, as occurs with partitioning. Otherwise you'll have to return SETOF RECORD
and then pass the table layout in the function invocation. See the documentation for a discussion of RECORD
and SETOF RECORD
.
Look into RETURNS TABLE
as another convenient alternative for when the table types aren't compatible but you can still return a compatible subset via a suitable SELECT
list.
If you're doing table partitioning, you should really do it as the PostgreSQL documentation on table partitioning advises, using table inheritance and triggers.
(Elaborating on Convert SQL Server stored procedure into PostgreSQL stored procedure)