在psql中使用位置参数($ 1,..) [英] Using positional parameter ($1,..) in psql

查看:487
本文介绍了在psql中使用位置参数($ 1,..)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常想从程序代码中复制/粘贴sql并在psql中进行测试/调试,必须用文字值替换位置参数很麻烦。是否有转换的好方法:

I often want to copy/paste sql out of my program code and test/debug in psql and it is tedious to have to replace positional arguments with literal values. Is there a good way to convert:

select * from users where name=$1 and email=$2; 

至:

select * from users where name='troy' and email='t@me.com';


推荐答案

您可以使用 psql变量。这些是用SQL代码内插的。 每个文档:

You could use psql variables. Those are interpolated in SQL code. Per documentation:


psql变量的主要功能是可以将
(内插)它们替换为常规SQL语句,也可以替换$ b元命令的$ b个参数。此外,psql为
提供了便利,以确保正确引用用作SQL文字和标识符的变量值
。在没有任何
引用的情况下插值的语法是在变量名前加一个冒号()。

请注意,(每个文档):


名称必须包含字母(包括非拉丁字母),数字,和下划线。

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

因此,您不能使用 $ 1 形式的位置参数。我假设您是从函数主体复制这些代码的,这就是位置参数的原因吗?

自PostgreSQL 9.2起,甚至SQL函数也可以按名称引用参数。 每个文档:

So you cannot work with positional parameters of the form $1. I am assuming you copy these pieces of code from function bodies, and that's the reason for the positional parameters?
Since PostgreSQL 9.2, even SQL functions can reference parameters by name. Per documentation:


可以使用名称或数字在函数主体中引用SQL函数的参数。

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

自v8.0起,

PL / pgSQL函数在功能主体中一直支持命名参数。

PL/pgSQL functions have been supporting named parameters in the function body since v8.0.

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

My preferred naming convention is to prepend function parameters with _ to avoid naming conflicts. But that's a matter of taste and style.

因此,您的示例可以像

db=> \set _name 'troy'
db=> \set _email 't@me.com'
db=> select * from users where name=:'_name' and email=:'_email'; 

您仍然必须准备查询字符串...

注意引号:'_ name'。与在字符串上应用 quote_literal()具有相同的效果。 手册中的详细信息。

You still have to prepare query strings ...
Note the quotes in :'_name'. That has the same effect as applying quote_literal() on the string. Details in the manual.

这篇关于在psql中使用位置参数($ 1,..)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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