gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 11:25:13 25 4
gpt4 key购买 nike

我经常想从我的程序代码中复制/粘贴 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 thearguments of meta-commands. Furthermore, psql provides facilities forensuring that variable values used as SQL literals and identifiers areproperly quoted. The syntax for interpolating a value without anyquoting 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.

PL/pgSQL 函数从 v8.0 开始支持在函数体中命名参数。

我首选的命名约定是在函数参数前加上 _ 以避免命名冲突。但这是品味和风格的问题。

只有一半的解决方案

因此,您的示例可以像这样工作:

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.

关于postgresql - 在 psql 中使用位置参数 ($1,..),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25090153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com