Re: using a plpgsql function argument as a table column. - Mailing list pgsql-general

From Tim Cross
Subject Re: using a plpgsql function argument as a table column.
Date
Msg-id CAC=50j-aZ1gjrtVD6RAnczBM+VdJwhQCFy+1vu_MLgPij02gUA@mail.gmail.com
Whole thread Raw
In response to using a plpgsql function argument as a table column.  (ss <ss@tuxclub.org>)
Responses Re: using a plpgsql function argument as a table column.
List pgsql-general
Off the top of my head, I think you could do this using dynamic (execute) SQL in a function. However, it is going to be messy, possibly slow and likely fragile. You would need to query the catalogue to get the column names in the table and then build the SQL dynamically 'on the fly'. 

Without having more detail, my spider sense tells me you have the wrong table/relationship design. While you may be able to get it to work, it is likely you will run into constant problems and additional complexity that could be avoided with a different design. You really want a design where your queries are driven by the data in your tables and not by the names of columns. I would seriously consider re-examining your schema design, look at how your design fits in with the normal forms and adapt as necessary.

Tim

On Wed, 29 Aug 2018 at 15:10, ss <ss@tuxclub.org> wrote:
I have a table with many years as columns. y1976, y2077, .. ,
y2019,y2020 I want to dynamically return a column from a function.


select * from FUNCTION('y2016') .....

select t1.cola t1.colb, t1.colc, t2.y2016 from ..... Where t2.y2016 != 0;

or if I select year y2012 I want FUNCTION('y2012')

select t1.cola t1.colb, t1.colc, t2.y2012 from ..... Where t2.y2012 != 0;


to generalize

select * from FUNCTION( year_column )

select t1.cola t1.colb, t1.colc, t2.year_column from ..... Where
t2.year_column != 0;

is it possible? if so how?




--
regards,

Tim

--
Tim Cross

pgsql-general by date:

Previous
From: Thomas Boussekey
Date:
Subject: Re: using a plpgsql function argument as a table column.
Next
From: Shaun Savage
Date:
Subject: Re: using a plpgsql function argument as a table column.