Oracle的字符替换函数translate用法

参考文档如下:http://www.banping.com/2009/05/18/oracle_function_translate/

Oracle提供了一个字符替换函数translate,不同于replace函数的是,translate函数是字符级别的替换,而不是字符串的替换。

其语法如下:

TRANSLATE ( expr , from_string , to_string )

简单的说就是对expr内容,用to_string中的字符逐一替换from_string 中的字符,举例说明如下:

SQL> select translate('123456789','456','abc') from dual;

TRANSLATE
———
123abc789

SQL> select translate('123456789','456','ab') from dual;

TRANSLAT
——–
123ab789

SQL> select translate('123456789','4564','a') from dual;

TRANSLAT
——-
123a789

SQL> select translate('123456789','4564','abcd') from dual;

TRANSLATE
———
123abc789

SQL>select translate('158975751','15','ab') from dual

TRANSLATE
———
ab897b7ba

从第五个例子(最后一个)可以看出,translate函数是以字符为单位逐一替换的,从第二、三个例子可以看出,如果第三个参数to_string的长度小于第二个参数from_string,那么from_string的后边超出的部分都被替换为空值。从第三、四个例子可见,如果某一个字符多次出现,则以第一次替换的内容为准。

以此可以实现的一个有用的功能是统计一个字符串中某个字符出现的次数:

select length(translate('expl','x'||'expl','x')) from dual

官方文档10g Release 2 (10.2) B14200-02 提供了一个例子如下:

Examples

The following statement translates a book title into a string that could be used (for example) as a filename. The from_string contains four characters: a space, asterisk, slash, and apostrophe (with an extra apostrophe as the escape character). The to_string contains only three underscores. This leaves the fourth character in the from_string without a corresponding replacement, so apostrophes are dropped from the returned value.

SELECT TRANSLATE('SQL*Plus User”s Guide', ' */"', '___') FROM DUAL;
——————–
SQL_Plus_Users_Guide

原文地址:https://www.cnblogs.com/hqbhonker/p/3457300.html