微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

rush:sql;"> 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、用数组

rush:sql;"> 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

rush:sql;"> 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,sal from emp where deptno = v_deptno; begin for c in cur loop pipe row(t_test(c.empno,c.sal)); end loop; return; end;

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

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

rush:sql;"> 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,sal) bulk collect into v_test from emp where deptno = v_deptno; return v_test; end;

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

rush:sql;"> select * from table(f_test_pipe(30)); select * from table(f_test_array(30)); select * from table(f_test_collect(30));

内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐