BLOB/CLOB 2 File

 

Per salvare il contenuto di un file binario su una cartella del server Oracle occorre che la corrispondente DIRECTORY logica sia stata creata:

CREATE OR REPLACE DIRECTORY DUMP_DIR AS '<dir>';
GRANT READ, WRITE ON DIRECTORY DUMP_DIR TO <user>;


Sulle macchine con sistema operativo UNIX bisogna anche assicurarsi che l’utente del database (di solito oracle) abbia i diritti in lettura/scrittura sul folder fisico <dir>.

Un esempio di procedura di salvataggio su disco è:

CREATE OR REPLACE PROCEDURE Blob_To_File(i_blob BLOB, i_directory VARCHAR2, i_filename VARCHAR2)
IS
  v_start NUMBER := 1;
v_bytelen NUMBER := 32000;
v_len NUMBER;
v_buffer RAW(32000);
x NUMBER;
v_output UTL_FILE.FILE_TYPE;
BEGIN
-- Define output directory
v_output := UTL_FILE.fopen(i_directory, i_filename, 'WB', 32760);
-- Get length of blob
v_len := DBMS_LOB.getlength(i_blob);
-- Save blob length
x := v_len;
-- If small enough for a single write
IF v_len < 32760 THEN
  UTL_FILE.put_raw(v_output, i_blob);
UTL_FILE.fflush(v_output);
ELSE
-- Write in pieces
v_start := 1;
WHILE v_start < v_len
LOOP
  DBMS_LOB.read(i_blob, v_bytelen, v_start, v_buffer);
UTL_FILE.put_raw(v_output, v_buffer);
UTL_FILE.fflush(v_output);
-- Set the start position for the next cut
v_start := v_start + v_bytelen;
-- Set the end position if less than 32000 bytes
x := x - v_bytelen;
IF x < 32000 THEN
v_bytelen := x;
END IF;
END LOOP;
END IF;
UTL_FILE.fclose(v_output);
EXCEPTION
WHEN OTHERS THEN
UTL_FILE.fclose_all;
RAISE;
END;

Per salvare un CLOB su file è sufficiente invocare una conversione BLOB 2 CLOB, come indicato in un post precedente:

EXEC Blob_To_File(Clob_To_Blob('Big text example...'), 'DUMP_DIR', 'clob.txt');

 

Lascia un commento