源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2022-12-18 22:50 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:利用函数返回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;
至于返回表对象的方法,目前发现三种: [b] 1、用数组 [/b]
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;
[b]2、用pipe [/b]
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种较高。  [b]3、用collect(不需要游标,代码相对简单) [/b]
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) 否则会报错:  [b]ORA-00947:[/b] 没有足够的值(object多字段) [b]ORA-00932: [/b]数据类型不一致(object单一字段) 而如果直接在plsql块中declare类型的话,是不需要先对象化输出结果的。 三种函数定义方式可以测试输出一样的结果:
select * from table(f_test_pipe(30));
select * from table(f_test_array(30));
select * from table(f_test_collect(30));
[img]http://files.jb51.net/file_images/article/201607/201671893002809.jpg?201661893035[/img] 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部