2013-07-30 27 views
0

我必須創建將有三個程序寫入文件的另一個函數的結果的包。 功能get_cursor(...)返回SYS_REFCURSOR看起來是這樣的:ORACLE:寫入返回sys_refcursor函數的文件結果

function get_cursor(
    tabname in varchar2, 
    cols in array_t, 
    vals in array_t, 
    rels in array_t) 
    return sys_refcursor 
is 
    cur sys_refcursor; 
    where_statement varchar2(1000); 
    tmp    varchar2(1000); 
begin 
    if cols.last      != 0 then 
    where_statement    := 'WHERE ' || cols(1) || ' ' || rels(1) || ' '; 
    if (rels(1)      = 'in' or rels(1) = 'not in') then 
     where_statement    := where_statement || trim(both '''' from vals(1)); 
    elsif (utils.is_number(vals(1)) = 'N' and substr(vals(1), 1, 8) != 'TO_DATE(') then 
     where_statement    := where_statement || '''' || vals(1) || ''''; 
    else 
     where_statement := where_statement || vals(1); 
    end if; 
    for i in 2..cols.last 
    loop 
     where_statement     := where_statement || ' AND ' || cols(i) || ' ' || rels(i) || ' '; 
     if (rels(i)      = 'in' or rels(i) = 'not in') then 
     where_statement    := where_statement || trim(both '''' from vals(i)); 
     elsif (utils.is_number(vals(i)) = 'N' and substr(vals(i), 1, 8) != 'TO_DATE(') then 
     where_statement    := where_statement || '''' || vals(i) || ''''; 
     else 
     where_statement := where_statement || vals(i); 
     end if; 
    end loop; 
    end if; 
    open cur for 'SELECT * FROM ' || tabname || ' ' || where_statement; 
    return cur; 
end get_cursor; 

是否可以正確它並不重要,它返回的東西,我必須把它寫在程序文件,將採取相同的論據get_cursor需要+路徑和文件名:

procedure txt_export(
    tabname in varchar2, 
    cols  in array_t, 
    vals  in array_t, 
    rels  in array_t, 
    path  in varchar2, 
    file_name in varchar2) 
is 
    l_file utl_file.file_type; 
    tmp_file_name varchar2(4000) := file_name; 
begin 
    if (tmp_file_name like '%.txt') then 
    l_file := utl_file.fopen(path, tmp_file_name, 'w'); 
    elsif (tmp_file_name not like '%.txt') then 
    tmp_file_name := tmp_file_name || '.txt'; 
    l_file  := utl_file.fopen(path, tmp_file_name, 'w'); 
    end if; 

    /* 
    run function get_cursor(tabname, cols, vals, rels) and write result to the file .txt 
    */ 

    utl_file.fclose(l_file); 
end; 

請幫我這個問題。 對不起,我的英語:)

問候!

回答

1

棘手的是該函數返回一個弱引用遊標;您不能使用強引用遊標,因爲該函數會動態組合查詢的投影。所以調用程序無法知道結果集的結構。這個meacns你需要使用動態SQL來詢問結果集並找出元數據。

幸運的是,您正在使用Oracle 11g,因爲Oracle引入了對方法4動態SQL的支持,允許我們將Ref Cursors轉換爲DBMS_SQL遊標。 Find out more

鑑於您已經知道如何使用UTL_FILE打開和關閉文件,我推測您知道如何使用UTL_FILE.PUT()和UTL_FILE.NEW_LINE()寫出列。

+0

謝謝你的回答。這非常有幫助。問題解決了。 高五! – llepec