有没有办法在 PostgreSQL 中的字符串值(如 eval)中执行查询? [英] Are there any way to execute a query inside the string value (like eval) in PostgreSQL?

查看:44
本文介绍了有没有办法在 PostgreSQL 中的字符串值(如 eval)中执行查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样做:

SELECT (EVAL 'SELECT 1') + 1;

在 PostgreSQL 中有没有办法做到这样(EVAL)?

Are there any way to do like this (EVAL) in PostgreSQL?

推荐答案

如果您尝试eval"的语句总是返回相同的数据类型,您可以编写一个使用 Grzegorz 提到的 EXECUTE 的 eval() 函数.

If the statements you are trying to "eval" always return the same data type, you could write an eval() function that uses the EXECUTE mentioned by Grzegorz.

create or replace function eval(expression text) returns integer
as
$body$
declare
  result integer;
begin
  execute expression into result;
  return result;
end;
$body$
language plpgsql

然后你可以做类似的事情

Then you could do something like

SELECT eval('select 41') + 1;

但是如果您的动态语句为您要评估的每个表达式返回不同的内容,则这种方法将不起作用.

But this approach won't work if your dynamic statements return something different for each expression that you want to evaluate.

还请记住,这会因为运行任意语句而带来巨大的安全风险.如果这是一个问题,则取决于您的环境.如果仅在交互式 SQL 会话中使用它,则没有问题.

Also bear in mind that this opens a huge security risk by running arbitrary statements. If that is a problem depends on your environment. If that is only used in interactive SQL sessions then it isn't a problem.

这篇关于有没有办法在 PostgreSQL 中的字符串值(如 eval)中执行查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆