问题
I would like to evaluate a pure-calculation string in Postgres.
For example: eval('234 + 65 * 3')
The function is NOT constant, so could also simply be 2 + 2
Expecting something like SELECT eval('2 + 2') AS result
I read about huge security issues regarding eval()
functions, but those seem to incorporate SELECT
statements. Here pure calculation requirements.
回答1:
You need PL/pgSQL
:
create or replace function f(_s text)
returns numeric as $$
declare i numeric;
begin
execute format('select %s', _s) into i;
return i;
end;
$$ language plpgsql;
select f('1 + 1');
f
---
2
来源:https://stackoverflow.com/questions/43118512/eval-calculation-string-2-3-4-5-in-postgresql