0

在 SQL 中,我试图在特定单词之后返回第一组数值。我只想要特定单词之后的字符串中的数字。例如:'你好:'

例如:

hello : 123            should return 123
hello : x123           should return 123
hello : 123 456        should return 123
cake : 10              should not return anything

到目前为止,我已经知道我需要做一些类似的事情 -

Declare @sInitialString varchar(max)
@sInitialString = " hello hello : 123 456"
--FIND ' hello : ' within @sInitialString
-- possibly save this a new substring or string?
-- find the first numerical value after this has been found

看起来很简单,但从以前的帖子来看,它似乎更复杂。

我设法让所有数值返回

DECLARE @sInitialString VARCHAR(MAX)

SET @sInitialString = (SELECT UPPER(' hello hello : 123 '))
select substring(@sInitialString,patindex('%[0-9]%',@sInitialString),100)

我似乎在我的方法或解决方案中遗漏了一些东西。有没有人设法做到这一点?

4

2 回答 2

0

假设您的代码可以找到相关字符串,您可以使用以下方法获取第一个值outer apply

select x.nums
from (select substring(@sInitialString, patindex('%[0-9]%', @sInitialString), 100) s
     ) s outer apply
     (select (case when s.s like '% %'
                   then left(s.s, charindex(' ', s.s)
                   else s.s
              end) as nums
     ) x

不过,我认为您的逻辑实际上并不奏效,因为它不是在寻找hello. 因此,您可能正在寻找类似的东西:

select x.nums
from (select (case when @sInitialString like 'hello%[0-9]%'
                   then substring(@sInitialString, patindex('%[0-9]%', @sInitialString), 100)
              end) s
     ) s outer apply
     (select (case when s.s like '% %'
                   then left(s.s, charindex(' ', s.s))
                   else s.s
              end) as nums
     ) x;
于 2015-12-24T12:54:26.127 回答
0

试试下面的解决方案。为了使最后的 PATINDEX 搜索工作,我必须在最后添加一个空格符号。我使用 2 step 使代码可读,但您可以将其转换为单个语句以在 SELECT 中使用或使用 CTE 实现多个 step。

DECLARE @sInitialString VARCHAR(MAX) = ' hello hello : retert 123'
DECLARE @sToken VARCHAR(MAX) = 'hello :'

-- Add a character at the to make search of the numeric string end work
SELECT @sInitialString += @sInitialString  + ' '
-- Find String token and save the rest of the string to the variable
SELECT @sInitialString = SUBSTRING(@sInitialString, PATINDEX('%' + @sToken + '%', @sInitialString) + LEN(@sToken), 10000) 
-- The extract string from first numeric character unitl last numeric 
SELECT @sInitialString = SUBSTRING(@sInitialString, PATINDEX('%[0-9]%', @sInitialString), PATINDEX('%[0-9][a-z !@#$%^&*(()_]%', @sInitialString) - PATINDEX('%[0-9]%', @sInitialString) + 1)
SELECT @sInitialString 
于 2015-12-24T20:15:58.187 回答