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 行记录)
posted @   KINGBASE研究院  阅读(209)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2021-09-18 字符类数据类型和oracle字符类型的区别
点击右上角即可分享
微信分享提示