简体   繁体   English

使用 PL/pgSQL 将查询结果存储在变量中

[英]Store query result in a variable using in PL/pgSQL

How to assign the result of a query to a variable in PL/pgSQL, the procedural language of PostgreSQL?如何将查询结果分配给 PL/pgSQL(PostgreSQL 的过程语言)中的变量?

I have a function:我有一个功能:

CREATE OR REPLACE FUNCTION test(x numeric)
RETURNS character varying AS
$BODY$
DECLARE
name   character varying(255);
begin
 name ='SELECT name FROM test_table where id='||x;

 if(name='test')then
  --do somthing
 else
  --do the else part
 end if;
end;
return -- return my process result here
$BODY$
LANGUAGE plpgsql VOLATILE

In the above function I need to store the result of this query:在上面的函数中,我需要存储这个查询的结果:

'SELECT name FROM test_table where id='||x;

to the variable name .到变量name

How to process this?这个怎么处理?

I think you're looking for SELECT select_expressions INTO :我认为您正在寻找SELECT select_expressions INTO

select test_table.name into name from test_table where id = x;

That will pull the name from test_table where id is your function's argument and leave it in the name variable.这将从test_table中提取name ,其中id是您函数的参数,并将其保留在name变量中。 Don't leave out the table name prefix on test_table.name or you'll get complaints about an ambiguous reference.不要在test_table.nametest_table.name表名前缀,否则您会收到关于不明确引用的投诉。

As long as you are assigning a single variable, you can also use plain assignment in a plpgsql function:只要您分配单个变量,您也可以在 plpgsql 函数中使用普通分配:

name := (SELECT t.name from test_table t where t.id = x);

Or use SELECT INTO like @mu already provided .或者使用SELECT INTO就像@mu已经提供的一样

This works, too:这也有效:

name := t.name from test_table t where t.id = x;

But better use one of the first two, clearer methods, as @Pavel commented.但是最好使用前两种更清晰的方法之一,正如@Pavel 所评论的那样。

I shortened the syntax with a table alias additionally.我还使用表别名缩短了语法。
Update: I removed my code example and suggest to use IF EXISTS() instead like provided by @Pavel .更新:我删除了我的代码示例并建议使用IF EXISTS()代替@Pavel 提供的

The usual pattern is EXISTS(subselect) :通常的模式是EXISTS(subselect)

BEGIN
  IF EXISTS(SELECT name
              FROM test_table t
             WHERE t.id = x
               AND t.name = 'test')
  THEN
     ---
  ELSE
     ---
  END IF;

This pattern is used in PL/SQL, PL/pgSQL, SQL/PSM, ...该模式用于 PL/SQL、PL/pgSQL、SQL/PSM、...

Create Learning Table:创建学习表:

CREATE TABLE "public"."learning" (
    "api_id" int4 DEFAULT nextval('share_api_api_id_seq'::regclass) NOT NULL,
    "title" varchar(255) COLLATE "default"
);

Insert Data Learning Table:插入数据学习表:

INSERT INTO "public"."learning" VALUES ('1', 'Google AI-01');
INSERT INTO "public"."learning" VALUES ('2', 'Google AI-02');
INSERT INTO "public"."learning" VALUES ('3', 'Google AI-01');

Step: 01步骤:01

CREATE OR REPLACE FUNCTION get_all (pattern VARCHAR) RETURNS TABLE (
        learn_id INT,
        learn_title VARCHAR
) AS $$
BEGIN
    RETURN QUERY SELECT
        api_id,
        title
    FROM
        learning
    WHERE
        title = pattern ;
END ; $$ LANGUAGE 'plpgsql';

Step: 02步骤:02

SELECT * FROM get_all('Google AI-01');

Step: 03步骤:03

DROP FUNCTION get_all();

Demo:演示: 在此处输入图片说明

Per Executing a Query with a Single-Row Result , use this syntax:Executing a Query with a Single-Row Result ,使用以下语法:

SELECT select_expressions INTO [STRICT] target FROM ...

where target can be a record variable, a row variable, or a comma-separated list of simple variables and record/row fields.其中target可以是记录变量、行变量或逗号分隔的简单变量和记录/行字段列表。

Unlike the SELECT INTO , SELECT select_expressions INTO does not create a table.SELECT INTO不同, SELECT select_expressions INTO不创建表。

In your example, you have a single simple variable name , so the select statement would be:在您的示例中,您有一个简单的变量name ,因此 select 语句将是:

SELECT test_table.name INTO name FROM test_table WHERE test_table.id = x;

You can use the following example to store a query result in a variable using PL/pgSQL:您可以使用以下示例将查询结果存储在使用 PL/pgSQL 的变量中:

 select * into demo from maintenanceactivitytrack ; 
    raise notice'p_maintenanceid:%',demo;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM