使用PL/pgSQL将查询结果存储在变量中 [英] Store query result in a variable using in PL/pgSQL

查看:608
本文介绍了使用PL/pgSQL将查询结果存储在变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将查询结果分配给PL/pgSQL(PostgreSQL的过程语言)中的变量?

How to assign the result of a query to a variable in PL/pgSQL, the procedural language of PostgreSQL?

我有一个功能:

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;

到变量name.

如何处理?

推荐答案

我认为您正在寻找

I think you're looking for SELECT INTO:

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

这将从test_table中拉出name,其中id是函数的参数,并将其保留在name变量中.不要在test_table.name上保留表名前缀,否则您会抱怨引用不明确.

That will pull the name from test_table where id is your function's argument and leave it in the name variable. Don't leave out the table name prefix on test_table.name or you'll get complaints about an ambiguous reference.

这篇关于使用PL/pgSQL将查询结果存储在变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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