在 PostgreSQL 查询中声明变量
如何声明在 PostgreSQL 8.3 查询中使用的变量?
在 MS SQL Server 中我可以这样做:
DECLARE @myvar INT;
SET @myvar = 5/
SELECT * FROM somewhere WHERE something = @myvar;
How do I do the same in PostgreSQL?根据文档,变量被简单地声明为“名称类型;”,但这给了我一个语法错误:
myvar INTEGER;
有人能给我一个正确语法的例子吗?
How do I declare a variable for use in a PostgreSQL 8.3 query?
In MS SQL Server I can do this:
DECLARE @myvar INT;
SET @myvar = 5/
SELECT * FROM somewhere WHERE something = @myvar;
How do I do the same in PostgreSQL? According to the documentation variables are declared simply as "name type;", but this gives me a syntax error:
myvar INTEGER;
Could someone give me an example of the correct syntax?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(18)
我通过使用
WITH
子句实现了相同的目标,它远没有那么优雅,但可以做同样的事情。但对于这个例子来说,这确实有点过分了。我也不是特别推荐这个。I accomplished the same goal by using a
WITH
clause, it's nowhere near as elegant but can do the same thing. Though for this example it's really overkill. I also don't particularly recommend this.PostgreSQL 中没有这样的功能。您只能在 pl/PgSQL(或其他 pl/*)中执行此操作,但不能在普通 SQL 中执行此操作。
一个例外是
WITH ()
查询,它可以用作变量,甚至可以用作变量的元组
。它允许您返回临时值表。There is no such feature in PostgreSQL. You can do it only in pl/PgSQL (or other pl/*), but not in plain SQL.
An exception is
WITH ()
query which can work as a variable, or eventuple
of variables. It allows you to return a table of temporary values.您也可以在 PLPGSQL 中尝试此操作:
以上需要 Postgres 9.0 或更高版本。
You could also try this in PLPGSQL:
The above requires Postgres 9.0 or later.
动态配置设置
您可以为此“滥用”动态配置设置:
配置设置始终是 varchar 值,因此您需要在使用它们时将它们转换为正确的数据类型。这适用于任何 SQL 客户端,而
\set
仅适用于psql
上述需要 Postgres 9.2 或更高版本。
对于以前的版本,该变量必须在使用之前在
postgresql.conf
中声明,因此它在某种程度上限制了它的可用性。实际上不完全是变量,而是配置“类”,本质上是前缀。但是一旦定义了前缀,就可以使用任何变量而无需更改postgresql.conf
Dynamic Config Settings
you can "abuse" dynamic config settings for this:
Config settings are always varchar values, so you need to cast them to the correct data type when using them. This works with any SQL client whereas
\set
only works inpsql
The above requires Postgres 9.2 or later.
For previous versions, the variable had to be declared in
postgresql.conf
prior to being used, so it limited its usability somewhat. Actually not the variable completely, but the config "class" which is essentially the prefix. But once the prefix was defined, any variable could be used without changingpostgresql.conf
这取决于您的客户。
但是,如果您使用的是 psql 客户端,则可以使用以下内容:
如果您使用的是文本变量,则需要引用。
It depends on your client.
However, if you're using the psql client, then you can use the following:
If you are using text variables you need to quote.
该方案基于 fei0x 提出的方案,但优点是无需加入查询中的常量和常量可以轻松地在查询开始时列出。它也适用于递归查询。
基本上,每个常量都是在WITH子句中声明的单值表,然后可以在查询的其余部分中的任何位置调用该表。
或者,您可以使用 SELECT * FROM Constant_name 来代替
TABLE Constant_name
,这对于不同于 postgresql 的其他查询语言可能无效。This solution is based on the one proposed by fei0x but it has the advantages that there is no need to join the value list of constants in the query and constants can be easily listed at the start of the query. It also works in recursive queries.
Basically, every constant is a single-value table declared in a WITH clause which can then be called anywhere in the remaining part of the query.
Alternatively you can use
SELECT * FROM constant_name
instead ofTABLE constant_name
which might not be valid for other query languages different to postgresql.在 pl/PgSQL 之外使用临时表
除了按照建议使用 pl/pgsql 或其他 pl/* 语言之外,这是我能想到的唯一其他可能性。
Using a Temp Table outside of pl/PgSQL
Outside of using pl/pgsql or other pl/* language as suggested, this is the only other possibility I could think of.
我想对 @DarioBarrionuevo 的答案提出改进,以使其更简单地利用临时表。
I want to propose an improvement to @DarioBarrionuevo's answer, to make it simpler leveraging temporary tables.
正如您从其他答案中了解到的,PostgreSQL 在直接 SQL 中没有这种机制,尽管您现在可以使用 匿名块。但是,您可以使用公共表表达式 (CTE) 执行类似的操作:
当然,您可以拥有任意多个变量,并且也可以导出它们。例如:
该过程是:
SELECT
生成单行 cte,无需表(在 Oracle 中,您需要包含FROM DUAL
)。SELECT
子句中可能出现的问题。我使用了 PostgreSQL 的较短语法,但您可以使用更正式的CAST('1980-01-01' AS date)
来实现跨方言兼容性。通常,您希望避免交叉联接,但由于您仅交叉联接单行,因此这会产生简单地使用可变数据扩大表的效果。
在许多情况下,如果名称与其他表中的名称不冲突,则不需要包含
vars.
前缀。我把它放在这里是为了明确这一点。此外,您还可以继续添加更多 CTE。
这也适用于支持变量的所有当前版本的 MSSQL 和 MySQL,以及不支持变量的 SQLite,以及支持或不支持变量的 Oracle。
As you will have gathered from the other answers, PostgreSQL doesn’t have this mechanism in straight SQL, though you can now use an anonymous block. However, you can do something similar with a Common Table Expression (CTE):
You can, of course, have as many variables as you like, and they can also be derived. For example:
The process is:
SELECT
without a table (in Oracle you will need to includeFROM DUAL
).CROSS JOIN
syntax, the older comma syntax is slightly more readable.SELECT
clause. I used PostgreSQL’s shorter syntax, but you could have used the more formalCAST('1980-01-01' AS date)
for cross-dialect compatibility.Normally, you want to avoid cross joins, but since you’re only cross joining a single row, this has the effect of simply widening the table with the variable data.
In many cases, you don’t need to include the
vars.
prefix if the names don’t clash with the names in the other table. I include it here to make the point clear.Also, you can go on to add more CTEs.
This also works in all current versions of MSSQL and MySQL, which do support variables, as well as SQLite which doesn’t, and Oracle which sort of does and sort of doesn’t.
您可以诉诸工具的特殊功能。就像 DBeaver 自己的专有语法一样:
You may resort to tool special features. Like for DBeaver own proprietary syntax:
确实,没有生动且明确的方法来声明单值变量,您可以做的是
,要访问此构造中存储的值,您可以
这样做
True, there is no vivid and unambiguous way to declare a single-value variable, what you can do is
then, to get access to the value stored in this construction, you do
for example
以下是使用 PREPARE 语句 的示例。您仍然不能使用
?
,但可以使用$n
表示法:Here is an example using PREPARE statements. You still can't use
?
, but you can use$n
notation:在 DBeaver 中,您可以像在代码中一样在查询中使用参数,因此这将起作用:
当您运行查询时,DBeaver 将询问您 :myvar 的值并运行查询。
In DBeaver you can use parameters in queries just like you can from code, so this will work:
When you run the query DBeaver will ask you for the value for :myvar and run the query.
这是在 postges 终端中使用普通变量的代码段。我已经用过几次了。但需要想出更好的办法。在这里我正在使用字符串变量。使用整数变量,不需要三引号。三引号在查询时变成单引号;否则你会遇到语法错误。在使用字符串变量时,可能有一种方法可以消除三引号的需要。如果您找到改进的方法,请更新。
Here is a code segment using plain variable in postges terminal. I have used it a few times. But need to figure a better way. Here I am working with string variable. Working with integer variable, you don't need the triple quote. Triple quote becomes single quote at query time; otherwise you got syntax error. There might be a way to eliminate the need of triple quote when working with string variables. Please update if you find a way to improve.
在 psql 中,您可以将这些“变量”用作宏。请注意,它们在每次使用时都会“评估”,而不是在“设置”时进行。
简单的例子:
每次都会给出两个不同答案。
但是,您仍然可以使用它们作为有价值的速记,以避免重复大量子选择。
然后在稍后的查询中使用它,
例如
请注意,您必须对变量中的字符串加双引号,因为整个内容都会被字符串插值(即宏扩展)到您的查询中。
In psql, you can use these 'variables' as macros. Note that they get "evaluated" every time they are used, rather than at the time that they are "set".
Simple example:
this gives two different answers each time.
However, you can still use these as a valuable shorthand to avoid repeating lots of subselects.
and then use it in your queries later as
e.g.
Note you have to double-quote the strings in the variables, because the whole thing is then string-interpolated (i.e. macro-expanded) into your query.
例如,您可以设置 自定义选项
my.num
和my.first.name
作为变量,如下所示。 *一个自定义选项可以有多个.
,并且自定义选项在注销后将被删除:或者,您可以使用set_config() 如下所示。 *对于
set_config()
,第三个参数中的false
表示新值适用于当前会话并且 <第三个参数中的 code>true 表示新值适用于当前交易并且我的回答详细解释了set_config()
:那么,你必须使用current_setting() 获取自定义选项的值
my.num< /code> 和
my.first.name
如下所示:小心,设置自定义选项时不使用
.
获取 错误如下所示:或者:
并且,
2
中没有''
set_config()
获取 错误如下所示:并且,使用不带
current_setting()
的自定义选项无法获取如下所示的值:并且,使用不带
''
的自定义选项并且current_setting()
得到错误 如下图:接下来例如可以使用 \set 将数字
2
设置为num
,如下所示。 *您必须根据文档 否则会出现错误,num
会在注销后被删除:并且,您可以使用
\set
将带有''
的文本John Smith
设置为name
,如下所示。 *请勿将""
用于John Smith
,因为""
包含在文本中,因此输出为"John Smith"
并且您必须使用''
作为name
,否则会出现错误,并且name
在注销后会被删除:设置文本时要小心
John Smith
不带''
到name
会删除John
和Smith
之间的空格,如下所示如下所示:并且,仅使用
\set
即可显示所有变量,如下所示:并且,您可以使用 \unset 取消设置(删除)
num
和name
作为如下所示:另外,您可以使用 \echo 输出
num
如下所示:并且,您可以使用 \echo 输出
name
如下所示。 *请勿使用''
作为name
,因为''
包含在文本中,因此输出为'John Smith'< /代码>:
For example, you can set the custom options
my.num
andmy.first.name
as variables as shown below. *A custom option can have multiple.
and custom options are deleted after logout:Or, you can set the custom options with set_config() as shown below. *For
set_config()
,false
in the 3rd argument means the new value applies to the current session andtrue
in the 3rd argument means the new value applies to the current transaction and my answer explainsset_config()
in detail:Then, you must use current_setting() to get the values of the custom options
my.num
andmy.first.name
as shown below:Be careful, setting a custom option without
.
gets the error as shown below:Or:
And,
2
without''
inset_config()
gets the error as shown below:And, using a custom option without
current_setting()
cannot get the value as shown below:And, using a custom option without
''
andcurrent_setting()
gets the error as shown below:Next for example, you can use \set to set the number
2
tonum
as shown below. *You must use:
to accessnum
according to the doc otherwise there is error andnum
is removed after logout:And, you can use
\set
to set the textJohn Smith
with''
toname
as shown below. *Don't use""
forJohn Smith
because""
is included in the text so the output is"John Smith"
and you must use''
forname
otherwise there is error andname
is removed after logout:Be careful, setting the text
John Smith
without''
toname
removes the space betweenJohn
andSmith
as shown below:And, only using
\set
can show all variables as shown below:And, you can use \unset to unset(remove)
num
andname
as shown below:In addition, you can use \echo to output
num
as shown below:And, you can use \echo to output
name
as shown below. *Don't use''
forname
because''
is included in the text so the output is'John Smith'
:使用fei0x的答案和bluish的建议 您可以将它们组合起来将您的值存储在
TEMP
表中。如果有人想使用日期/时间戳保存到变量中,以下是一个片段。您可以在任何查询中使用变量
v_startdate
和v_enddate
。Using fei0x's answer and bluish's suggestion you can combine them to store your values in a
TEMP
table. Following is a snippet if someone wants to use the date/timestamp to save into the variables.You can use the variables
v_startdate
andv_enddate
in any query.在简单查询中(Postgress)
In simple query (Postgress)