Work with BLOB object in Oracle

2019-08-07 03:32发布

问题:

I have an SQL statement like this-

select utl_encode.utl_encode.base64_encode(IMAGE1) 
from IPHONE.accidentreports 
where "key" = 66

But when I run it I get this error-

ORA-00904: "UTL_ENCODE"."UTL_ENCODE"."BASE64_ENCODE": invalid identifier
00904. 00000 -  "%s: invalid identifier"
*Cause:    
*Action:
Error at Line: 2 Column: 8

I want to convert my BLOB object into BASE64. How could it be done?

回答1:

Since the UTL_ENCODE.BASE64_ENCODE function works on RAWs, it will work with BLOBs up to 32767 bytes in PL/SQL or 4000 bytes in SQL.

If your images are larger, you'll have to write your own function. Here's an example:

CREATE OR REPLACE FUNCTION base64_encode_blob (p BLOB) RETURN BLOB IS
   l_raw    RAW(24573);
   l_base64 RAW(32767);
   l_result BLOB;
   l_offset NUMBER := 1;
   l_amount NUMBER := 24573;
BEGIN
   DBMS_LOB.createtemporary(l_result, FALSE);
   DBMS_LOB.open(l_result, DBMS_LOB.lob_readwrite);
   LOOP
      DBMS_LOB.read(p, l_amount, l_offset, l_raw);
      l_offset := l_offset + l_amount;
      l_base64 := utl_encode.base64_encode(l_raw);
      DBMS_LOB.writeappend(l_result, utl_raw.length(l_base64), l_base64);
   END LOOP;
EXCEPTION
   WHEN NO_DATA_FOUND THEN
      RETURN l_result;
END;
/


回答2:

First of all UTL_ENCODE.BASE64_ENCODE works on binary representation of a RAW value and the function looks like:

UTL_ENCODE.BASE64_ENCODE (
   r  IN RAW) 
RETURN RAW;

So, considering IMAGE1 is of RAW type:

SELECT UTL_ENCODE.BASE64_ENCODE(CAST(IMAGE1 AS RAW))  --if IMAGE1 is LOB
  FROM IPHONE.accidentreports 
 WHERE "key" = 66;

More on CASTing here.