2015-12-24 14 views
0

在SQL中,我試圖在特定單詞後返回第一組數值。我只想要特定單詞後的字符串中的數字。 如:「你好:」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) 

我剛纔似乎在我的方法或解決方案無論是失去了一些東西。有沒有人設法實現這一目標?

+0

我想知道這個操作背後的原因是什麼。 – athabaska

+2

也許應該把這個邏輯放到你的客戶端,會更容易 – athabaska

+0

最好的選擇是把這個邏輯封裝到SQL CLR函數中。在函數內部,您可以使用正則表達式或使用字符串拆分操作來實現此邏輯。 –

回答

0

請嘗試下面的解決方案。爲了進行最後一次PATINDEX搜索,我必須在最後添加一個空格符號。我使用2步來使代碼可讀,但是您可以將它轉換爲單一語句以在SELECT中使用或使用CTE來實現多個步驟。

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 [email protected]#$%^&*(()_]%', @sInitialString) - PATINDEX('%[0-9]%', @sInitialString) + 1) 
SELECT @sInitialString 
+0

非常感謝你。 – WelliXL

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; 
+0

感謝您的邏輯指針,它給了我一些想法 – WelliXL

相關問題