2017-07-27 58 views
0

的oracle管道函數我想創建一個函數,它返回一個可以在select語句中作爲表使用的對象。根據對oracle文檔的研究,我發現一個PIPELINED函數是我需要的。用sql來管道管道函數的語法有問題。提前致謝!包含SQL使用條款

DROP TYPE ODSMaxVRSN_ROW; 
DROP TYPE ODSMaxVRSN_TBL; 

CREATE OR REPLACE TYPE ODSMaxVRSN_ROW 
AS OBJECT 
(
    sls_tran_key       INT, 
    sls_tran_key_unaud  int, 
    audit_sls_trans_key  int, 
    sls_4_part_key      varchar2(50), 
    sls_audit_rvsn_nbr  VARCHAR2(25) 
) 
/

CREATE OR REPLACE TYPE ODSMaxVRSN_TBL AS TABLE OF ODSMaxVRSN_ROW 
/

    -- Declare the function 
function GET_ODSMaxVRSN(in_dtFmt varchar2, 
         in_start_date varchar2, 
         in_end_date varchar2) 
     return ODSMaxVRSN_TBL pipelined is 

rt ODSMaxVRSN_TBL; 
l_sql VARCHAR2(2000); 
l_cursor SYS_REFCURSOR; 

begin 
    -- Your query to load the table type 

       l_sql := 'With sales as (
       select s.SLS_TRANS_KEY,s.SLS_4_PART_KEY, nvl(s.SLS_AUDIT_RVSN_NBR,0), a.AUDIT_SLS_TRANS_KEY 
       from SLS_TRANS s 
       left outer join AUDIT_SLS_TRANS a 
               on s.SLS_4_PART_KEY = a.SLS_4_PART_KEY and a.SLS_AUDIT_RVSN_NBR = 1 
       where s.REC_CRT_TS between to_date(''' || in_start_date ||',''' || in_dtFmt || ') and to_date(''' || in_end_date ||',''' || in_dtFmt || ')'' 
           and a.AUDIT_SLS_TRANS_KEY > 0 
               OR s.SLS_AUDIT_RVSN_NBR > 0 
       )    , maxrvsn as (
       Select trn.SLS_4_PART_KEY , max(n) SLS_AUDIT_RVSN_NBR 
           from sales trn 
           group by trn.sls_4_part_key 
       )    , unaudited as (
       select t.SLS_TRANS_KEY, t.SLS_4_PART_KEY, t.SLS_AUDIT_RVSN_NBR 
       from SLS_TRANS t 
       where t.SLS_AUDIT_RVSN_NBR is null 
       ) 
       select t.AUDIT_SLS_TRANS_KEY, t.SLS_TRANS_KEY, t.SLS_4_PART_KEY, t.SLS_AUDIT_RVSN_NBR, u.sls_trans_key unaud_sls_trans_key 
       from sales t 
       inner join maxrvsn m on m.SLS_4_PART_KEY = t.SLS_4_PART_KEY and m.SLS_AUDIT_RVSN_NBR = t.SLS_AUDIT_RVSN_NBR 
       INNER join unaudited u on t.SLS_4_PART_KEY = u.SLS_4_PART_KEY'; 

    OPEN l_cursor FOR l_sql; 
    FETCH l_cursor BULK COLLECT INTO rt; 
    CLOSE l_cursor; 

    -- Stuff the results into the pipeline.. 
    if rt.count > 0 then 
    for i in rt.FIRST .. rt.LAST loop 
     pipe row (rt(i)); 
    end loop; 
    end if; 

    -- Add more results as you please.... 
return; 

end GET_ODSMaxVRSN; 
/

回答

0

而不是做一個BULK COLLECT,然後遍歷表的,你可以嘗試只讀取和在一個循環中的一次管道一行。看到這裏例如:http://www.oracle-developer.net/display.php?id=429

function GET_ODSMaxVRSN(in_dtFmt varchar2, 
         in_start_date varchar2, 
         in_end_date varchar2) 
     return ODSMaxVRSN_TBL pipelined is 

l_row ODSMaxVRSN_ROW; 
l_sql VARCHAR2(2000); 
l_cursor SYS_REFCURSOR; 

begin 

    l_sql := '--your query--'; 

    OPEN l_cursor FOR l_sql; 
    loop 
     fetch l_cursor into l_row; 
     exit when l_cursor%NOTFOUND; 

     pipe row (l_row); 

    end loop; 
    CLOSE l_cursor; 
    return; 
end GET_ODSMaxVRSN; 
/
+0

感謝您的建議。 – user3120960

+0

當我嘗試使用l_sql和l_cursor進行編譯時,我仍然遇到錯誤。還有什麼我需要補充的。 – user3120960