在 PL/pgSQL 中是否可以将字符串评估为表达式,而不是语句?
Is it possible in PL/pgSQL to evaluate a string as an expression, not a statement?
我有两个数据库表:
# \d table_1
Table "public.table_1"
Column | Type | Modifiers
------------+---------+-----------
id | integer |
value | integer |
date_one | date |
date_two | date |
date_three | date |
# \d table_2
Table "public.table_2"
Column | Type | Modifiers
------------+---------+-----------
id | integer |
table_1_id | integer |
selector | text |
table_2.selector
中的值可以是one
、two
或three
之一,用于select日期列之一在 table_1
.
我的第一个实现使用了 CASE
:
SELECT value
FROM table_1
INNER JOIN table_2 ON table_2.table_1_id = table_1.id
WHERE CASE table_2.selector
WHEN 'one' THEN
table_1.date_one
WHEN 'two' THEN
table_1.date_two
WHEN 'three' THEN
table_1.date_three
ELSE
table_1.date_one
END BETWEEN ? AND ?
selector
的值使我可以将感兴趣的列识别为 eval(date_#{table_2.selector})
,if PL/pgSQL 允许评估字符串作为表达式。
我能找到的最接近的是 EXECUTE string
,它计算整个语句。有没有办法计算 expressions?
在 plpgsql 函数中,您可以动态创建任何表达式。但是,这不适用于您描述的情况。查询必须在执行前显式定义,而字段的选择是在查询执行时发生的。
您的查询是最好的方法。你可能会尝试使用一个功能,但它不会带来任何好处,因为问题的本质不会改变。
我有两个数据库表:
# \d table_1
Table "public.table_1"
Column | Type | Modifiers
------------+---------+-----------
id | integer |
value | integer |
date_one | date |
date_two | date |
date_three | date |
# \d table_2
Table "public.table_2"
Column | Type | Modifiers
------------+---------+-----------
id | integer |
table_1_id | integer |
selector | text |
table_2.selector
中的值可以是one
、two
或three
之一,用于select日期列之一在 table_1
.
我的第一个实现使用了 CASE
:
SELECT value
FROM table_1
INNER JOIN table_2 ON table_2.table_1_id = table_1.id
WHERE CASE table_2.selector
WHEN 'one' THEN
table_1.date_one
WHEN 'two' THEN
table_1.date_two
WHEN 'three' THEN
table_1.date_three
ELSE
table_1.date_one
END BETWEEN ? AND ?
selector
的值使我可以将感兴趣的列识别为 eval(date_#{table_2.selector})
,if PL/pgSQL 允许评估字符串作为表达式。
我能找到的最接近的是 EXECUTE string
,它计算整个语句。有没有办法计算 expressions?
在 plpgsql 函数中,您可以动态创建任何表达式。但是,这不适用于您描述的情况。查询必须在执行前显式定义,而字段的选择是在查询执行时发生的。
您的查询是最好的方法。你可能会尝试使用一个功能,但它不会带来任何好处,因为问题的本质不会改变。