2011-12-20 23 views
0

我有功能,如:循环数组提供了错误的Oracle

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 
+0

如果我想返回type1,应该返回什么类型的函数? – chetan 2011-12-20 07:12:56

回答

2

如果您想选择多行,你可以使用批量一个PLSQL表收集:

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

更新:,如果你想返回类型1:

我不认为你可以在使用%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 ; 
/

,但我敢肯定,你就可以选择一个内statment使用它:

select package_name.dedup_temp() from dual; 

对于做这样的事情,你需要一个管道函数

+0

'bulk collect'是对的,但是'type1(num)'不是。它应该是'type1'。 – 2011-12-20 06:49:53

+0

感谢@RenéNyffenegger,修复它(我应该检查我复制粘贴) – 2011-12-20 06:52:21

+0

谢谢它应该工作。 – chetan 2011-12-20 07:09:43

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; 
+0

实际上,我想返回数组,即从这个函数,但之前我想检查这是迭代可能呢? – chetan 2011-12-20 06:40:48

+0

如果这就是你想要的,为什么你会问一个完全不同的问题? – 2011-12-20 06:50:36

+0

对不起,实际上我没有原始代码的副本 – chetan 2011-12-20 07:18:42