我需要创建将字符串中的字符替换为另一个表中的字符的函数。我正在尝试从一开始返回完全相同的字符串。表t_symbols是:
+-------------------+-------------------------+
| Symbol_to_replace | Symbol_in_return_string |
+-------------------+-------------------------+
| K | Ќ |
| k | ќ |
| X | Ћ |
| x | ћ |
| A | Є |
| a | є |
| H | Њ |
| h | њ |
| O | ¤ |
| o | µ |
| U | ¦ |
| u | ± |
| Y | ‡ |
| y | ‰ |
| I | І |
| i | і |
| G | Ѓ |
| g | ѓ |
+-------------------+-------------------------+
我需要使用游标并从该表中获取字符,而不仅仅是嵌套多个REPLACE
create or replace function f_replace(text in varchar2) return varchar2 is
ResultText varchar2(2000);
begin
for cur in (select t.symbol_to_replace, t.symbol_in_return_string from
t_symbols t) loop
ResultText:= Replace(text, cur.symbol_to_replace,
cur.symbol_in_return_string);
end loop;
return(ResultText);
end f_replace;
答案 0 :(得分:2)
SQL为此具有确切的功能。不是REPLACE
(实际上您需要多次迭代);这是TRANSLATE
函数。
如果表的内容可能会更改,并且您需要编写一个在调用时在表中查找内容的函数,则可以执行类似下面的功能。
我将显示一个完整的示例:首先,我创建一个表,该表将存储所需的替换。我只包括前几个替换项,因为我想展示在修改表时函数的行为如何变化-无需就无需更改任何有关函数的内容。 (这就是重点。)
然后,我显示函数定义,并演示其工作原理。然后,我在替换表中再插入两行,并运行完全相同的查询;现在,结果将根据需要反映出更长的替换“列表”。
create table character_substitutions ( symbol_to_replace, symbol_in_return_string )
as
select 'K', 'Ќ' from dual union all
select 'k', 'ќ' from dual union all
select 'X', 'Ћ' from dual union all
select 'x', 'ћ' from dual union all
select 'A', 'Є' from dual union all
select 'a', 'є' from dual
;
create or replace function my_character_substitutions ( input_str varchar2 )
return varchar2
deterministic
as
symbols_to_replace varchar2(4000);
symbols_to_return varchar2(4000);
begin
select listagg(symbol_to_replace ) within group (order by rownum),
listagg(symbol_in_return_string) within group (order by rownum)
into symbols_to_replace, symbols_to_return
from character_substitutions;
return translate(input_str, symbols_to_replace, symbols_to_return);
end;
/
select 'Kags' as input_str, my_character_substitutions('Kags') as replaced_str
from dual;
INPUT_STR REPLACED_STR
---------- ------------
Kags Ќєgs
好的,现在让我们在表中再插入几行并运行相同的查询。请注意,现在g
也被替换了。
insert into character_substitutions ( symbol_to_replace, symbol_in_return_string )
select 'G', 'Ѓ' from dual union all
select 'g', 'ѓ' from dual
;
select 'Kags' as input_str, my_character_substitutions('Kags') as replaced_str
from dual;
INPUT_STR REPLACED_STR
---------- ------------
Kags Ќєѓs