栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 数据库 > Oracle

利用函数返回oracle对象表的三种方法

Oracle 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

利用函数返回oracle对象表的三种方法

因为要返回表对象,无论后续用什么方法返回,都先要声明全局type;并且,字段变量类型要为object,不能为record:

create or replace type t_test as object(
 EMPNO  NUMBER(4),
 ENAME  VARCHAr2(10),
 JOB   VARCHAr2(9),
 SAL   NUMBER(7,2)
);

create or replace type t_test_table as table of t_test;

至于返回表对象的方法,目前发现三种:
 1、用数组

create or replace function f_test_array(v_deptno in number default null)
return t_test_table
is 
v_test t_test_table := t_test_table();
cursor cur is select empno, ename, job, sal from emp where deptno = v_deptno;
begin
for c in cur loop
v_test.extend();
v_test(v_test.count) := t_test(c.empno, c.ename, c.job, c.sal);
end loop;
return v_test;
end;

2、用pipe

create or replace function f_test_pipe(v_deptno in number default null)
return t_test_table PIPELINED 
is
v_test t_test_table := t_test_table();
cursor cur is select empno, ename, job, sal from emp where deptno = v_deptno;
begin 
for c in cur loop
pipe row(t_test(c.empno, c.ename, c.job, c.sal)); 
end loop; 
return; 
end;

这两种都需要用游标遍历,得到表对象,性能上估计第2种较高。 

3、用collect(不需要游标,代码相对简单)

create or replace function f_test_collect(v_deptno in number default null)
return t_test_table
is 
v_test t_test_table := t_test_table();
begin
select t_test(empno, ename, job, sal) bulk collect into v_test from emp where deptno = v_deptno;
return v_test;
end;

需要注意的是,select into之前要先把输出结果对象化:
t_test(empno, ename, job, sal)
否则会报错: 
ORA-00947: 没有足够的值(object多字段)
ORA-00932: 数据类型不一致(object单一字段)
而如果直接在plsql块中declare类型的话,是不需要先对象化输出结果的。
三种函数定义方式可以测试输出一样的结果:

select * from table(f_test_pipe(30));
select * from table(f_test_array(30));
select * from table(f_test_collect(30));

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/171567.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号