如果我想将一些字符更改为空,翻译函数会做什么?
what will translate function do if I want to change some chars to nothing?
我有一个sql声明:
select translate('abcdefg', 'abc', '') from dual;
为什么结果什么都没有?
我觉得应该是'defg'.
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.
所以你可以这样做:
select translate('abcdefg', '#abc', '#') from dual;
TRANSLATE('ABCDEFG','#ABC','#')
-------------------------------
defg
...使用任何不会出现在您的 from_string
中的字符。
select translate('abcdefg', 'abc', '') from dual;
要添加到 Alex 的答案中,您可以使用任何字符(在 SQL 中允许)来连接以删除所有字符。因此,您甚至可以使用 space
而不是 empty string
。 Oracle 中的空字符串被视为 NULL
值。
所以,你也可以这样做 -
SQL> SELECT TRANSLATE('abcdefg', ' abc', ' ') FROM dual;
TRAN
----
defg
SQL>
与-
相同
SQL> SELECT TRANSLATE('abcdefg', chr(32)||'abc', chr(32)) FROM dual;
TRAN
----
defg
SQL>
因为 space 的 ascii
值为 32。
这只是一个演示,为了更好的理解和代码可读性,最好使用 space 以外的任何其他字符。
我有一个sql声明:
select translate('abcdefg', 'abc', '') from dual;
为什么结果什么都没有? 我觉得应该是'defg'.
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.
所以你可以这样做:
select translate('abcdefg', '#abc', '#') from dual;
TRANSLATE('ABCDEFG','#ABC','#')
-------------------------------
defg
...使用任何不会出现在您的 from_string
中的字符。
select translate('abcdefg', 'abc', '') from dual;
要添加到 Alex 的答案中,您可以使用任何字符(在 SQL 中允许)来连接以删除所有字符。因此,您甚至可以使用 space
而不是 empty string
。 Oracle 中的空字符串被视为 NULL
值。
所以,你也可以这样做 -
SQL> SELECT TRANSLATE('abcdefg', ' abc', ' ') FROM dual;
TRAN
----
defg
SQL>
与-
相同SQL> SELECT TRANSLATE('abcdefg', chr(32)||'abc', chr(32)) FROM dual;
TRAN
----
defg
SQL>
因为 space 的 ascii
值为 32。
这只是一个演示,为了更好的理解和代码可读性,最好使用 space 以外的任何其他字符。