Dumping CLOB fields into files?

↘锁芯ラ 提交于 2019-12-03 17:10:52
LukStorms

This pl/sql code should work in oracle 11g. It dumps the text of the clobs into a directory with the title as filename.

begin 
  for rec in (select title, text from mytable)
  loop DBMS_XSLPROCESSOR.clob2file(rec.text, 'DUMP_SOURCES', rec.title ||'.txt'); end loop;
end;

If DBMS_XSLPROCESSOR isn't available then you could replace DBMS_XSLPROCESSOR.clob2file with a procedure that uses UTL_FILE. For example :

CREATE OR REPLACE PROCEDURE CLOB2FILE (
    clob_in IN CLOB,
    directory_name IN VARCHAR2,
    file_name IN VARCHAR2
)
IS
    file_handle UTL_FILE.FILE_TYPE;
    clob_part VARCHAR2(1024);
    clob_length NUMBER;
    offset NUMBER := 1;
BEGIN
    clob_length := LENGTH(clob_in);
    file_handle := UTL_FILE.FOPEN(directory_name, file_name, 'W');

    LOOP
        EXIT WHEN offset >= clob_length;
        clob_part := DBMS_LOB.SUBSTR (clob_in, 1024, offset);
        UTL_FILE.PUT(file_handle, clob_part);
        offset := offset + 1024;
    END LOOP;

    UTL_FILE.FFLUSH(file_handle);
    UTL_FILE.FCLOSE(file_handle);

EXCEPTION
    WHEN OTHERS THEN
        UTL_FILE.FCLOSE(file_handle);
        RAISE;

END;

Or perhaps replace DBMS_XSLPROCESSOR.clob2file with dbms_advisor.create_file.

Justin Cave

Are you trying to generate files on the database server file system? Or on the client file system?

If you are trying to generate files on the database server file system, there is an example of exporting a CLOB to a file in another StackOverflow thread that is based on Tim Hall's LOB export examples (Tim's site appears to be down at the moment).

If you're trying to generate files on the client file system, it would involve much more complex SQLPlus scripting. You'd be looking at doing something like querying the table and using the data to dynamically generate one SQLPlus script per file that you wanted to generate and then dynamically calling those scripts. You'd be really pushing SQL*Plus's scripting capabilities so that's not an architecture that I would generally advocate but I believe it could be done.

If you do need to generate files on the client file system, I'd generally prefer to use something other than SQLPlus. For example, there is an example of a small Java class that reads and writes CLOB and BLOB data to and from files on the AskTom site. I'd tend to write a small Java utility that ran on the client and exported the data rather than trying to put too much logic in SQLPlus scripts.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!