加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在PostgreSQL中使用PL/pgSQL返回多个字段作为记录

发布时间:2020-12-13 16:49:34 所属栏目:百科 来源:网络整理
导读:我写了一个SP,使用PL / pgSQL。 我想返回一个记录,包括来自几个不同的表的字段。可能看起来像这样: CREATE OR REPLACE FUNCTION get_object_fields(name text) RETURNS RECORD AS $$BEGIN -- fetch fields f1,f2 and f3 from table t1 -- fetch fields f4
我写了一个SP,使用PL / pgSQL。
我想返回一个记录,包括来自几个不同的表的字段。可能看起来像这样:
CREATE OR REPLACE FUNCTION get_object_fields(name text)
  RETURNS RECORD AS $$
BEGIN
  -- fetch fields f1,f2 and f3 from table t1
  -- fetch fields f4,f5 from table t2
  -- fetch fields f6,f7 and f8 from table t3
  -- return fields f1 ... f8 as a record
END
$$ language plpgsql;

如何从单个记录中的字段返回不同表中的字段?

[编辑]

我意识到,上面给出的例子太简单了。我需要检索的一些字段将被保存为正在查询的数据库表中的单独行,但是我想在“flattened”记录结构中返回它们。

下面的代码应该进一步说明:

CREATE TABLE user (id int,school_id int,name varchar(32));

CREATE TYPE my_type (
  user1_id   int,user1_name varchar(32),user2_id   int,user2_name varchar(32)
);

CREATE OR REPLACE FUNCTION get_two_users_from_school(schoolid int)
  RETURNS my_type AS $$
DECLARE
  result my_type;
  temp_result user;
BEGIN
  -- for purpose of this question assume 2 rows returned
  SELECT id,name INTO temp_result FROM user where school_id = schoolid LIMIT 2;
  -- Will the (pseudo)code below work?:
  result.user1_id := temp_result[0].id ;
  result.user1_name := temp_result[0].name ;
  result.user2_id := temp_result[1].id ;
  result.user2_name := temp_result[1].name ;
  return result ;
END
$$ language plpgsql
您需要定义一个新类型并定义您的函数以返回该类型。
CREATE TYPE my_type AS (f1 varchar(10),f2 varchar(10) /*,... */ );

CREATE OR REPLACE FUNCTION get_object_fields(name text) 
RETURNS my_type 
AS 
$$

DECLARE
  result_record my_type;

BEGIN
  SELECT f1,f2,f3
  INTO result_record.f1,result_record.f2,result_record.f3
  FROM table1
  WHERE pk_col = 42;

  SELECT f3 
  INTO result_record.f3
  FROM table2
  WHERE pk_col = 24;

  RETURN result_record;

END
$$ LANGUAGE plpgsql;

如果要返回多个记录,您需要将该函数定义为返回setof my_type

更新

另一个选项是使用RETURNS TABLE(),而不是创建在Postgres 8.4中引入的TYPE

CREATE OR REPLACE FUNCTION get_object_fields(name text) 
  RETURNS TABLE (f1 varchar(10),... */ )
...

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读