Warm tip: This article is reproduced from stackoverflow.com, please click
encoding oracle sql

encoding and decoding in oracle select statement

发布于 2020-04-18 09:40:39

Is there a way i can encode a string from a select statement in oracle.

i.e.

SELECT base64encode('mystring') FROM dual; --this doesn't work

base64 or any other encoding mechanism is welcomed. one that can be decoded

Questioner
Omari Victor Omosa
Viewed
62
mathguy 2020-02-04 22:29

Oracle has the UTL_ENCODE package, including the BASE64_ENCODE and BASE64_DECODE functions. Both functions work on RAW data type (both the input and the return value are RAW); so, if you want to use this for character data types, like VARCHAR2 or perhaps CLOB, you need to use additional conversions - as found in the UTL_RAW package; functions like CAST_TO_RAW and CAST_TO_VARCHAR2.

Here is a brief example. I start with the string 'mathguy' (in VARCHAR2 data type); first I convert it to RAW, and then I encode it to base64. Then, to demonstrate the decoding step, I apply the BASE64_DECODE function to the output from the first query, and convert the resulting RAW value back to VARCHAR2; the result of the second query should be the input of the first. Let's see:

select utl_encode.base64_encode(utl_raw.cast_to_raw('mathguy')) as encoded
from   dual;

/* ENCODING */

ENCODED
------------------------
625746306147643165513D3D


/* DECODING */

select utl_raw.cast_to_varchar2(
         utl_encode.base64_decode('625746306147643165513D3D')) as decoded
from   dual;

DECODED
-----------
mathguy

Edit Please see Wernfried Domscheit's Comment below: the RAW data type is limited to 2000 bytes, or 32767 bytes with extended max string size. So this may not work as shown here for very long input strings.