【oracle】函数-translate

Posted on 2012-07-16 09:33  雅飞士  阅读(1126)  评论(1编辑  收藏  举报

oracle 11gr2 官方介绍地址:

http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions216.htm#SQLRF06145

基本语法:translate(expr,from_string,to_string)

translate 就是一个字符级别的替换:

如下所示:

SQL> select * from v$version;

BANNER

----------------------------------------------------------------

Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi

PL/SQL Release 10.2.0.4.0 - Production

CORE  10.2.0.4.0  Production

TNS for IBM/AIX RISC System/6000: Version 10.2.0.4.0 - Productio

NLSRTL Version 10.2.0.4.0 - Production

SQL> select translate('yafeishi','a','b') from dual;

TRANSLATE('YAFEISHI','A','B')

-----------------------------

ybfeishi

可以看到 yafeishi 中的 a 被替换成了 b.

文档中可以看到这么一句话:

The argumentfrom_string can contain more characters than to_string. In this case, the extra characters at the end offrom_string have no corresponding characters in to_string. If these extra characters appear in expr, then they are removed from the return value.

什么意思呢?在expr 和 from_string 都出现的字符,但在 to_string 没有对应字符,则会在返回的结果中移除。看例子:

SQL> select translate('yafeishi','ya','b') from dual;
TRANSLATE('YAFEISHI','YA','B')
------------------------------
bfeishi

看到 字符 A 被移除。

If a character appears multiple times in from_string, then the to_string mapping corresponding to the first occurrence is used.

如果一个字符在from_string 出现多次,则匹配的时候以to_string 的第一个为准。

SQL> select translate('12345678','232','bcd') from dual;

TRANSLATE('12345678','232','BC

------------------------------

1bc45678

SQL> select translate('12345678','232','dcb') from dual;

TRANSLATE('12345678','232','DC

------------------------------

1dc45678

上面例子中,from_string 中 2 出现2次,但每次都是以在 to_string 中第一次碰到的字符为准。

结合上面2点,可以计算一个字符串中某个字符出现的字数:

SQL> select length(translate('aabbccaa','a'||'aabbccaa','a')) from dual;

LENGTH(TRANSLATE('AABBCCAA','A

------------------------------

                             4

这点来源的半瓶一篇文章: 传送

Copyright © 2024 雅飞士
Powered by .NET 9.0 on Kubernetes