问题描述
金仓数据库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-# KaTeX parse error: Can't use function '$' in math mode at position 6: test$̲# select * from…
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-# KaTeX parse error: Can't use function '$' in math mode at position 6: test$̲# declare 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 行记录)