Function to return dynamic set of columns for given table

前端 未结 2 1610
春和景丽
春和景丽 2020-12-10 09:29

I have a fields table to store column information for other tables:

CREATE TABLE public.fields (
   schema_name varchar(100), 
   table_name  va         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-10 09:50

    I think you just need another query to get the list of columns you want.

    Maybe something like (this is untested):

    create or replace function public.get_table(_schema_name text, _table_name text, active boolean default true) returns setof record as $$
    declare
        entity_name text default schema_name || '.' || table_name;
        r record;
        columns varchar;
    begin
        -- Get the list of columns
        SELECT string_agg(column_name, ', ')
             INTO columns
             FROM public.fields
             WHERE fields.schema_name = _schema_name
                AND fields.table_name = _table_name
                AND fields.column_visible = TRUE;
    
        -- Return rows from the specified table
        RETURN QUERY EXECUTE 'select ' || columns || ' from ' || entity_name;
    
        RETURN;
    end
    $$
    language plpgsql;
    

    Keep in mind that column/table references may need to be surrounded by double quotes if they have certain characters in them.

提交回复
热议问题