加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-13 18:06:37 所属栏目:百科 来源:网络整理
导读:我经常想从我的程序代码中复制/粘贴sql并在psql中测试/调试,并且必须用文字值替换位置参数是很繁琐的.有一个很好的转换方式: select * from users where name=$1 and email=$2; 至: select * from users where name='troy' and email='t@me.com'; 您可以使
我经常想从我的程序代码中复制/粘贴sql并在psql中测试/调试,并且必须用文字值替换位置参数是很繁琐的.有一个很好的转换方式:
select * from users where name=$1 and email=$2;

至:

select * from users where name='troy' and email='t@me.com';
您可以使用 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 't@me.com'
db=> select * from users where name=:'_name' and email=:'_email';

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读