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?
You cannot to use a psql variables inside plpgsql code directly. The symbol substitution is blocked inside strings:
But you can set a server session variables and later to use this kind of variables in plpgsql code (on server side):
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
is invalid in plpgsql. Results of any
SELECT
s should be stored in some variables. Postgres has not possibility to returns result of freeSELECT
to client -DO
statement is not equivalent of MS SQL procedure.