用oracle utl file包讀取資料寫入檔案

2021-05-22 06:38:06 字數 2776 閱讀 5228

create or replace directory my_dir as '/usr/test/';

create or replace function f_exporttxt(

--傳入引數

i_query in varchar2,

i_separator in varchar2,

i_dir in varchar2,

i_filename in varchar2

) return number

--定義引數

v_file utl_file.file_type;

v_thecursor integer default dbms_sql.open_cursor;

v_columnvalue varchar2(2000); --臨時(列值)

v_colcnt number default 0; --列總數

v_separator varchar2(10) default ',';--分隔符,預設為#@

v_cnt number default 0;  --記錄總數

v_filename varchar2(100);--時間

v_status integer;--執行sql後返回狀態值

v_count number default 10000 ; --每次查詢的數量,大於該數量則多次讀取資料到游標

v_tmp number ;--臨時(總記錄數,通過sql統計算出,假如v_cnt不等於v_tmp,則匯出有誤)

v_sql varchar2(2000) ; --組合sql語句

v_loops number ; --迴圈次數

begin

--select to_char(sysdate,'yyyymmddhh24mi') into v_filename from dual; --取時間年月日時分做檔名字首

v_filename :='';

v_filename := v_filename||i_filename ; --組建檔名

v_sql := 'select count(''x'') from (' ||i_query||')' ;--統計總數

execute immediate v_sql into v_tmp;

select trunc(v_tmp/v_count) into v_loops from dual ; --迴圈次數

if mod(v_tmp,v_count) > 0 then

v_loops := v_loops+1;

end if;

v_file := utl_file.fopen(i_dir,v_filename,'w'); --開啟檔案

for i in 1 .. v_loops loop

v_sql := 'select * from ( select m.*,rownum r from ('|| i_query ||' ) m where rownum <= '

||i*v_count ||') where r >'|| (i-1)*v_count ;

dbms_sql.parse(v_thecursor, v_sql, dbms_sql.native);  --解析動態sql語句

for i in 1 .. 255 loop

begin

dbms_sql.define_column(v_thecursor, i, v_columnvalue, 2000); --定義列

v_colcnt := i;

exception

when others then

if (sqlcode = -1007) then

exit;

else

raise;

end if;

end;

end loop;

dbms_sql.define_column(v_thecursor, 1, v_columnvalue, 2000);

v_status := dbms_sql.execute(v_thecursor); --執行sql

loop

exit when(dbms_sql.fetch_rows(v_thecursor) <= 0);  --游標記錄小於0退出

v_separator := ''; --分隔符,第一次為''

for i in 1 .. v_colcnt-1 loop  --迴圈列

dbms_sql.column_value(v_thecursor, i, v_columnvalue); --將當前行的查詢結果寫入上面定義的列中

utl_file.put(v_file, v_separator || v_columnvalue); --將值寫入檔案中

v_separator := i_separator;

end loop;

utl_file.new_line(v_file);--換行

v_cnt := v_cnt + 1;--記錄寫入記錄總數

end loop;

end loop ;

dbms_sql.close_cursor(v_thecursor); --關閉

utl_file.fclose(v_file);--關閉寫入檔案

return v_cnt ;

exception

when others then

dbms_sql.close_cursor(v_thecursor);

utl_file.fclose(v_file);

v_cnt := -1 ;

return v_cnt ;

end f_exporttxt;

Oracle utl file檔案寫入讀取

oracle utl file檔案寫入讀取 1 建立伺服器目錄 1 在system使用者下執行如下命令 create or replace directory mail file dir as tmp data dev 2 給建立的目錄賦許可權,執行 grant read write on dire...

用conda管理Python包

conda是乙個很好的包管理工具,在用了anaconda之後一直不知道怎麼用conda進行管理,其實很簡單,就是沒人教,慢慢自己摸索了一點。直接在anaconda的命令列裡輸入相應命令就行了。雖然在國內用不是很方便,希望有快一點的源。清理 conda clean lock tarball packa...

用陣列理解閉包

閉包 乙個函式可以把自己內部的語句,和自己宣告時所處的作用域封裝在乙個密閉的環境中 函式在定義時,能夠記住自己函式體以及所處的外部環境 每個函式都是閉包,每個函式天生能記住自己定義時所處的作用域環境。這是乙個陣列,陣列中有10個函式,目的 想要輸出函式的角標,也就是說arr 0 彈出0 arr 2 ...