日期:2014-05-16  浏览次数:20439 次

UTL_FILE写文件
oracle内部提供的很多使用的包,为应用提供了可能!
在我们项目中有这样的需求,根本没有必要使用线程来做,直接用oracle原生的功能特性更好,看来包要好好学习!
utl_file写文件:
declare
     inf utl_file.file_type;
     line_org  varchar2(2000);
     o_vc_return_flag varchar2(2000);
  begin
    inf := utl_file.fopen('TEST','test1.txt', 'A');
     select v into line_org from t1 where v!='aaa';
     utl_file.put_line(inf, line_org);
     utl_file.fclose(inf);
  exception
    when others then
      o_vc_return_flag := 'E' || '_' || sqlcode || '_' || sqlerrm;
      raise_application_error(-20109,o_vc_return_flag);
      return;
  end;
/
utl_file写blob:
CREATE OR REPLACE PROCEDURE GET_PIC_BLOB (i_xh VARCHAR2) IS
l_file UTL_FILE.FILE_TYPE;
l_buffer RAW(32767);
l_amount BINARY_INTEGER := 32767;
l_pos INTEGER := 1;
l_blob BLOB;
l_blob_len INTEGER;

BEGIN
SELECT PIC INTO L_BLOB FROM TB_ZP WHERE PSNNO = i_xh;
l_blob_len := DBMS_LOB.GETLENGTH(l_blob);
l_file := UTL_FILE.FOPEN('BLOBDIR',i_xh || '.jpg','WB',32767);
WHILE l_pos < l_blob_len LOOP
    DBMS_LOB.READ (l_blob, l_amount, l_pos, l_buffer);
    UTL_FILE.PUT_RAW(l_file, l_buffer, TRUE);
    l_pos := l_pos + l_amount;
END LOOP;
UTL_FILE.FCLOSE(l_file);

EXCEPTION

--WHEN NO_DATA_FOUND THEN
  --DBMS_OUTPUT.put_line('no data : ' || i_xh);
WHEN OTHERS THEN
  IF UTL_FILE.IS_OPEN(l_file) THEN
   UTL_FILE.FCLOSE(l_file);
  RAISE;
  END IF;
END GET_PIC_BLOB;

utl_file写clob:
l_buffer RAW(32767);这个地方改为l_buffer varchar2(4000);其他一样

放一个调试好的例子,免得以后费神:
CREATE OR REPLACE PROCEDURE GET_ret_cLOB(ids number) IS
  l_file     UTL_FILE.FILE_TYPE;
  l_buffer   varchar2(4000);
  l_amount   BINARY_INTEGER := 32767;
  l_pos      INTEGER := 1;
  l_clob     CLOB;
  l_blob_len INTEGER;

BEGIN
  SELECT ret_content INTO L_cLOB FROM ret_info WHERE id = ids;
  l_blob_len := DBMS_LOB.GETLENGTH(l_clob);
  l_file     := UTL_FILE.FOPEN('TEST1', ids || '.xml', 'W',32760);
  WHILE l_pos < l_blob_len LOOP
    DBMS_LOB.READ(l_clob, l_amount, l_pos, l_buffer);
    UTL_FILE.PUT(l_file, l_buffer);
    l_pos := l_pos + l_amount;
  END LOOP;
  UTL_FILE.FCLOSE(l_file);

EXCEPTION

  --WHEN NO_DATA_FOUND THEN
  --DBMS_OUTPUT.put_line('no data : ' || i_xh);
  WHEN OTHERS THEN
    IF UTL_FILE.IS_OPEN(l_file) THEN
      UTL_FILE.FCLOSE(l_file);
      RAISE;
    END IF;
END GET_ret_cLOB;

可以使用job调用:
declare
    cursor ids is
        select id from ret_info where rownum <= 50000 ;
begin
    for rec_ids in ids loop       
        get_ret_clob(rec_ids.id);
    end loop;  
end;

open打开模式说明:
open_mode
Specifies how the file is opened. Modes include:

r -- read text

w -- write text

a -- append text

rb -- read byte mode

wb -- write byte mode

ab -- append byte mode