T-SQL查找字符串中单词的长度

时间:2015-03-18 13:56:42

标签: sql-server regex tsql sql-server-2012

使用PATINDEX,我可以在字符串中找到模式的第一个发现,比如一个数字 - 在字符串中有几个匹配到我的模式

我的问题是如何在字符串中找到该模式的第一个发现的结束位置?

DECLARE @txt VARCHAR(255)
SET @txt = 'this is a string 30486240 and the string is still going 30485 and this is the end'
PRINT SUBSTRING(@txt,PATINDEX('%[0-9]%',@txt),8)

我的问题是,我不想手动输入8,我想找到第一个数字的长度

使用SQL Server 2012

2 个答案:

答案 0 :(得分:0)

试试这个,它应该从你的文字中返回第一个数字:

DECLARE @txt VARCHAR(255)
SET @txt = 'this is a string 30486240 and the string is still going 30485 and this is the end'

DECLARE @startIndex INTEGER
SELECT @startIndex = PATINDEX('%[0-9]%',@txt)

DECLARE @remainingString NVARCHAR(MAX)
SELECT @remainingString = substring(@txt, @startIndex, LEN(@txt) - @startIndex)

DECLARE @endingIndex INTEGER
SELECT @endingIndex = PATINDEX('%[a-zA-Z]%', @remainingString) - 1

SELECT RTRIM(SUBSTRING(@txt, @startIndex, @endingIndex))

只要您的数字中没有“嵌入”字母,此查询就会起作用,例如30486a24b0

答案 1 :(得分:0)

当你不知道子串的长度时,这是一个解决方案:

SELECT Left(
             SubString(@Data, PatIndex('%[0-9.-]%', @Data), 8000), 
             PatIndex('%[^0-9.-]%', SubString(@Data, PatIndex('%[0-9.-]%', @Data), 8000) + 'X')-1)

来源:http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/extracting-numbers-with-sql-server/

我必须多次完成练习,并且在注意到第二个PATINDEX中的插入符之前一直认为博客文章是错误的。