Referring to session variables (\set var='value') from PL/PGSQL

☆樱花仙子☆ 提交于 2019-11-28 09:09:10

问题


I can pass variables into PostgreSQL using

psql --variable="var='value'" <<<'SELECT :var'

...and refer to them as, in this case, :var in SQL queries passed to psql on stdin.

However, this doesn't work from code using PL/PGSQL:

psql --variable=var="'value'" <<'EOF'
  DO $$
  BEGIN
    SELECT :var;
  END;
  $$
EOF

...yielding the error:

ERROR:  syntax error at or near ":"

How can this be resolved?


回答1:


You cannot to use a psql variables inside plpgsql code directly. The symbol substitution is blocked inside strings:

postgres=> select :'xx';
 ?column? 
----------
 AHOJ
(1 row)

postgres=> select ' :xx ';
?column? 
----------
 :xx 
(1 row)

But you can set a server session variables and later to use this kind of variables in plpgsql code (on server side):

postgres=> set myvars.xx = :'xx';
SET
postgres=> do $$ begin 
                   raise notice '>>%<<', current_setting('myvars.xx');
                 end $$;
NOTICE:  >>AHOJ<<
DO

You can use same technique from command line, see: http://okbob.blogspot.cz/2015/01/how-to-push-parameters-to-do-statement.html

last note - the code

BEGIN
  SELECT some;
END;

is invalid in plpgsql. Results of any SELECTs should be stored in some variables. Postgres has not possibility to returns result of free SELECT to client - DO statement is not equivalent of MS SQL procedure.



来源:https://stackoverflow.com/questions/28868514/referring-to-session-variables-set-var-value-from-pl-pgsql

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