函数:translate

xixuefeng SQL&Function 2014-04-10 9:32:09 1,661 次浏览 函数:translate已关闭评论

1:语法
TRANSLATE(expr, from_string, to_string)
2:功能
expr中的字符串进行替换,替换的规则是:from_string与to_string一一对应进行替换,如果没有对应上,那么将expr中的相应字符将删除。
文字描述不好理解,我们直接上例子。
3、例题
将字符串’123a1b2c3456’中所有的数字删除,保留英文字符,即处理后的字符串应为’abc’


4、解释例题

按照 translate函数中from_string与to_string一一对应进行替换规则,我们可以这样理解
(注:”=>”表示替换)
x=>x,
0=>null(也可以理解为将字符串中所有出现的0删除)
1=>null
2=>null
3=>null
4=>null
5=>null
6=>null
7=>null
8=>null
9=>null
这一串替换下来,把字符串’123a1b2c3456’中的所有数字就都删除了,以达到去除字符串中数字的效果。

5、疑问
疑问出现了,今天一个朋友问我,from_string和to_string参数中的x略显多余,直接把x去掉,改为(‘123a1b2c3456′,’0123456789’,”)不就可以了吗?

我印象中这样一定是不行的,具体是为什么,我忘记了,测试了一下,确实应验了,返回的是null,那么究其原因何在呢?

只能去官方文档中一查究竟,看看有没有相关的介绍,果然有,官方解释如下:
“You cannot use an empty string for to_string to remove all characters in from_string from the return value. Oracle Database interprets the empty string as null, and if this function has a null argument, then it returns null. To remove all characters in from_string, concatenate another character to the beginning of from_string and specify this character as the to_string. For example, TRANSLATE(expr, ‘x0123456789’, ‘x’) removes all digits from expr.”

6、小结
也就是说to_string这个参数是不被允许的,如果为空的话,那么这个函数就直接返回null。

回顶部