I have a table like this:
Table: survey
| formula | var1 | var2 | var3 |
|------------------------|-------|--------|--------|
| var1 + var2 | 12 | 9 | 2 |
| var3 * (var1 * var2) | 20 | 10 | 1 |
The trick is that the values inside column formula
can be used as the SELECT
clause against its row to get the final score, for example:
SELECT var1 + var2 FROM (VALUE ('var1 + var2', 12, 9, 2) AS t(formula, var1, var2, var3)
I am working on a sql procedure to dynamically compute the score for each row.
My current solution is to loop over each row and use EXECUTE
to evaluate each formula. Here is the code:
CREATE FUNCTION cpt_scores() RETURNS SETOF scores as
$$
DECLARE
score numeric;
in_rec record;
BEGIN
FOR in_rec IN
SELECT * FROM survey
LOOP
EXECUTE format('SELECT %s FROM (VALUES %s) AS t(formula, var1, var2, var3)', in_rec.formula, in_rec)
INTO score
RETURN NEXT ROW(score);
END LOOP;
END;
$$ language plpgsql;
I would like to know if there is any better way to handle this task. I think that the hard-coded column names in that FROM
clause can cause trouble when there are too many metrics to type manually.