psql passed variable

断了今生、忘了曾经 提交于 2019-12-06 06:58:07

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.

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