数组循环在oracle中出错

时间:2011-12-20 06:15:09

标签: oracle plsql

我的功能如下:

create or replace function dedup_temp
 return varchar2
 as 
 TYPE OriType IS TABLE OF deduporiginal%ROWTYPE;
 type1 OriType;
 num number;
 begin
 select count(1) into num from deduporiginal;
 select * into type1(num) from deduporiginal where rownum < 125;


   for i in 1 .. type1.count
   loop
     DBMS_OUTPUT.put_line('v_month_va(i): '||type1(i).name);
   end loop; 

 return 'DONE';

 end dedup_temp;

它编译成功但在使用

等查询运行时出错
 select dedup_temp() from dual;

错误:

ORA-01422: exact fetch returns more than requested number of rows
ORA-06512: at "CRESTELDEDUPDEV.DEDUP_TEMP", line 9
01422. 00000 -  "exact fetch returns more than requested number of rows"
*Cause:    The number specified in exact fetch is less than the rows returned.
*Action:   Rewrite the query or change number of rows requested

2 个答案:

答案 0 :(得分:2)

我假设表deduporiginal为条件rownum < 125

返回多行

你可能想要像

这样的东西
create or replace function dedup_temp  
   return varchar2  
as
   TYPE OriType IS TABLE OF deduporiginal%ROWTYPE;  
   type1 OriType;  num number;  
begin  
  --?   select count(1) into num from deduporiginal;  
  for r in (
       select *   
         from deduporiginal 
         where rownum < 125
  ) loop

      DBMS_OUTPUT.put_line('v_month_va(i): ' || r.name);  
  end loop; 

  return 'DONE';  

end dedup_temp; 

答案 1 :(得分:2)

如果要为plsql表选择多行,可以使用批量收集:

 select * BULK COLLECT into type1 from deduporiginal where rownum < 125;

更新:如果您想要返回type1:

我认为您不能在使用%ROWTYPE的函数之外创建一个类型对象,因此您可能需要将它们全部打包到一个包中:

CREATE OR REPLACE PACKAGE package_name IS
  TYPE OriType IS TABLE OF deduporiginal%ROWTYPE;
  FUNCTION dedup_temp RETURN OriType ;
END package_name ;
/
CREATE OR REPLACE PACKAGE BODY package_name IS
FUNCTION dedup_temp RETURN OriType IS
 type1 OriType;
 num number;
 begin
   select count(1) into num from deduporiginal;
   select * BULK COLLECT into type1 from deduporiginal where rownum < 125;


   for i in 1 .. type1.count
   loop
     DBMS_OUTPUT.put_line('v_month_va(i): '||type1(i).name);
   end loop; 

   return type1 ;
 end dedup_temp;

END package_name ;
/

但我相信您可以在选择的陈述中使用它:

 select package_name.dedup_temp() from dual;

要做那样的事情,你需要一个流水线功能