psql传递变量 [英] psql passed variable

查看:262
本文介绍了psql传递变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

psql脚本的新手。

我尝试将变量传递给psql脚本,但出现错误:

  psql -v dateav = 2012-01-28 mcdb -p 5555 -U admin -q -t -A -c'从v_activities选择计数(client_name),其中cheduled_start_date类似于:'dateav';'

错误:v_activities中:
第1行... ...或附近的语法错误,其中cheduled_start_date如:dateav;

有什么想法吗?

解决方案

将像这样工作:

  echo从v_activities select $ b $中选择计数(client_name) b其中,cheduled_start_date像:'dateav' | \ 
psql -v dateav = 2012-01-28 mcdb -p 5555 -U admin -q -t -A



说明:



我引用此处的手册


-c命令



(...)命令必须是服务器完全可解析的命令字符串(即,它不包含没有特定于psql的功能


加粗强调。您可以通过在命令中使用管道而不是使用 -c 选项来克服此限制。

  echo'command'| psql 

这种不同的调用稍微贵一些,但是这样可以按照您的意图替换psql变量。 / p>

尾随反斜杠仅用于换行。同一行上不得有任何字符。唯一的目的是使用更好的格式。






在这种简单情况下,您可以只使用变量 before 您调用psql:

  psql mcdb -p 5555 -U admin -q -t -A \ 
-c从v_activities \
中选择计数(client_name),其中schedule_start_date类似于'2012-01-28'

我在命令行上使用双引号来获取单引号。您还可以结合美元引用和单引号:

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

但是您的现实生活应用程序中可能还存在其他限制。


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?

解决方案

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.

这篇关于psql传递变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆