psql passed variable

2019-05-29 02:14发布

问题:

New to psql scripting.
I try to pass a variable to a psql script but get an error:

psql -v dateav="2012-01-28" mcdb -p 5555 -U admin -q -t -A -c 'select count (client_name) from v_activities where scheduled_start_date like :'dateav';'

ERROR:  syntax error at or near ":"
LINE 1: ...) from v_activities where scheduled_start_date like :dateav;

Any ideas?

回答1:

Would work like this:

echo "select count (client_name) from v_activities \
where scheduled_start_date like :'dateav'" | \
psql -v dateav="2012-01-28" mcdb -p 5555 -U admin -q -t -A

Explain:

I quote the manual here:

-c command

(...) command must be either a command string that is completely parsable by the server (i.e., it contains no psql-specific features)

Bold emphasis mine. You can overcome this restriction by piping in the command instead of using the -c option.

echo 'command' | psql

This different invocation is slightly more expensive, but this way psql variables are substituted like you intended.

Trailing backslashes are just for line continuation. No character may follow on the same line. The only purpose is a nicer format.


For this simple case you could just substitute the variable before you call psql:

psql mcdb -p 5555 -U admin -q -t -A \
     -c "select count (client_name) from v_activities \
         where scheduled_start_date like '2012-01-28'"

I use double-quotes on the command-line to get in single-quotes. You could also combine dollar-quoting and single-quotes:

-c 'select ... like $x$2012-01-28$x$'

But you probably have other restrictions in your real life application.