Are there any way to execute a query inside the string value (like eval) in PostgreSQL?

本小妞迷上赌 提交于 2019-11-26 07:42:30

问题


I want to do like this:

SELECT (EVAL \'SELECT 1\') + 1;

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


回答1:


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.

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.




回答2:


NOTES

The language PLpgSQL syntax have many ways to say:

 Y := f(X);

The EXECUTE clause is only for "dynamic execution" (less performance),

 EXECUTE 'f(X)' INTO Y;     

Use Y := f(X); or SELECT for execute static declarations,

 SELECT f(X) INTO Y;

Use PERFORM statment when discard the results or to work with void returns:

 PERFORM f(X);     



回答3:


I'd go with data type text since it's more flexible using casting operators like ::int if needed:

create or replace function eval( sql  text ) returns text as $$
declare
  as_txt  text;
begin
  if  sql is null  then  return null ;  end if ;
  execute  sql  into  as_txt ;
  return  as_txt ;
end;
$$ language plpgsql
-- select eval('select 1')::int*2         -- => 2
-- select eval($$ select 'a'||1||'b' $$)  -- => a1b
-- select eval( null )                    -- => null

I also added this and another eval( sql, keys_arr, vals_arr ) function supporting some custom key-value substitutions, e.g. for handy :param1 substitutions to postgres-utils




回答4:


I am not sure if it suits you but PostgreSQL has EXECUTE statement.




回答5:


Good idea. You can modify to perform direct expressions:

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

To run just type this:

SELECT eval('2*2');


来源:https://stackoverflow.com/questions/7433201/are-there-any-way-to-execute-a-query-inside-the-string-value-like-eval-in-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!