oracle|动态|游标不少朋友在开发过程中,要使用到游标进行统计(不用临时表)并返回统计结果,但游标后面的SQL却是动态的,如select * from tablename where ? order ?."?"代表条件,这样该如何处理呢。在同事的帮助下我实践了一下。总结出来。
假设tablename表中有field如下:
field1 varchar2(50)
field2 Varchar2(50)
field3 Varchar(50)
field4 varchar2(50)
field5 varchar2(20)
field6 float,
field7 float
1.定义游标
create or replace package RefCursor is
-- Author : Ricky
-- Created : 2003-9-1 14:08:45
-- Purpose :
-- Public type declarations
type t_RefCursor is ref cursor;
end RefCursor;
2.创建类型
创建的类型与tablename中表的fields一致,当然也要看你实际是否要统计所有的fields.
create or replace type TableType as object
(
-- Author : Ricky
-- Created : 2003-8-25 9:12:08
-- Purpose :
-- Attributes
field1 varchar2(50),
field2 Varchar2(50),
field3 Varchar(50),
field4 varchar2(50),
field5 varchar2(20),
field6 float,
field7 float
);
3.创建表类型
create or replace type TableTypeList as table of TableType;
4.在存储过程或者函数中使用,下面在函数中使用(存储过程中不能用return一个表结构,要用到临时表)
CREATE OR REPLACE FUNCTION "TEST" (
return TableTypeList pipelined as
begin
v_Cur RefCursor.t_Refcursor;
v_SQLStatement string(10000);
v_Table tablename%rowtype;
tmp1 tablename.field1%Type;
tmp2 tablename.field2%Type;
tmp3 tablename.field3%Type;
tmp4 tablename.field4%Type;
tmp5 tablename.field5%Type;
tmp6 tablename.field6%Type;
tmp7 tablename.field6%Type;
v_SQLStatement := 'Select * From tablename where field1='1' order by field1';
open v_Cur for v_SQLStatement;
loop
--这里是循环过程
fetch v_Cur into v_Comm;
exit when v_CommCur%notfound;
--这里是你要处理的统计过程,中间的过程我没有做统计,各位在实践中按需要自己添加。
field1 = v_Cur.field1;
field2 = v_Cur.field2;
field3 = v_Cur.field3;
field4 = v_Cur.field4;
field5 = v_Cur.field5;
field6 = v_Cur.field6;
field7 = v_Cur.field7;
v_Table = TableType(field1,
field2,
field3,
field4,
field5,
field6,
field7)
pipe row(v_Table);
end loop
end;
Oracle下的动态游标实现(总结)
80酷酷网 80kuku.com