首页 > 解决方案 > 在 psql CLI 中从任何大小写到较小大小写的变量值转换

问题描述

我正在创建一个脚本来通过 psql CLI 在 Postgres 中创建数据库用户,我面临的挑战是从任何大小写到小写的值转换正在发生或无法找到相同的解决方案。

\prompt 'Please input user name (must be lowercase): ' inputName
\set lowerVal lower(:inputName)    --This is not working

按照我的预期,lowerVal 变量应该将 inputValue 转换为小写值。谷歌搜索但没有得到相同的解决方案。

标签: sqlpostgresqlpsqlpostgresql-9.5

解决方案


psql不能评估表达式,所以你的例子不能工作。您可以使用 statement\gset评估查询并将结果存储到psql变量:

postgres=# \prompt 'Please input user name (must be lowercase): ' inputName
Please input user name (must be lowercase): AHOJ
postgres=# select lower(:'inputName') as "inputName" \gset 
postgres=# \echo :inputName
ahoj

可能最好只使用小字符作为psql变量名。

另一种可能性是使用带有反撇号的 shell 表达式评估:

postgres=# \set str AHOJ
postgres=# \set str `echo ":str" | tr "[:upper:]" "[:lower:]"`
postgres=# \echo :str
ahoj

此示例仅适用于类 Unix 系统。


推荐阅读