微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

postgresql – 在psql中使用位置参数($1,..)

我经常想从我的程序代码中复制/粘贴sql并在psql中测试/调试,并且必须用文字值替换位置参数是很繁琐的.有一个很好的转换方式:
select * from users where name=$1 and email=$2;

至:

select * from users where name='troy' and email='[email protected]';
您可以使用 psql variables.这些是在sql代码中插入的. Per documentation:

A key feature of psql variables is that you can substitute
(“interpolate”) them into regular sql statements,as well as the
arguments of Meta-commands. Furthermore,psql provides facilities for
ensuring that variable values used as sql literals and identifiers are
properly quoted. The Syntax for interpolating a value without any
quoting is to prepend the variable name with a colon (:).

请注意(per documentation):

The name must consist of letters (including non-Latin letters),digits,and underscores.

因此,您无法使用$1格式的位置参数.我假设您从函数体中复制这些代码片段,这就是位置参数的原因?
从Postgresql 9.2开始,即使sql函数也可以按名称引用参数. Per documentation:

Arguments of a sql function can be referenced in the function body using either names or numbers.

自v8.0起,PL / pgsql函数一直支持函数体中的命名参数.

我首选的命名约定是用_前缀函数参数以避免命名冲突.但那是品味和风格的问题.

只有一半的解决方

所以,你的例子可以这样工作:

db=> \set _name 'troy'
db=> \set _email '[email protected]'
db=> select * from users where name=:'_name' and email=:'_email';

您仍然需要准备查询字符串…
请注意:’_ name’中的引号.这与在字符串上应用quote_literal()具有相同的效果. Details in the manual.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐