Kingbase 函数查询返回结果集

发布时间 2023-09-18 16:19:06作者: KINGBASE研究院

数据库使用过成中,时常会遇到需要返回一个结果集的情况,如何返回一个结果集,以及如何选择一个合适的方式返回结果集,是现场经常需要考虑的问题。
下面介绍KingbaseES中各种返回结果集的方式。

1.通过自定义类型方式,返回结果集

-- 测试数据:创建自定义类型
CREATE TYPE rctype AS(id int , nam varchar(10));

CREATE TYPE rctable IS TABLE OF rctype;

创建测试函数:

CREATE OR replace FUNCTION tablereturn1(x int) RETURNS rctable pipelined AS  
BEGIN 
    FOR i IN 1..x LOOP 
      pipe row(rctype(i , to_char(i*i)));
    END LOOP ;
    RETURN ;
END ;

通过table函数方式返回函数结果集数据:

test=# SELECT * FROM TABLE(tablereturn1(5));
 id | nam 
----+-----
  1 | 1
  2 | 4
  3 | 9
  4 | 16
  5 | 25
(5 行记录)

2.通过return返回定义的table类型,返回结果集

-- 测试数据:
CREATE TABLE "public"."table1" (
    "id" integer NULL,
    "nam" character varying(10 char) NULL
);

INSERT INTO "public"."table1" ("id","nam") VALUES
     (1,'a'),
     (2,'b'),
     (3,'c'),
     (4,'d'),
     (5,'e');

创建测试函数:

CREATE OR replace FUNCTION tablereturn2() RETURNS TABLE(id int , nam varchar(10))
AS 
BEGIN 
    RETURN query SELECT id , nam FROM table1; 
END ;

通过table函数方式返回函数结果集数据:

test=# SELECT * FROM tablereturn2();
 id | nam 
----+-----
  1 | a
  2 | b
  3 | c
  4 | d
  5 | e
(5 行记录)

3.通过setof方式返回表结构,返回结果集

-- 测试数据:
CREATE TABLE "public"."table1" (
    "id" integer NULL,
    "nam" character varying(10 char) NULL
);

INSERT INTO "public"."table1" ("id","nam") VALUES
     (1,'a'),
     (2,'b'),
     (3,'c'),
     (4,'d'),
     (5,'e');

创建测试函数:

CREATE OR replace FUNCTION tablereturn3() RETURNS setof table1 AS 
DECLARE 
res record;
BEGIN 
    FOR res IN SELECT * FROM table1 LOOP 
      RETURN NEXT res;
    END LOOP ;
    RETURN;  
END;

通过table函数方式返回函数结果集数据:

test=# select * from tablereturn3();
 id | nam 
----+-----
  1 | a
  2 | b
  3 | c
  4 | d
  5 | e
(5 行记录)