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 #tempSET 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 @sptempSET 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 syscommentsWHERE 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 @sptempSET 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函数

sql replace函数_SQL REPLACE函数概述相关推荐

  1. sql stuff 函数_SQL STUFF函数概述

    sql stuff 函数 This article gives an overview of the SQL STUFF function with various examples. 本文通过各种示 ...

  2. sql字符串函数_SQL字符串函数概述

    sql字符串函数 In this article, we will try to give a brief overview of the SQL string functions used in S ...

  3. sql isnull函数_SQL ISNULL函数

    sql isnull函数 This article explores the SQL ISNULL function to replace NULL values in expressions or ...

  4. sql用于字符串的聚合函数_SQL字符串函数用于数据整理(争用)

    sql用于字符串的聚合函数 In this article, you'll learn the tips for getting started using SQL string functions ...

  5. sql trim函数_SQL TRIM函数

    sql trim函数 In this article, we will review the new SQL TRIM function in SQL Server 2017 onwards as w ...

  6. java datediff函数_sql DATEDIFF 函数

    sql  DATEDIFF 函数 今天的所有数据:select * from 表名 where DateDiff(dd,datetime类型字段,getdate())=0 昨天的所有数据:select ...

  7. python substr函数_Sql SUBSTR函数

    SQL常用函数总结 SQL常用函数总结 这是我在项目开发中使用db2数据库写存储过程的时候经常用到的sql函数.希望对大家有所帮助: sql cast函数 (1).CAST()函数的参数是一个表达式, ...

  8. dql聚合函数_sql聚合函数有哪些

    SQL聚合函数有:1.AVG函数:2.COUNT函数:3.MAX函数:4.MIN函数:5.SUM函数:6.GROUPING函数:7.CHECKSUM函数:8.STDEV函数:9.STDEVP函数:10 ...

  9. sql over函数_SQL 高级函数

    今天是高端局,都是超级高大上的内容,惯例上目录 今天觉得红黑配色好好看呀 今天没有什么具体的栗子合集,大家的应用场景都很不一样,so,到具体知识点,我们再具体举栗子. 窗口函数 概念: 窗口函数,也叫 ...

最新文章

  1. C语言中的匿名结构体
  2. 阿里云白皮书_奥雅纳携手阿里云研究中心发布《动态数据增强未来城市设计倡议》白皮书...
  3. Restic 跨平台加密备份工具
  4. 第一次使用水晶报表,柱状图的横竖坐标不会定位,怎么办?
  5. Android默认记住登录用户名,【教程】Android 记住密码和自动登录界面的实现
  6. 二次优化问题dfp_MATLAB优化问题应用实例讲解
  7. java关于Timer schedule执行定时任务 1、在应用开发中,经常需要一些周期性的操作,比如每5分钟执行某一操作等...
  8. Servlet 环境设置
  9. oracle 用户包含;,Oracle 数据库查看client的用户登录信息包括ip
  10. FDQuery 怎么能插入NULL参数
  11. spring security 使用 application/json 接收数据
  12. php 如何去除说有空格,php怎么去除所有空格
  13. 给大家推荐一首好听的流行音乐
  14. 采集工具助力企业拓客,让你的业务快速扩张
  15. Game101课程笔记_lecture06_光栅化2
  16. Mysql之limit语句
  17. IP协议详解(ip头部,ip分片,ip路由选择)
  18. 浏览器——主页修改及恢复方法
  19. 国家质量基础设施(NQI)“一站式”公共服务平台建设方案
  20. TMC2225电机驱动简介

热门文章

  1. 使用计算机过程存在的问题,中小学教师计算机应用过程中存在的问题及解决方法...
  2. java jdk1.8使用_Java jdk1.8配置
  3. layui数据表格如何获取id_LayUI之table数据表格获取行、行高亮等相关操作
  4. 网络链路不稳定的排查问题方法
  5. IntelliJ IDEA 2018 设置代码提示对大小写不敏感
  6. 机器学习之路:python 集成分类器 随机森林分类RandomForestClassifier 梯度提升决策树分类GradientBoostingClassifier 预测泰坦尼克号幸存者...
  7. lintcode-87-删除二叉查找树的节点
  8. Motan:目录结构
  9. NET中对象的构建过程
  10. hibernate+spring 注解 对事务的一些信息 (还没有整理)