psql passed variable

故事扮演 提交于 2020-01-02 12:39:29

问题


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.



来源:https://stackoverflow.com/questions/13570248/psql-passed-variable

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