Tried to come up with a solution which will match your exact requirement: Given a table with special character and corresponding normal character mapping we need to write a PL/SQL to get the mappings done.
- Create table with mappings
create table replace_char_tab(special_ascii number, special_char nvarchar2(1),
replace_ascii number, replace_char varchar2(1));
insert into replace_char_tab values(49833,'©', null, null);
insert into replace_char_tab values(50058,'Ê', 69, 'E');
insert into replace_char_tab values(50064,'Ð', 68, 'D');
insert into replace_char_tab values(50070,'Ö', 79, 'O');
insert into replace_char_tab values(50069,'Õ', 79, 'O');
commit;
In the above statements we have bigger values for special_ascii, because Oracle's ascii supports 0-127 characters natively. For a higher range the unicode value is returned based on the character encoding of the database.
- Create a PL/SQL
create or replace function getSpecialCharMapping(input_string varchar2)
return varchar2
as
TYPE key_pair_type IS TABLE OF number INDEX BY pls_integer;
special_rep key_pair_type;
output_string varchar2(4000);
r_char nvarchar2(1);
begin
-- Generate associative array
for rec in (select * from replace_char_tab) loop
if rec.replace_ascii is not null then
special_rep(rec.special_ascii) := rec.replace_ascii;
else
special_rep(rec.special_ascii) := 0;
end if;
end loop;
-- Now find map the special chars with ascii
for cnt in 1..length(input_string) loop
if special_rep.exists(ascii(substr(input_string, cnt, 1))) then
output_string := output_string
|| chr(special_rep(ascii(substr(input_string,cnt,1))));
else
output_string := output_string || substr(input_string,cnt,1);
end if;
end loop;
return output_string;
end;
/
In the above PL/SQL we have used associative array feature of PL/SQL. Which essentially is a key/value pair and helps in fast lookup. By using associative array we are trying to avoid querying table for each character mapping.
- Sample execution
select getSpecialCharMapping('HÊLLÕ WÖRLЩ !!') from dual;
The motive of this solution is to make special character mapping scalable and easy to understand.
Link to SQLFiddle.