to_ascii() 是一个系统函数,用于将字符串从一小部分其他编码转换为 ASCII。
to_ascii() 添加于 PostgreSQL 7.1。
用法
to_ascii(stringTEXT)
to_ascii(stringTEXT,encodingNAME)
to_ascii(stringTEXT,encodingINTEGER)
实际上,第一种形式(默认使用当前数据库编码)是唯一实用的变体。
支持从以下编码进行转换
| 编码 | 编号 |
|---|---|
LATIN1 |
8 |
LATIN2 |
9 |
LATIN9 |
16 |
WIN1250 |
29 |
PostgreSQL 文档并未指定前表中列出的编码编号;这些对应于 pg_enc 枚举中的匹配值,该枚举定义于 src/include/mb/pg_wchar.h。
contrib 模块 unaccent 提供了更灵活的选项范围来实现相同的目标。
变更历史
- PostgreSQL 8.0
- 添加对
LATIN9编码的支持(提交 75b61043)
- 添加对
- PostgreSQL 7.1
- 添加(提交 dffd8cac)
示例
基本用法
asciitest=# SELECT to_ascii('überbewertete äthiopische Ödnis');
to_ascii
---------------------------------
uberbewertete athiopische Odnis
(1 row)
分别使用编码名称和编号得到相同的结果
asciitest=# SELECT to_ascii('überbewertete äthiopische Ödnis', 'LATIN1');
to_ascii
---------------------------------
uberbewertete athiopische Odnis
(1 row)
asciitest=# SELECT to_ascii('überbewertete äthiopische Ödnis', 8);
to_ascii
---------------------------------
uberbewertete athiopische Odnis
(1 row)
尝试从不支持或无效的编码进行转换
asciitest=# SELECT to_ascii('ü', 'EUC_JP');
ERROR: encoding conversion from EUC_JP to ASCII not supported
asciitest=# SELECT to_ascii('ü', 19);
ERROR: encoding conversion from WIN1258 to ASCII not supported
asciitest=# SELECT to_ascii('ü', 99);
ERROR: 99 is not a valid encoding code
to_ascii() 在数据库不属于支持的编码之一时会产生乱码输出
postgres=# \l postgres
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
----------+----------+----------+-------------+-------------+-------------------
postgres | postgres | UTF8 | de_DE.UTF-8 | de_DE.UTF-8 |
(1 row)
postgres=# SELECT to_ascii('äü');
to_ascii
----------
A A
(1 row)
参考资料
- PostgreSQL 文档: 其他字符串函数
