41.12. 表函数

表函数可以将数组数据进行行转列操作,参数类型可以是数组或者嵌套表,或者是函数返回值(数组/嵌套表)。也可以查询语句中使用。 为了兼容Oracle数据库的table函数的功能,当from子句中使用table函数, 并且table函数返回的数据是单列时,将列名修改为column_value。这个功能在Oracle兼容模式下生效。

数组例子:

select table(array[1,2,3]) as a;

嵌套表例子:

create type kk is table of int;
select table(kk(1,2,3)) as a;

函数返回值的例子:

create table t1(a int, b int);
insert into t1 (values (1,1), (2,2), (3,3));

create or replace package pkg
as
	type nt is table of t1%rowtype;
	res nt;
	function myfunc() return nt;
end;
/

create or replace package body pkg
as
	function myfunc() return nt
	is
	begin
		res(1) := ROW(1,1);
		res(2) := ROW(2,2);
		res(3) := ROW(3,3);
		return res;
	end;
end;
/

select * from table(pkg.myfunc());

查询语句使用例子:

create type kk is table of int;
create table t100 (a int, b kk);
insert into t100 values(1, kk(1, 2));
insert into t100 values(2, kk(3, 4, 5));
select a, b_table from t100, table(b) b_table;