我有下表:
test=# CREATE TABLE stmts(id SERIAL, selector VARCHAR(255));
CREATE TABLE
test=# INSERT INTO stmts(selector) VALUES('5 > 3'),('5 < 3');
INSERT 0 2
test=# SELECT selector FROM stmts;
selector
----------
5 > 3
5 < 3
(2 rows)
我想修改select以便能够为每一行评估选择器的值,所以期望的效果是:
selector, magic FROM stmts;
selector | magic
--------------------
5 > 3 | true
5 < 3 | false
(2 rows)
如果在行的上下文中执行它会很棒,所以我们可以评估例如表达式id = 5
等。
这甚至可能吗?
答案 0 :(得分:0)
您可以在plpgsql函数中动态执行此操作:
create or replace function eval_bool(expr text)
returns boolean language plpgsql as $$
declare
rslt boolean;
begin
execute format('select %s', expr) into rslt;
return rslt;
end $$;
select id, selector, eval_bool(selector)
from stmts;
id | selector | eval_bool
----+----------+-----------
1 | 5 > 3 | t
2 | 5 < 3 | f
(2 rows)