8i | 9i | 10g | 11g | 12c | 13c | 18c | 19c | 21c | 23c | Misc | PL/SQL | SQL | RAC | WebLogic | Linux

Home » Articles » 8i » Here

Export CLOB

Related articles.

The following article presents a simple method for exporting the contents of a CLOB datatype to the filesystem. First a directory object is created to point to the relevant filesystem directory.

create or replace directory documents as 'C:\';

Then we read the contents of the CLOB and write them to a file.

set serveroutput on
declare
  l_file    utl_file.file_type;
  l_clob    clob;
  l_buffer  varchar2(32767);
  l_amount  binary_integer := 32767;
  l_pos     integer := 1;
begin
  select col1
  into   l_clob
  from   tab1
  where  rownum = 1;

  l_file := utl_file.fopen('DOCUMENTS_DIR', 'Sample2.txt', 'w', 32767);

  loop
    dbms_lob.read (l_clob, l_amount, l_pos, l_buffer);
    utl_file.put(l_file, l_buffer);
    utl_file.fflush(l_file);
    l_pos := l_pos + l_amount;
  end loop;
exception
  when no_data_found then
    -- Expected end.
    if utl_file.is_open(l_file) then
      utl_file.fclose(l_file);
    end if;
  when others then
    if utl_file.is_open(l_file) then
      utl_file.fclose(l_file);
    end if;
    raise;
end;
/

The process will always finish with a NO_DATA_FOUND exception when the end of the CLOB is reached. For simplicity I've not trapped any of the other possible UTL_FILE exceptions.

In reality you would probably put this code into a stored procedure, or packaged procedure. This example is available here.

create or replace procedure clob_to_file (p_clob      in  clob,
                                          p_dir       in  varchar2,
                                          p_filename  in  varchar2)
as
  l_file    utl_file.file_type;
  l_buffer  varchar2(32767);
  l_amount  binary_integer := 32767;
  l_pos     integer := 1;
begin
  l_file := utl_file.fopen(p_dir, p_filename, 'w', 32767);

  loop
    dbms_lob.read (p_clob, l_amount, l_pos, l_buffer);
    utl_file.put(l_file, l_buffer);
    utl_file.fflush(l_file);
    l_pos := l_pos + l_amount;
  end loop;
exception
  when no_data_found then
    -- expected end.
    if utl_file.is_open(l_file) then
      utl_file.fclose(l_file);
    end if;
  when others then
    if utl_file.is_open(l_file) then
      utl_file.fclose(l_file);
    end if;
    raise;
end clob_to_file;
/

You might call this like the following.

declare
  l_clob  clob;
begin
  -- get lob locator
  select col1
  into   l_clob
  from   tab1
  where  rownum = 1;

  clob_to_file(p_clob     => l_clob,
               p_dir      => 'DOCUMENTS_DIR',
               p_filename => 'Sample2.txt');
end;
/

For more information see:

Hope this helps. Regards Tim...

Back to the Top.