Oracle提供了一個字符替換函數translate,不同於replace函數的是,translate函數是字符級別的替換,而不是字符串的替換。
其語法如下:
TRANSLATE ( expr , from_string , to_string )
簡單的說就是對expr內容,用to_string中的字符逐一替換from_string 中的字符,舉例說明如下:
SQL> select translate('123456789','456','abc') from dual;
TRANSLATE
---------
123abc789SQL> select translate('123456789','456','ab') from dual;
TRANSLAT
--------
123ab789SQL> select translate('123456789','4564','a') from dual;
TRANSLAT
-------
123a789SQL> select translate('123456789','4564','abcd') from dual;
TRANSLATE
---------
123abc789
可以看到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