sql replace函数_SQL REPLACE函数概述

sql replace函数

In this article, I’ll show you how to find and replace data within strings. I will demonstrate how to use the function SQL REPLACE, where you look for a substring within a string, and then replace it.

在本文中,我将向您展示如何在字符串中查找和替换数据。 我将演示如何使用SQL REPLACE函数,在该函数中您将在字符串中查找子字符串,然后将其替换。

This article answers the following commonly asked questions:

本文回答以下常见问题:

  1. What does the SQL replace function do in SQL Server?

    SQL替换功能在SQL Server中有什么作用?
  2. How to use Collate function with REPLACE in SQL Server?

    如何在SQL Server中将整理功能与REPLACE一起使用?
  3. How to replace multiple characters in SQL?

    如何替换SQL中的多个字符?
  4. How to perform an update using the REPLACE in SQL Server?

    如何在SQL Server中使用REPLACE执行更新?
  5. How to prepare T-SQL code to perform a REPLACE?

    如何准备T-SQL代码以执行替换?

A few other string functions are discussed in the articles SQL Substring function overview and SQL string functions for Data Munging (Wrangling).

SQL子字符串函数概述Data Munging(Wrangling)SQL字符串函数一文中讨论了其他一些字符串函数。

Syntax

句法

REPLACE (Expression, pattern, replacement)

替换(表达,图案,替换)

Expression: The input string value on which the replace function has to operate.

表达式:替换功能必须在其上操作的输入字符串值。

Pattern: The substring to evaluate and provides a reference position to the replacement field.

模式:要评估的子字符串,并为替换字段提供参考位置。

REPLACEment: REPLACEs the specified string or character value of the given expression.

REPLACEment:替换给定表达式的指定字符串或字符值。

Note: The SQL REPLACE function performs comparisons based on the collation of the input expression.

注意:SQL REPLACE函数根据输入表达式的排序规则执行比较。

Examples

例子

How to use perform a simple REPLACE

如何使用执行简单的替换

The following SQL uses the REPLACE keyword to find matching pattern string and replace with another string.

以下SQL使用REPLACE关键字查找匹配的模式字符串,并替换为另一个字符串。

SELECT REPLACE('SQL Server vNext','vNext','2017') SQL2017;

Here is the result set.

这是结果集。

GO

将整理功能与REPLACE一起使用 (Using the Collate function with REPLACE)

The following SQL uses the case-sensitive collation function to validate the expression within the SQL REPLACE function

以下SQL使用区分大小写的排序规则函数来验证SQL REPLACE函数中的表达式

SELECT REPLACE('SQL Server vNext' COLLATE Latin1_General_CS_AS,'vnext','2017') SQL2017;

The output is a direct input of the expression as it fails to validate the input pattern.

输出是表达式的直接输入,因为它无法验证输入模式。

The following SQL uses the same example but case-insensitive collation function is used to validate the expression within the function

以下SQL使用相同的示例,但不区分大小写的排序规则函数用于验证函数中的表达式

SELECT REPLACE('SQL Server vNext' COLLATE Latin1_General_CI_AS,'vnext','2017') SQL2017;

The output shows the values are matched irrespective of cases

输出显示值匹配,无论情况如何

如何替换给定字符串中的多个模式 (How to replace multiple patterns in a given string)

The following example uses the SQL replace function to replace multiple patterns of the expression 3*[4+5]/{6-8}.

以下示例使用SQL replace函数替换表达式3 * [4 + 5] / {6-8}的多个模式。

SELECT REPLACE(REPLACE(REPLACE(REPLACE('3*[4+5]/{6-8}', '[', '('), ']', ')'), '{', '('), '}', ')');

We can see that the REPLACE function is nested and it is called multiple times to replace the corresponding string as per the defined positional values within the SQL REPLACE function.

我们可以看到REPLACE函数是嵌套的,并且根据SQL REPLACE函数中定义的位置值多次调用它来替换相应的字符串。

In the aforementioned example, we can use the TRANSLATE, a new SQL Server 2017 function. It’s a good replacement string function for the SQL REPLACE function.

在上述示例中,我们可以使用TRANSLATE,这是一个新SQL Server 2017函数。 它是SQL REPLACE函数的很好的替换字符串函数。

  • You can refer to the article 您可以参考 Top SQL String functions in SQL Server 2017SQL Server 2017中的顶级SQL字符串函数一文以 for more information.获取更多信息。

The following query replaces the pattern A, C and D with the values 5, 9 and 4 and generates a new column named GRPCODE

以下查询将模式A,C和D替换为值5、9和4,并生成一个名为GRPCODE的新列

DROP TABLE IF EXISTS #temp;
CREATE TABLE #temp
(name NVARCHAR(50), 
 GRP  NVARCHAR(100)
);
INSERT INTO #temp
VALUES
('Prashanth', 
 'AB'
),
('Kiki', 
 'ABC'
),
('Steven', 
 'ABCD'
);

The below SQL REPLACE function undergoes an execution of 3 iterations to get the desired result. The first, input pattern ‘A’ is evaluated and if found, 5 are replaced. The second, B is evaluated. If found the numeric value 9 is replaced. Finally, D is replaced by 4.

下面SQL REPLACE函数经过3次迭代以获得所需的结果。 首先评估输入模式“ A”,如果找到,将替换5。 第二,评估B。 如果找到,则替换数值9。 最后,将D替换为4。

SELECT Name, 
       GRP, 
       REPLACE (REPLACE (REPLACE(GRP, 'A', '5'), 'C', 9), 'D', 4) GRPCODE
FROM #temp;

Here is an example to update using the SQL REPLACE function. In this case, GRP column with the GRP CODE, run the following SQL.

这是使用SQL REPLACE函数进行更新的示例。 在这种情况下,GRP列与GRP CODE一起运行以下SQL。

UPDATE #temp
  SET 
      GRP = replace(replace(REPLACE(GRP, 'A', '5'), 'C', 9), 'D', 4);

Now, let’s take a look at the data

现在,让我们看一下数据

SELECT *
FROM #temp;

用例 (Use-Case)

In general, when you migrate a database, the dependent objects also need to be migrated. For example, a linked server or specific column values of specific tables that reference a renamed table. Let’s get in-depth about the process of handling such changes dynamically using the SQL REPLACE function with T-SQL constructs.

通常,在迁移数据库时,还需要迁移从属对象。 例如,链接服务器或引用重命名表的特定表的特定列值。 让我们深入了解如何使用带有T-SQL构造SQL REPLACE函数动态处理此类更改的过程。

In one complex database migration project, the server has multiple Linked Server configurations. These linked servers were referred and mentioned in multiple stored procedures. It is a matter of the fact to find and replace the stored procedure scripts but the intent is to automate the entire process to make sure that we are not going to do any manual updates.

在一个复杂的数据库迁移项目中,服务器具有多个链接服务器配置。 这些链接的服务器在多个存储过程中被引用和提及。 找到并替换存储过程脚本是事实,但是目的是使整个过程自动化,以确保我们不会进行任何手动更新。

Let me take you through the simple steps.

让我引导您完成简单的步骤。

Step 1:

第1步:

In this case, the search pattern is employee. Also, you see that the custom escape character is used to escape special characters ‘[‘and ‘]’ in the search pattern.

在这种情况下,搜索模式是员工。 此外,您还会看到自定义转义字符用于转义搜索模式中的特殊字符'['和']'。

DECLARE @searchPattern VARCHAR(100)= 'employee';
SELECT DISTINCT 
       'sp_helptext '''+OBJECT_SCHEMA_NAME(id)+'.'+OBJECT_NAME(id)+''' '
FROM syscomments
WHERE TEXT LIKE '%'+REPLACE(REPLACE(@searchPattern, ']', '\]'), '[', '\[')+'%' ESCAPE '\'
ORDER BY 'sp_helptext '''+OBJECT_SCHEMA_NAME(id)+'.'+OBJECT_NAME(id)+''' ';

We can see in the output that 13 objects are listed by satisfying the search condition employee.

通过满足搜索条件employee,在输出中可以看到列出了13个对象。

Step 2:

第2步:

Now, it is simple to loop through the listed objects and generate the script and store it a temp table.

现在,很容易遍历列出的对象并生成脚本并将其存储到临时表。

Step 3:

第三步:

Perform a simple update to change the keyword create to “ALTER”. This way the script is ready to execute on the target database. In some cases, you just need to retain the script. That is still fine but don’t run this step.

执行简单的更新即可将关键字create更改为“ ALTER”。 这样,脚本就可以在目标数据库上执行了。 在某些情况下,您只需要保留脚本。 仍然可以,但是不要执行此步骤。

UPDATE @sptemp
  SET 
      storedProcedureText = REPLACE(REPLACE(storedProcedureText, 'CREATE PROCEDURE', 'ALTER PROCEDURE'), @searchpattern, @replacestring);
SELECT storedProcedureText
FROM @sptemp;

It’s time to copy and paste result into new query window then make sure everything looks good to run the SQL.

现在是时候将结果复制并粘贴到新的查询窗口中,然后确保运行SQL的一切看起来都很好。

In the below output you can see that search pattern employee is replaced by Prashanth.

在下面的输出中,您可以看到搜索模式employee被Prashanth取代。

You can refer the complete code in the Appendix section.

您可以在附录部分中参考完整的代码。

附录 (Appendix)

T-SQL code to replace a string in all intended Stored Procedures automatically.

T-SQL代码可自动替换所有预期的存储过程中的字符串。

SET NOCOUNT ON;
DECLARE @sql NVARCHAR(MAX), @searchpattern VARCHAR(100)= 'employee', @replacestring VARCHAR(100)= 'Prashanth';
 
-- this will hold stored procedures text
DECLARE @sptemp TABLE(storedProcedureText VARCHAR(MAX));
DECLARE cur CURSOR FAST_FORWARD
FOR SELECT DISTINCT 
           'sp_helptext '''+OBJECT_SCHEMA_NAME(id)+'.'+OBJECT_NAME(id)+''' '
    FROM syscomments
    WHERE TEXT LIKE '%'+REPLACE(REPLACE(@searchpattern, ']', '\]'), '[', '\[')+'%' ESCAPE '\'
    ORDER BY 'sp_helptext '''+OBJECT_SCHEMA_NAME(id)+'.'+OBJECT_NAME(id)+''' ';
 
--Open Cursor 
OPEN cur;
FETCH NEXT FROM cur INTO @sql;
WHILE @@FETCH_STATUS = 0
BEGIN
        --stored procedure script into a column
INSERT INTO @sptemp
EXEC (@sql);
        -- Add GO keyword
INSERT INTO @sptemp
VALUES('GO');
FETCH NEXT FROM cur INTO @sql;
END;
CLOSE cur;
DEALLOCATE cur;
UPDATE @sptemp
  SET 
      storedProcedureText = REPLACE(REPLACE(storedProcedureText, 'CREATE PROCEDURE', 'ALTER PROCEDURE'), @searchpattern, @replacestring);
SELECT storedProcedureText
FROM @sptemp;

翻译自: https://www.sqlshack.com/overview-of-the-sql-replace-function/

sql replace函数

<think>嗯,用户想了解SQL中的REGEXP_REPLACE函数用法。我需要先回忆一下这个函数的基本结构,确保自己理解正确。首先,REGEXP_REPLACE主要用于字符串的替换,支持正则表达式,比普通的REPLACE更灵活。 应该先介绍函数的语法结构,参数的含义。比如基本语法是REGEXP_REPLACE(原字符串, 正则表达式, 替换内容, 开始位置, 替换次数, 匹配模式)。可能用户需要知道每个参数的作用,特别是后面三个可选参数,容易忽略。 接下来需要举一些例子,帮助用户理解不同场景下的应用。比如替换数字、格式化电话号码、移除多余空格等。例子要具体,说明每个参数的使用情况,尤其是替换次数和匹配模式的影响。 可能用户会遇到的问题包括正则表达式的编写,或者对替换结果不满意,这时候需要提醒注意正则的语法以及不同数据库系统的差异,比如Oracle、MySQL、PostgreSQL可能有不同的实现,需要用户参考具体文档。 还要考虑用户的实际应用场景,比如数据清洗、格式化输出等,强调这个函数在处理复杂字符串替换时的优势。同时,指出性能方面的考虑,避免在大量数据中使用过于复杂的正则导致效率低下。 另外,常见错误和注意事项也要提到,比如特殊字符的转义,大小写敏感问题,以及不同数据库的兼容性。确保用户在使用时能够避免这些陷阱。 最后,总结一下使用要点,让用户有个清晰的回顾。可能需要检查语法是否正确,例子是否能够正确运行,特别是转义字符的部分是否正确,比如在正则中的反斜杠是否需要转义两次,取决于数据库系统。 总之,结构要清晰,分步骤讲解,从语法到示例,再到注意事项,确保用户能够逐步理解和应用这个函数。</think>### SQL中REGEXP_REPLACE函数用法详解 #### 一、基本语法 ```sql REGEXP_REPLACE( source_string, -- 原始字符串 pattern, -- 正则表达式匹配模式 replace_string, -- 替换内容 position, -- 开始匹配位置(可选,默认1) occurrence, -- 替换次数(可选,默认0=全部替换) match_param -- 匹配模式(可选,如'i'不区分大小写) ) ``` #### 二、参数说明 1. **source_string** 需要被处理的原始字符串,可以是字段名或直接字符串值。 2. **pattern** 正则表达式模式,用于匹配要替换的内容。 ✅ 示例:`'[0-9]'`(匹配所有数字)、`'^A'`(匹配以A开头的部分) 3. **replace_string** 替换后的新内容。支持使用捕获组(`\1`, `\2`等)引用匹配的子串。 4. **position**(默认1) 指定开始搜索的字符位置。 5. **occurrence**(默认0) 控制替换次数: - `0`:替换所有匹配项 - `n`:仅替换第n次匹配项 6. **match_param** 匹配模式修饰符,常用选项: - `'i'`:不区分大小写 - `'c'`:区分大小写 - `'m'`:多行模式 --- #### 三、典型场景示例 **📌 场景1:替换所有数字** ```sql SELECT REGEXP_REPLACE('Order1234ID567', '[0-9]', 'X') AS result; -- 输出:OrderXXXXIDXXX ``` **📌 场景2:格式化电话号码** 将 `1234567890` 转换为 `(123)-456-7890`: ```sql SELECT REGEXP_REPLACE( '1234567890', '([0-9]{3})([0-9]{3})([0-9]{4})', '(\1)-\2-\3' ) AS formatted_phone; -- 输出:(123)-456-7890 ``` **📌 场景3:选择性替换(仅替换第二次匹配)** ```sql SELECT REGEXP_REPLACE('a-b-c-d-e', '-', '/', 1, 2) AS result; -- 输出:a-b/c-d-e ``` **📌 场景4:移除多余空格** ```sql SELECT REGEXP_REPLACE('Hello World SQL', ' {2,}', ' ') AS cleaned; -- 输出:Hello World SQL ``` --- #### 四、注意事项 1. **正则表达式语法差异** 不同数据库(如Oracle、MySQL、PostgreSQL)的正则实现可能有差异,需查阅对应文档。 2. **性能优化** 复杂正则可能导致性能下降,尤其在处理大文本时需谨慎。 3. **转义字符处理** 特殊字符需转义,例如匹配`.`应写为`\.`,在SQL中可能需要双写反斜杠:`\\\\.` 4. **匹配模式优先级** 如同时指定`match_param`和正则内联修饰符(如`(?i)`),内联修饰符优先级更高。 --- #### 五、常见错误案例 ```sql -- 错误:未转义特殊字符 SELECT REGEXP_REPLACE('price: $10', '$', 'USD'); -- 错误匹配行尾 -- 正确写法 SELECT REGEXP_REPLACE('price: $10', '\$', 'USD'); -- 输出:price: USD10 ``` --- #### 六、总结 `REGEXP_REPLACE` 是处理复杂字符串替换的利器,通过合理设计正则表达式,可以实现: - 数据清洗(去噪、格式化) - 动态内容重组 - 批量模式化修改 建议通过逐步测试正则表达式(如先用`REGEXP_SUBSTR`验证匹配结果)再执行替换操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值