sql中截取字符串函数_SQL Server 2017中的顶级SQL字符串函数

sql中截取字符串函数

SQL Server 2017 has been in the talk for its many features that simplify a developer’s life. With the previous versions, developers had to write T-SQL, or user-defined functions using temporary tables, and build complex logic, just for string manipulation. In almost every database I work with, I see many user-defined functions for string manipulation and string aggregation.

SQL Server 2017一直在谈论其简化开发人员生活的许多功能。 在以前的版本中,开发人员必须使用临时表编写T-SQL或用户定义的函数,并构建复杂的逻辑,仅用于字符串操作。 在我使用的几乎每个数据库中,我都看到许多用于字符串操作和字符串聚合的用户定义函数。

This article outlines the basic concepts of how to use the new SQL Server string function in SQL Server 2017 on a Linux machine.

本文概述了如何在Linux计算机上SQL Server 2017中使用新SQL Server字符串函数的基本概念。

SQL Server 2017 CTP 1.1 contains various SQL string functions out of the box, a few of them being:

SQL Server 2017 CTP 1.1包含现成的各种SQL字符串函数,其中一些是:

  • CONCAT_WS, TRANSLATE, and TRIM
  • CONCAT_WSTRANSLATETRIM
  • Support for the WITHIN GROUP clause for the STRING_AGG function.
  • 支持STRING_AGG函数的WITHIN GROUP子句。

A collection of new SQL string function in SQL Server 2017, such as TRANSLATE, TRIM, CONCAT_WS, STRING_AGG are almost similar to the SQL string functions of other relational databases engines.

SQL Server 2017中新SQL字符串函数的集合(例如TRANSLATETRIMCONCAT_WSSTRING_AGG)几乎与其他关系数据库引擎SQL字符串函数类似。

As developers, we try to achieve results in simple and smart ways. The SQL Server string functions available in SQL Server 2017 make the life of a developer much simpler.

作为开发人员,我们尝试以简单而明智的方式取得成果。 SQL Server 2017中可用SQL Server字符串函数使开发人员的工作变得更加简单。

So, let us get started, and see the usage of the available SQL string functions!

因此,让我们开始吧,看看可用SQL字符串函数的用法!

修剪 (TRIM)

The SQL trim function removes the space character char(32) or other specified characters from the start or end of a string.

SQL修剪函数 从字符串的开头或结尾 删除空格字符 char(32) 或其他指定的字符。

As a SQL developer, you must have often come across a scenario where you had to remove the empty spaces at the beginning and the end of strings. To achieve that, you may have used the SQL Server string functions, RTRIM and
LTRIM—you had to use both, because SQL Server does not have a function which can trim leading or trailing spaces of a given string with a single function, even though TRIM() is a very popular function in many languages. The release of SQL Server 2017 comes with this new string function “TRIM”. You can use the SQL TRIM function to get rid of the leading and trailing spaces around any given string.

作为SQL开发人员,您必须经常遇到一种情况,必须删除字符串开头和结尾的空格。 为此,您可能使用了SQL Server字符串函数,RTRIM和
LTRIM —您必须同时使用这两者,因为即使TRIM()在许多语言中非常流行,SQL Server都没有一个函数可以用单个函数修剪给定字符串的前导或尾随空格。 SQL Server 2017发行版附带此新的字符串函数“ TRIM”。 您可以使用SQL TRIM函数来消除任何给定字符串周围的前导和尾随空格。

SQL Server 2017 SQL Server
Syntax TRIM ([characters FROM] string)
Characters could be a literal, variable, or a function call of any non-LOB character type (nvarchar, varchar, nchar, or char) containing characters to be removed. nvarchar(max) and varchar(max) types are not allowed.
A string is an expression of any character type (nvarchar, varchar, nchar, or char) from which characters should be removed.
CREATE FUNCTION dbo.TRIM(@str VAR-CHAR(MAX))
RETURNS VAR-CHAR(MAX)
BEGIN
RETURN LTRIM(RTRIM(@str))
END
or CLR
SQL Server 2017 SQL服务器
句法 TRIM([characters FROM]字符串)
字符可以是包含要删除字符的任何非LOB字符类型( nvarcharvarcharncharchar )的文字,变量或函数调用。 不允许使用nvarchar(max)varchar(max)类型。
字符串是应从中删除字符的任何字符类型( nvarcharvarcharncharchar )的表达式。
创建函数 dbo.TRIM ( @str VAR-CHAR ( MAX ))
返回VAR-CHAR ( MAX )
开始
返回 LTRIM ( RTRIM ( @str ))
结束
或CLR

Let us consider an example string, from which we have to remove the leading and trailing spaces:
‘   SQLShack   ’

让我们考虑一个示例字符串,我们必须从中删除前导和尾随空格:
' SQLShack '

 
DECLARE @Str NVARCHAR(MAX)
SET @Str = '           SQLShack           '
SELECT @Str OriginalString, RTRIM(LTRIM(@Str)) TrimmedString
GO
 

This is how we have been trimming the leading and trailing spaces until SQL Server 2016. With SQL Server 2017, we could use the SQL TRIM function to remove the leading and trailing spaces of a given string:

这是我们一直修剪到SQL Server 2016为止的前导和尾随空格的方式。对于SQL Server 2017,我们可以使用SQL TRIM函数删除给定字符串的前导和尾随空格:

 
SELECT @@version SQLVersion
GO
DECLARE @Str NVARCHAR(MAX)
SET @Str = '           SQLShack           '
SELECT @Str OriginalString, TRIM(@Str) TrimmedString
 

翻译 (TRANSLATE )

The TRANSLATE SQL string function allows us to perform a one-to-one, single-character substitution in a string. Until SQL Server 2016, we used use REPLACE function to replace each character or write UDF function.

TRANSLATE SQL字符串函数使我们可以在字符串中执行一对一,单字符替换。 在SQL Server 2016之前,我们使用REPLACE函数替换每个字符或编写UDF函数。

SQL Server 2017 SQL Server
Syntax TRANSLATE ( inputString, characters, translations)
Arguments
InputString is an expression of any character type (nvarchar, varchar, nchar, char).
Characters is an expression of any character type containing characters to be replaced.
Translations, is a character expression that matches second argument by type and length.
REPLACE ( string_expression , string_pattern , string_replacement ) or UDF.
SQL Server 2017 SQL服务器
句法 TRANSLATE(inputString,字符,翻译)
争论
InputString是任何字符类型( nvarcharvarcharncharchar )的表达式。
字符是包含要替换字符的任何字符类型的表达式。
Translations是一个按类型和长度匹配第二个参数的字符表达式。
替换(string_expression,string_pattern,string_replacement)UDF

Let us consider the following example:

让我们考虑以下示例:

Replace the special characters in a string with ‘1

将字符串中的特殊字符替换为“ 1

 
SELECT @@version SQLVersion
GO
DECLARE @Str NVARCHAR(MAX)
SET @Str = '{~~[##SQLShack##]~~}'
SELECT @Str InputString, REPLACE
    (
        REPLACE
            (
                REPLACE
                    (
                        REPLACE
                            (
                                REPLACE
                                    (
                                        REPLACE(@Str,'#','1'),
                                        '[','1'
                                    ),
                                ']','1'
                            ),
                            '~','1'
                        ), 
                    '{','1'
                ),
            '}','1'
    ) OutPutString
 

With the TRANSLATE SQL string function, the process becomes much simpler than using REPLACE

使用TRANSLATE SQL字符串函数,该过程比使用REPLACE更加简单。

 
SELECT @@version SQLVersion
GO
DECLARE @Str NVARCHAR(MAX)
SET @Str = '{~~[##SQLShack##]~~}'
SELECT TRANSLATE(@Str, '#[]{}~~', '1111111');
GO
 

Note: The second and third arguments of the built-in SQL string function, TRANSLATE, must contain an equal number of characters.

注意:内置SQL字符串函数 TRANSLATE 的第二个和第三个参数 必须包含相等数量的字符。

输出量 (Output)

InputString OutPutString
{~~[##SQLShack##]~~} 111111SQLShack111111
输入字符串 OutPutString
{~~ [## SQLShack ##] ~~} 111111SQLShack111111

CONCAT_WS (CONCAT_WS)

CONCAT_WS() stands for Concatenate with Separator, and is a special form of CONCAT(). The first argument is the separator—separates the rest of the arguments. The separator is added between the strings to be concatenated. The separator can be a string, as can the rest of the arguments be. If the separator is NULL, the result is NULL.

CONCAT_WS()表示与分隔符并置,并且是CONCAT()的一种特殊形式。 第一个参数是分隔符,用于分隔其余参数。 分隔符被添加到要连接的字符串之间。 分隔符可以是字符串,其余参数也可以。 如果分隔符为NULL ,则结果为NULL

In the following example, the separator hyphen () is used. The CONCAT_WS is similar to the existing CONCAT() function, which was introduced in SQL Server 2012. The function concatenates a number of arguments or string values.

在以下示例中,使用了分隔符连字符( - )。 CONCAT_WS与SQL Server 2012中引入的现有CONCAT()函数相似。该函数可连接多个参数或字符串值。

The CONCAT_WS behavior can be emulated using the STUFF and the COALESCE functions in SQL Server.

可以使用SQL Server中的STUFFCOALESCE函数来模拟CONCAT_WS行为。

COALESCE() accepts a series of values along with a value to use in the event that all items in the list are null.

COALESCE()接受一系列值以及在列表中的所有项目均为null的情况下使用的值。

The STUFF function inserts a string into another string. It deletes a specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.

STUFF函数将一个字符串插入另一个字符串。 它在开始位置删除第一个字符串中指定长度的字符,然后在开始位置将第二个字符串插入第一个字符串。

SQL Server 2017 SQL Server
Syntax CONCAT_WS (separator, argument1, argument1
[, argumentN]…)

Separator is an expression of any character type (nvarchar, varchar, nchar, or char).
argument1, argument2, etc. could be expressions of any type.
Using coalesce to handle null values and stuff for string manipulation
SQL Server 2017 SQL服务器
句法 CONCAT_WS(分隔符,参数1,参数1
[,argumentsN]…)
分隔符是任何字符类型( nvarcharvarcharncharchar )的表达式。
arguments1argument2等可以是任何类型的表达式。
利用聚结 ,处理空值和东西的字符串操作

One primary difference is that concat_ws() skips NULL arguments, but + does not. You could emulate this behavior with:

一个主要区别是concat_ws()会跳过NULL参数,但+不会。 您可以使用以下方式模仿此行为:

Select stuff((coalesce(‘-‘ + A, ”) + coalesce(‘-‘ + B, ”) + . . .
        ), 1, 1, ”)

选择stuff((coalesce('-'+ A,))+ coalesce('-'+ B,))+。
),1、1,”)

Of course, this doesn’t convert the values to strings, as concat_ws() does. Therefore, a version that’s closer, could be something like:

当然,这不会像concat_ws()那样将值转换为字符串。 因此,更接近的版本可能类似于:

 
SELECT @@version SQLVersion
GO
 
select top 10 stuff(
  (coalesce
    (' - ' + FirstName, '') + 
      coalesce(' - ' + MiddleName, '') +
        coalesce(' - ' + LastName, '') 
             ), 2, 1, ' ')
       ,    FirstName, MiddleName, LastName
FROM [Person].[Person]
 

Using Concat_WS, the entire string manipulation is made very simpler

使用Concat_WS,整个字符串操作变得非常简单

 
SELECT @@version SQLVersion
GO
SELECT TOP 10 
    CONCAT_WS 
  (
    ' - ' , 
    FirstName , 
    MiddleName , 
    LastName
  ) as FullName, 
    FirstName, MiddleName,LastName
FROM [Person].[Person]
 

STRING_AGG (STRING_AGG)

Aggregate functions compute a single result from a set of input values. With the prior versions of SQL, string aggregation was possible using T-SQL or CLR, but there was no inbuilt function available for string aggregation, with a separator placed in between the values.

聚合函数根据一组输入值计算单个结果。 在早期版本SQL中,可以使用T-SQL或CLR进行字符串聚合,但是没有内置函数可用于字符串聚合,在值之间放置了分隔符。

With SQL Server 2017, built-in STRING_AGG functions are available for string aggregation.

使用SQL Server 2017,内置的STRING_AGG函数可用于字符串聚合。

SQL Server 2017 SQL Server
Syntax STRING_AGG ( expression, separator [ <order_clause> ] )
<order_clause> ::=
WITHIN GROUP ( ORDER BY <order_by_expression_list> [ ASC | DESC ] )

Arguments
Separator is an expression of NVARCHAR or VARCHAR type that is used as a separator for concatenated strings. It can be a literal or a variable.
The Expression could be an expression of any type. Expressions are converted to NVARCHAR or VARCHAR types during concatenation. Non-string types are converted to NVARCHAR type.
+ is used to optionally specify order of concatenated results using the WITHIN GROUP clause:
copy
code
WITHIN GROUP ( ORDER BY <order_by_expression_list> [ ASC | DESC ] )
Aggregate String Concatenation SQL Server Using stuff and XML Parsing, or UDF
SQL Server 2017 SQL服务器
句法 STRING_AGG(表达式,分隔符[<order_clause>])
<order_clause> :: =
WITHIN GROUP(ORDER BY <order_by_expression_list> [ASC | DESC])
争论
分隔符NVARCHARVARCHAR类型的表达式,用作串联字符串的分隔符。 它可以是文字或变量。
表达式可以是任何类型的表达式。 在连接过程中,表达式将转换为NVARCHARVARCHAR类型。 非字符串类型将转换为NVARCHAR类型
+用于使用WITHIN GROUP子句来选择指定连接结果的顺序:
复制

WITHIN GROUP(ORDER BY <order_by_expression_list> [ASC | DESC])
使用填充和XML解析或UDF聚合字符串连接SQL Server

The following example shows how simple it is to group based on the name field, and generate a CSV. The same can be derived using available SQL functions. However, this readily available SQL string function provides a simple interface to string manipulation.

以下示例说明了基于名称字段进行分组并生成CSV的简单性。 可以使用可用SQL函数得出相同的结果。 但是,这个易于使用SQL字符串函数为字符串操作提供了一个简单的接口。

 
CREATE  TABLE  #temp(id int,name char(3))
 
INSERT INTO #temp VALUES (1,'CD')
,(1,'AB')
,(2,'LM')
,(3,'BC')
,(3,'GH')
,(4,'KJ')
,(3,'AB')
 
 
SELECT id, 
    STRING_AGG (name, ',') AS data 
FROM #temp
GROUP BY id; 
 
SELECT id, 
    STRING_AGG (name, ',') WITHIN GROUP (ORDER BY name ASC) AS data 
FROM #temp
GROUP BY id; 
 
DROP TABLE #temp
 

The old way to do this was using a STUFF command along with an XML path statement, which could then show one row of data, with values separated by a comma. While this is achievable, it is rather confusing to read and understand. The new way to do this is by the string aggregate ( STRING_AGG) function as given above.

执行此操作的旧方法是使用STUFF命令以及XML路径语句,该语句随后可以显示一行数据,其值之间用逗号分隔。 尽管这是可以实现的,但阅读和理解却相当混乱。 执行此操作的新方法是通过如上所述的字符串聚合( STRING_AGG )函数。

 
CREATE  TABLE  #temp(id int,name char(3))
 
INSERT INTO #temp VALUES (1,'CD')
,(1,'AB')
,(2,'LM')
,(3,'BC')
,(3,'GH')
,(4,'KJ')
,(3,'AB')
 
select distinct t1.id,
  STUFF((SELECT distinct ',' + t2.name
         from #temp t2
         where t1.id = t2.id
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'') data
from #temp t1;
 
DROP TABLE #temp
 

结论 (Conclusion)

This article outlines the concept of advanced SQL string functions in comparison with the old-school methods of string manipulation.

本文概述了与老式的字符串处理方法相比,高级SQL字符串函数的概念。

With SQL Server 2017, SQL string manipulation is a lot easier. Developers need not juggle alternatives or maintain obsolete workarounds.

使用SQL Server 2017,SQL字符串操作要容易得多。 开发人员无需杂耍替代方案或维护过时的解决方法。

These new built-in SQL Sever string functions perform generally better than the user-defined functions or T-SQL.

这些新的内置SQL Sever字符串函数通常比用户定义的函数或T-SQL更好。

目录 (Table of contents)

A Quick start Guide to Managing SQL Server 2017 on CentOS/RHEL Using the SSH Protocol
How to use Python in SQL Server 2017 to obtain advanced data analytics
Data Interpolation and Transformation using Python in SQL Server 2017
An introduction to a SQL Server 2017 graph database
Top string functions in SQL Server 2017
Top 8 new (or enhanced) SQL Server 2017 DMVs and DMFs for DBAs
Overview of Resumable Indexes in SQL Server 2017
Understanding automatic tuning in SQL Server 2017
使用SSH协议在CentOS / RHEL上管理SQL Server 2017的快速入门指南
如何在SQL Server 2017中使用Python获得高级数据分析
在SQL Server 2017中使用Python进行数据插值和转换
SQL Server 2017图形数据库简介
SQL Server 2017中的顶级字符串函数
适用于DBA的前8大新(或增强)SQL Server 2017 DMV和DMF
SQL Server 2017中的可恢复索引概述
了解SQL Server 2017中的自动调整

翻译自: https://www.sqlshack.com/top-sql-string-functions-in-sql-server-2017/

sql中截取字符串函数

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值