ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# 9.5\. 二进制字符串函数和操作符 本节描述那些检查和操作类型为`bytea`数值的函数和操作符。 SQL定义了一些字符串函数, 在这些函数里使用关键字而不是逗号来分隔参数。 详情请见[Table 9-8](#calibre_link-2190)。 PostgreSQL也提供了使用常用语法进行函数调用的函数的版本 (参阅[Table 9-9](#calibre_link-1072))。 > **Note:** 本页面例子的结果在假设服务器的参数[`bytea_output`](#calibre_link-1042) 设置为`escape`的基础上的(传统的PostgreSQL格式)。 **Table 9-8\. SQL 二进制字符串函数和操作符** | 函数 | 返回类型 | 描述 | 例子 | 结果 | | --- | --- | --- | --- | --- | | `string` `||` `string` | `bytea` | 字符串连接 | `E'\\\\Post'::bytea || E'\\047gres\\000'::bytea` | `\\Post'gres\000` | | ``octet_length(```string`) | `int` | 二进制字符串中的字节数 | `octet_length(E'jo\\000se'::bytea)` | `5` | | ``overlay(```string` placing `string` from `int` [for `int`]) | `bytea` | 替换子串 | `overlay(E'Th\\000omas'::bytea placing E'\\002\\003'::bytea from 2 for 3)` | `T\\002\\003mas` | | ``position(```substring` in `string`) | `int` | 特定子字符串的位置 | `position(E'\\000om'::bytea in E'Th\\000omas'::bytea)` | `3` | | ``substring(```string` [from `int`] [for `int`]) | `bytea` | 截取子串 | `substring(E'Th\\000omas'::bytea from 2 for 3)` | `h\000o` | | ``trim([both]` ``bytes` from `string`) | `bytea` | 从`string`的开头和结尾删除只包含 `bytes`中字节的最长字符串 | `trim(E'\\000'::bytea from E'\\000Tom\\000'::bytea)` | `Tom` | 还有一些二进制字符串处理函数可以使用,在[Table 9-9](#calibre_link-1072) 列出。其中有一些是在内部使用,用于实现[Table 9-8](#calibre_link-2190) 列出的SQL标准的字符串函数。 **Table 9-9\. 其它二进制字符串函数** | 函数 | 返回类型 | 描述 | 例子 | 结果 | | --- | --- | --- | --- | --- | | ``btrim(```string` `bytea`, `bytes` `bytea`) | `bytea` | 从`string`的开头和结尾删除只包含`bytes` 中字节的最长的字符串 | `btrim(E'\\000trim\\000'::bytea, E'\\000'::bytea)` | `trim` | | ``decode(```string` `text`, `format` `text`) | `bytea` | 把`string`中的文本表示解码为二进制数据。`format` 的选项和`encode`相同。 | `decode(E'123\\000456', 'escape')` | `123\000456` | | ``encode(```data` `bytea`, `format` `text`) | `text` | 把二进制数据编码为文本表现形式。支持的格式:`base64`, `hex`, `escape`。`escape` 转换零字节和高位设置字节为八进制序列(`\``_nnn_`) 和双写反斜杠。 | `encode(E'123\\000456'::bytea, 'escape')` | `123\000456` | | ``get_bit(```string`, `offset`) | `int` | 从字符串中抽取位 | `get_bit(E'Th\\000omas'::bytea, 45)` | `1` | | ``get_byte(```string`, `offset`) | `int` | 从字符串中抽取字节 | `get_byte(E'Th\\000omas'::bytea, 4)` | `109` | | ``length(```string`) | `int` | 二进制字符串的长度 | `length(E'jo\\000se'::bytea)` | `5` | | ``md5(```string`) | `text` | 计算`string`的MD5散列值,以十六进制方式返回结果。 | `md5(E'Th\\000omas'::bytea)` | `8ab2d3c9689aaf18 b4958c334c82d8b1` | | ``set_bit(```string`, `offset`, `newvalue`) | `bytea` | 设置字符串中的位 | `set_bit(E'Th\\000omas'::bytea, 45, 0)` | `Th\000omAs` | | ``set_byte(```string`, `offset`, `newvalue`) | `bytea` | 设置字符串中的字节 | `set_byte(E'Th\\000omas'::bytea, 4, 64)` | `Th\000o@as` | `get_byte`和`set_byte`数以二进制字符串的第一个字节为0字节。 `get_bit`和`set_bit`从每个字节的右边取位; 例如位0是第一个字节的最低位,位15是第二个字节的最高位。 又见[Section 9.20](#calibre_link-1641)中的聚集函数`string_agg`。