从T-SQL中的给定字符串中仅获取数字

时间:2019-05-31 16:35:53

标签: sql sql-server tsql

给出以下字符串,

DECLARE @Text1 = 'This is the 1st time I found the Car# CAR:8 #NumberIncluded#'

DECLARE @Text2 = 'This is the 1st time I found the Car# CAR:8 #NumberIncluded# with no ID tied to it, the prices is 588USD for  CAR:8 #NumberIncluded##NumberIncluded#'

我想知道是否有一种方法可以在mssql 2008中仅获得CAR之后的第一个数字8:

3 个答案:

答案 0 :(得分:3)

这是获得它的一种选择。它首先删除CAR:之前的所有内容,然后删除其余字符串中的所有数字后的所有内容。

SELECT SUBSTRING( x.TruncString, 0, PATINDEX( '%[^0-9]%', x.TruncString))
FROM (VALUES('This is the 1st time I found the Car# CAR:8 #NumberIncluded#'),
            ('This is the 1st time I found the Car# CAR:8 #NumberIncluded# with no ID tied to it, the prices is 588USD for  CAR:8 #NumberIncluded##NumberIncluded#')
     )SampleData(String)
CROSS APPLY( SELECT STUFF( String, 1, CHARINDEX( 'CAR:', String)+3, ''))x(TruncString)

答案 1 :(得分:1)

我建议这个:

DECLARE @Text1 NVARCHAR(MAX) = 'This is the 1st time I found the Car# CAR:8 #NumberIncluded#'

DECLARE @Text2 NVARCHAR(MAX) = 'This is the 1st time I found the Car# CAR:8 #NumberIncluded# with no ID tied to it, the prices is 588USD for  CAR:7 #NumberIncluded##NumberIncluded#'

DECLARE @Text3 NVARCHAR(MAX) = 'My CAR:A5, CAR:9 AND CAR:10'

SELECT SUBSTRING(@Text1, PATINDEX('%CAR:[0-9]%', @Text1) + 4, 1)  
SELECT SUBSTRING(@Text2, PATINDEX('%CAR:[0-9]%', @Text2) + 4, 1)
SELECT SUBSTRING(@Text3, PATINDEX('%CAR:[0-9]%', @Text3) + 4, 1)

预期结果:8、8、9

答案 2 :(得分:0)

如果您使用的是SQL Server 2016+,请使用string_split()

DECLARE @Text1 varchar(100) = 'This is the 1st time I found the Car# CAR:8 #NumberIncluded#';

SELECT top 1 value  
FROM STRING_SPLIT(@Text1, 'CAR:')