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函数

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值