0 0

难题:存储过程或函数,返回多个查询结果的集合,涉及到游标,集合操作等。5

最近在做一个批量查询,在参数表里取出参数,然后对每个参数查询主表,每个参数对应多个结果,只取前n行,把这些结果集合起来,返回。
最开始用的是一条语句查询,由于用不到索引,查询相当慢,所以改为用存储过程。
原来的语句
select t.*,(row_number() over (partition by t.col_name2 order by t.col_name3)) rn from (
  select * from main_table 
  where col_name1 in ($params$)  and $otherParams$
) where rn < #maxReturn#

现在改为用存储过程来做,遇到的问题:
1、otherparam是拼成的sql字符串,涉及多个字段(col1 = value or col2 = value or col3 = .....),如果先组装字符串再执行 open cursor for sqlString,sql不能包含 bulk collect into。
2、通过select col1,col2,col3 bulk into collect t_type_table from maintable where col1 = param1 查出结果,如何把一个参数查出的结果放到一个大的集合里,统一返回?
一部分代码:
create or replace function fun_query_batch(param_seq varchar2, otherParams varchar2, maxAmount number)

--返回类型,已创建 create  or replace type xxx is object(col1 varchar(100), col2 varchar(1000) ...)
-- create  or replace type res_type_table is table of xxx;
return res_type_table

is
--取出参数
cursor cursor_param is select t.col1 from param_table where t.seq = param_seq;

x param_table%rowtype;

res_table is type_res_table := type_res_table();

res_table_all is type_res_table := type_res_table();


begin

for x in cursor_param loop

--查询主表,如果加入otherParams就需要拼接字符串,这里暂不考虑
select tp_maintable(col1,col2,col3) bulk collect into res_table from (
  select * from maintable where colName = x.col1 order by colName2
)where rownum <= maxAmount ;

dbms_output.put_line( res_table.count );
--如果查出数据,加入到总的集合里。(另外一种方式是插入到临时表里,然后统一取出,但是需要建临时表,还要再去查一次清理一次)
if p_table.count > 0 then

for i in p_table.first .. p_table.last loop
--这里应该怎么处理?
p_table_all.extend();

end loop;
end if;


end loop;

dbms_output.put_line( res_table_all.count );
dbms_output.put_line( res_table_all(1).colname );

return p_table_all;

end;

调用方式:
select * from table(fun_query_batch('seq','otherparam',10));


还有procedure方式的查询,返回游标,逻辑跟上面的差不多。

不管用什么方式,怎样实现这个批量查询的功能?

各位兄弟帮下忙!先谢谢了
2014年11月04日 18:46

1个答案 按时间排序 按投票排序

0 0

如何把一个参数查出的结果放到一个大的集合里,统一返回?
自定义一个 table ,在你检索完之后,new一个自定义的table,往里面放数据。然后返回就ok了。

2014年11月05日 13:01

相关推荐

Global site tag (gtag.js) - Google Analytics