Kingbase 函数查询返回结果集

本文介绍了在KingbaseES中通过自定义类型、table函数、return返回table类型以及setof方式处理结果集的方法,通过实例演示了如何在函数中返回数据。
摘要由CSDN通过智能技术生成

数据库使用过成中,时常会遇到需要返回一个结果集的情况,如何返回一个结果集,以及如何选择一个合适的方式返回结果集,是现场经常需要考虑的问题。
下面介绍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 行记录)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值