KingbaseES函数如何返回结果集

函数返回值一般是某一类型值,如int,varchar,date等,返回结果集时就需要用到setof语法。

  • 创建数据
    create table class(id number primary key, name varchar(20));
    create table student(id number, name varchar(20),classtid number references class);
    insert into class values (1, '六年一班'),(2, '六年二班'),(3, '六年三班');
    insert into student values (1, '张三',1);
    insert into student values (2, '李四',2);
    insert into student values (3, '王五',2);

  • 例1

test=# \set SQLTERM /
test=# create or replace function f_get_class()
test-# returns setof class
test-# as
test-# $$
test$# select * from class;
test$# $$
test-# language sql;
test-# /
CREATE FUNCTION

  • 查询结果

test=# \set SQLTERM ;
test=# select * from f_get_class();
id | name
----+----------
1 | 六年一班
2 | 六年二班
3 | 六年三班
(3 行记录)

KingbaseES还支持对函数结果集的条件查询

test=# select * from f_get_class() where id =3;
id | name
----+----------
3 | 六年三班
(1 行记录)

  • 例2

test=# \set SQLTERM /
test=# create or replace function f_get_table(text) returns setof record as
test-# $$
test$# declare
test$# rec record;
test$# begin
test$# for rec in EXECUTE 'select * from ' || $1 loop
test$# return next rec;
test$# end loop;
test$# return;
test$# end
test$# $$
test-# language 'plpgsql';
test-# /
CREATE FUNCTION

  • 查询结果

test=# select * from f_get_table('student') as student(stuid number, name varchar(20),classtid number);
stuid | name | classtid
-------+------+----------
1 | 张三 | 1
2 | 李四 | 2
3 | 王五 | 2
(3 行记录)

test=# select * from f_get_table('class') as class(id number, name varchar(20));
id | name
----+----------
1 | 六年一班
2 | 六年二班
3 | 六年三班
(3 行记录)

posted @ 2022-03-04 16:00  KINGBASE研究院  阅读(72)  评论(0编辑  收藏  举报