about me and my world

Montag, 8. Oktober 2007

[PostgreSQL] Formula in a Column, how calculate the fee?

Someone ask on IRC: how can i store a formula in a column and calculate the fee for an operator with this formula and other values from other columns?


My solution:

test=# select * from operators ;
id | minutes | base_salary | factor | bonus | formula
----+---------+-------------+--------+-------+-------------------------------------------------
1 | 120 | 6.50 | 1.20 | 10.50 | minutes * base_salary * factor + bonus
2 | 120 | 6.50 | 1.20 | 10.50 | minutes * base_salary * factor + bonus * factor
(2 rows)

test=*# create or replace function fee(
int) returns numeric(10,2) as $$
declare f text;
ret numeric(10,2);
begin
select into f formula from operators where id=$1;
execute
'select ' || f || ' from operators where id=' || $1 into ret;
return ret;
end;
$$language plpgsql;
CREATE FUNCTION

test=*# select * from fee(1);
fee
--------
946.50
(1 row)

test=*# select * from fee(2);
fee
--------
948.60
(1 row)

Keine Kommentare:

Labels