Convert into PostgreSQL Dynamic Query

后端 未结 1 1880
梦如初夏
梦如初夏 2021-01-16 17:38

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.

1条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-16 17:58

    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)

    0 讨论(0)
提交回复
热议问题