Tuesday, August 19, 2008

Oracle: How to convert CLOB to BLOB


CREATE OR REPLACE Procedure Convert_Clob_To_Blob( clobvalue in clob , blobValue in out blob)
as
Position pls_integer := 1;
Temp_Buffer raw(32767);
Length_To_Copy int ;
clob_Length pls_integer := dbms_lob.getLength(clobValue);

begin

dbms_lob.open(BlobValue,dbms_lob.lob_readwrite);

--Length_To_Copy := least(1000,(clob_Length - Position) + 1);

While (Position <= clob_Length ) loop

Length_To_Copy := least(1000,(clob_Length - Position) + 1);

Temp_Buffer := utl_raw.cast_to_raw(dbms_lob.substr(clobValue,Length_To_Copy,Position));
If utl_raw.length(Temp_Buffer) > 0 then
dbms_lob.writeappend(BlobValue,utl_raw.length(Temp_Buffer),Temp_Buffer);
end if;

Position := Position + Length_To_Copy;

--Length_To_Copy := least(1000,(clob_Length - Position) + 1);


end loop;

dbms_lob.close(BlobValue);




end;
/

In order to test the above code look at this example.Lets assume you have a table called TABLE_NAME with a clob column called CLOB_COLUMN

Declare
b blob;
Begin
For cTemp in ( Select clob_column from table_name ) loop
Begin
b := null;

Insert into TABLE_NAME2(BLOB_COLUMN) values (empty_blob())
returning BLOB_COLUMN into b;
Convert_Clob_To_Blob (cTemp.clob_column,b);
end;
end loop;
Commit;
end;
/

No comments:

Post a Comment