2011-12-20 49 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