PostgreSQL 教程: replace 字符串替换函数 |
您所在的位置:网站首页 › pc851替换 › PostgreSQL 教程: replace 字符串替换函数 |
摘要:在本教程中,我们将向您介绍 PostgreSQL 的字符串替换函数,这些函数在字符串中搜索子字符串并将其替换为新的子字符串。 目录 PostgreSQL REPLACE 函数简介有时,您想要搜索列中的字符串并将其替换为新字符串,例如替换过时的电话号码、损坏的 URL 和拼写错误。 要搜索所有出现的字符串并将其替换为新字符串,请使用REPLACE()函数。 下面说明了 PostgreSQL 的REPLACE()函数的语法: REPLACE(source, old_text, new_text );REPLACE()函数接受三个参数: source是您要替换的字符串。 old_text是您要搜索和替换的文本。如果old_text在字符串中多次出现,则所有出现的位置都将被替换。 new_text是将替换旧文本 (old_text) 的新文本。 PostgreSQL REPLACE 函数示例让我们来探索一些使用REPLACE()函数的示例。 1) 基本 REPLACE 函数示例请查看以下使用REPLACE()函数的示例: SELECT REPLACE ('ABC AA', 'A', 'Z');输出: replace --------- ZBC ZZ (1 row)在此示例中,我们将字符串中的所有字符 ‘A’ 替换为字符 ‘Z’。 以下示例将 URL 中的子字符串tt替换为xx: SELECT REPLACE ( 'https://www.rockdata.net', 'tt', 'xx' );输出: replace -------------------------- hxxps://www.rockdata.net (1 row) 2) 将 PostgreSQL REPLACE 函数用于表数据如果要搜索并替换表列中的子字符串,请使用以下语法: UPDATE table_name SET column_name = REPLACE(column, old_text, new_text) WHERE condition我们使用示例数据库中的customer表进行演示: SELECT first_name, last_name, email FROM customer;输出: first_name | last_name | email -------------+--------------+------------------------------------------ Jared | Ely | [email protected] Mary | Smith | [email protected] Patricia | Johnson | [email protected] Linda | Williams | [email protected] Barbara | Jones | [email protected] Elizabeth | Brown | [email protected] Jennifer | Davis | [email protected] Maria | Miller | [email protected] Susan | Wilson | [email protected] ...现在,假设您要更新电子邮件列以将域名sakilacustomer.org替换为rockdata.net,请使用以下语句: UPDATE customer SET email = REPLACE ( email, 'sakilacustomer.org', 'rockdata.net' );因为我们省略了 WHERE 子句,所以customer表中的所有行都被更新。 让我们验证一下是否已进行替换。 SELECT first_name, last_name, email FROM customer;输出: first_name | last_name | email -------------+--------------+------------------------------------ Jared | Ely | [email protected] Mary | Smith | [email protected] Patricia | Johnson | [email protected] Linda | Williams | [email protected] Barbara | Jones | [email protected] Elizabeth | Brown | [email protected] Jennifer | Davis | [email protected] Maria | Miller | [email protected] Susan | Wilson | [email protected] ...在本教程中,我们向您展示了REPLACE()字符串替换函数,搜索子字符串并将其替换为新子字符串。 了解更多PostgreSQL 教程:字符串函数 PostgreSQL 文档:字符串函数和操作符 regexp_replace(), translate() |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |