TRANSLATE
更新时间:2025-10-17
描述
TRANSLATE 函数用于字符串替换,将源字符串中的字符按照映射规则进行转换。它会将源字符串中出现在 from 字符串中的字符替换为 to 字符串中对应位置的字符。
语法
SQL
1TRANSLATE(<source>, <from>, <to>)
参数
参数 | 说明 |
---|---|
<source> |
需要进行转换的源字符串。类型:VARCHAR |
<from> |
要被替换的字符集合。类型:VARCHAR |
<to> |
替换后的字符集合。类型:VARCHAR |
返回值
返回 VARCHAR 类型,表示替换后的字符串。
特殊情况:
- 如果任意参数为 NULL,返回 NULL
- 如果 from 字符串中有重复字符,只使用第一次出现的位置
- 如果源字符不在 from 字符串中,该字符将保持不变
- 如果 from 字符串中字符的位置超出了 to 字符串的长度,对应的源字符将被删除
- 如果 from 和 to 都为空字符串,返回原字符串
示例
- 基本字符替换
SQL
1SELECT translate('abcd', 'a', 'z');
Text
1+-----------------------------+
2| translate('abcd', 'a', 'z') |
3+-----------------------------+
4| zbcd |
5+-----------------------------+
- 多次替换相同字符
SQL
1SELECT translate('abcda', 'a', 'z');
Text
1+------------------------------+
2| translate('abcda', 'a', 'z') |
3+------------------------------+
4| zbcdz |
5+------------------------------+
- 特殊字符替换
SQL
1SELECT translate('Palhoça', 'ç', 'c');
Text
1+--------------------------------+
2| translate('Palhoça', 'ç', 'c') |
3+--------------------------------+
4| Palhoca |
5+--------------------------------+
- 字符删除(to 字符串为空)
SQL
1SELECT translate('abcd', 'a', '');
Text
1+----------------------------+
2| translate('abcd', 'a', '') |
3+----------------------------+
4| bcd |
5+----------------------------+
- from 字符串中的重复字符
SQL
1SELECT translate('abcd', 'aac', 'zq');
Text
1+--------------------------------+
2| translate('abcd', 'aac', 'zq') |
3+--------------------------------+
4| zbd |
5+--------------------------------+