Oracle UTL_FILE的使用

來源:互聯網
上載者:User

使用dbms_output輸出有一個缺點是要到整個過程執行完畢才會把結果輸出到螢幕,這樣就無法在一個長時間啟動並執行過程中通過dbms_output輸出來隨時監控執行狀況。
為此可以使用utl_file包來輸出檔案。

utl_file.fopen 開啟檔案
utl_file.put_line 輸出檔案
utl_file.get_line 讀取檔案
utl_file.fclose 關閉檔案
utl_file.fflush 強制輸出緩衝
utl_file.fopen的第一個參數指定檔案所在目錄,這個目錄必須包含在utl_file_dir參數指定的目錄列表中,或者指定一個directory對象。否則fopen()會報錯。

1)utl_file_dir
設定這個參數必須重起資料庫,可以指定多個目錄(用逗號隔開)。如果指定為*,表示任意目錄。
alter system set utl_file_dir='\u01\Oracle','\u02\oracle' scope=spfile;

2)directory
建立一個directory對象並賦予所有使用者讀寫權利
create or replace directory logfile_target as '/u01/oracle';
grant read,write on directory logfile_target to public;
察看已有的directory對象
select * from dba_directories;

3)使用utl_file包輸出檔案
DECLARE
l_file utl_file.file_type;
BEGIN
l_file := utl_file.fopen('LOGFILE_TARGET', 'sql.log', 'W');
for row in (select * from user_tables)
loop
utl_file.put_line(l_file, dbms_metadata.get_ddl('TABLE', row.table_name));
end loop;
utl_file.fclose(l_file);
END;
*這裡也可以寫成utl_file.fopen('/u01/oracle', 'sql.log', 'W');
*fopen()的第三個參數OPEN_MODE,可以指定為
r -- read text
w -- write text
a -- append text
rb -- read byte mode
wb -- write byte mode
ab -- append byte mode
如果指定'a'或者'ab'但是檔案不存在會先建立。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.