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 @   KINGBASE研究院  阅读(88)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示