我正在尝试编写一个 PL/PgSQL 函数,它将执行存储在 PostgreSQL 表中的查询,如下所示:
CREATE OR REPLACE FUNCTION evaluate_scenario(scenario_id int)
RETURNS TABLE(line_item_id int, organization_id int, data_element_id int, value varchar) AS $$
BEGIN
RETURN QUERY
SELECT
li.id,
li.organization_id,
de.id,
(EXECUTE 'SELECT ' || de.query)::varchar
FROM
line_items AS li INNER JOIN
summary_files AS sf ON li.summary_file_id = sf.id INNER JOIN
scenarios AS s ON s.summary_file_id = sf.id CROSS JOIN
data_elements AS de
WHERE
s.id = 1 AND
de.scope = 3 AND (
de.model_id = s.model_id OR
de.scenario_id = s.id OR
de.organization_id = s.organization_id
);
END;
$$ LANGUAGE plpgsql;
当我尝试运行此查询时:
select line_item_id, data_element_id, value from evaluate_scenario(1)
我收到以下错误:
********** Error **********
ERROR: type "execute" does not exist
SQL state: 42704
Context: PL/pgSQL function "evaluate_scenario" line 3 at RETURN QUERY
任何帮助将不胜感激。请注意,如果我删除“EXECUTE”并在这些括号内执行 SELECT de.query,我会按预期收到该列的值,但我无法弄清楚如何使 de.query 成为“EXECUTE”的可接受查询字符串”。