有什么方法可以在PostgreSQL的字符串值(例如eval)内执行查询? [英] Are there any way to execute a query inside the string value (like eval) in PostgreSQL?

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

问题描述

我想这样做:

SELECT (EVAL 'SELECT 1') + 1;

在PostgreSQL中有什么办法可以做这样的(EVAL)吗?

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

推荐答案

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

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

然后您可以做类似

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天全站免登陆