I need to provide a number of stored procedures that return the result of an aggregate function run on a selection of values in the database, i.e. average, sum, min, max, etc. The selection of values is always done in a similar manner.
My first, naive implementation consists of one stored proc per aggregate function type, e.g. get_avg(...), get_sum(...). The functions obviously share quite a lot of duplicate code. I wonder if there is a way to move the aggregate type into a parameter or so and then use one stored proc only, e.g. get_aggregate(aggr_type, ...)
The only way I can think of as far as the pl/pgsql implementation is concerned is to select the values that should go into the aggregate and then use that in as many if aggr_type == ... / else clauses as there are aggregate types. This is not very flexible though and requires change of the code whenever a new aggregate type should be supported.
Is there any way to parameterize the name of a function in pl/pgsql ? Can ayone think of an approach that I fail to see ?