本文介绍了空格后的子串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拆分一个字符串并获取空格后的值.我可以在空格前获取值,但如何在空格后获取字符串.

DECLARE @string varchar(20)SELECT @string = '测试名称'SELECT SUBSTRING(@string, 0, CHARINDEX(' ', @string))

我使用的是 SQLServer 2012

解决方案

以下是使用 SUBSTRINGCHARINDEX 的版本,适用于 SQL Server 2016 之前的 SQL SERVER 版本,当 STRING_SPLIT.

以下任一作品:

SELECT SUBSTRING(@string, CHARINDEX(' ', @string) +1, 20)SELECT SUBSTRING(@string, CHARINDEX(' ', @string) +1, DATALENGTH(@string) - CHARINDEX(' ', @string) +1 )

根据 Rao 的评论编辑添加描述

我们需要使用 CHARINDEX 找到空格的位置(它返回一个表示字符串(空格)开始位置的数字.但是我们要选择的字符串在空格之后开始,因此我们必须加 1 (+1) 到我们 SUBSTRING 的起始位置,使起始位置变为 CHARINDEX(' ', @string) + 1.

SUBSTRING 的第三个参数是要选择的字符串的长度,在第一种情况下,我只是假设您指定为 varchar(20) 的字符串不能超过 20 个字符,因此我使用 20.注意 SUBSTRING 将不要尝试选择超过字符串末尾的字符,因此指定一个长度大于剩余字符数的长度是安全的.

我的第二个示例根据总字符串的长度 (DATALENGTH) 减去我们选择之前的字符数 (CHARINDEX + 1) 来获取要选择的字符串的长度

I want to split a string and get the value after the space. I can get the value before space but how to get the string after space.

DECLARE @string varchar(20) 
SELECT @string = 'Test Name'
SELECT SUBSTRING(@string, 0, CHARINDEX(' ', @string))

Edit: I am using SQLServer 2012

解决方案

Here's a version using SUBSTRING and CHARINDEX for versions of SQL SERVER prior to SQL Server 2016 when STRING_SPLIT was introduced.

Either of the following works:

SELECT  SUBSTRING(@string, CHARINDEX(' ', @string) +1, 20)

SELECT  SUBSTRING(@string, CHARINDEX(' ', @string) +1, DATALENGTH(@string) - CHARINDEX(' ', @string) +1 )

We need to find the position of the space using CHARINDEX (which returns a number representing where the string (the space) begins. However the string that we want to select begins after the space, therefore we must add 1 (+1) to the starting position of our SUBSTRING so that the starting position becomes CHARINDEX(' ', @string) + 1.

The 3rd argument for SUBSTRING is the length of the string to select, in the first case I just assume that the string you specified as a varchar(20) can be no longer than 20 characters hence me using 20. Note SUBSTRING will not try to select characters past the end of the string, so it is safe to specify a length longer than the number of characters left.

My second example gets the length of the string to select based on it being the length of the total string (DATALENGTH) minus the number of characters before our selection (CHARINDEX + 1)

这篇关于空格后的子串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 05:00