postgresql 根据查询结果为变量设置值(PL/pgSQL 风格)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17187873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 00:14:05  来源:igfitidea点击:

Set a value to a variable based on the results of a query (in PL/pgSQL style)

postgresqlplpgsqlpostgresql-9.2

提问by Oto Shavadze

What I need to do is set a value to a variable using the EXECUTINGquery.

我需要做的是使用EXECUTING查询为变量设置一个值。

In pure SQL style, I could do something like the following:

在纯 SQL 样式中,我可以执行以下操作:

// here declaring function and etc...
DECLARE cnt INTEGER;

EXECUTE 'SELECT COUNT(*) FROM t' INTO cnt;

How to achieve the same functionality in the form of a PL/pgSQL function? What is the correct syntax for the following pseudo-code? (The following is obviously the wrong syntax)

如何以 PL/pgSQL 函数的形式实现相同的功能?以下伪代码的正确语法是什么?(以下显然是错误的语法)

cnt :=  EXECUTE ( 'SELECT COUNT(*) FROM t' )   ;

回答by Kurt Burns

I think what you are looking for is:

我认为你正在寻找的是:

cnt := COUNT(*) FROM t;

回答by Roberto

you can use SELECT INTO

你可以使用 SELECT INTO

DECLARE cnt INTEGER;
SELECT INTO cnt count(*) FROM t;

回答by Roberto

Not sure what you mean by "plpgsql style". The syntax you showed is perfectly OK, as shown in documentation.

不确定“plpgsql 风格”是什么意思。您展示的语法完全没问题,如文档中所示。