2013-06-24 51 views
0

我在SQL Server Management Studio中有一個表,其中包含以字符串形式表示的數字範圍的列。我試圖找到一種方法來從字符串中提取數字值並將它們插入到一個新表中。從T-SQL中的字符串中提取多個十進制數

例如,在表中,我將值12.45% - 42.32%作爲字符串。我希望能夠得到12.4542.32,並將它們插入到列表中,其列min_percentmax_percent

我發現了幾種使用SQL從字符串中提取單個數值的方法,並嘗試從Extract numbers from a text in SQL Server(它返回多個整數,但不是小數點)修改函數,但到目前爲止我還沒有能夠獲得它工作。在此先感謝您的任何建議

回答

0

假設你的數據是一致的,這應該做工精細,並具有可對眼睛更容易的優點。如果你要精確,還要考慮小數。

select 
    cast(left(r, charindex('%', r) - 1) AS float) as minVal, 
    cast(replace(right(r, charindex('-', r) - 1), '%', '') as float) AS maxVal 
from (select '22.45% - 42.32%' as r) as tableStub 
0

下面是使用SQL Server提供的字符串操作的蠻力方法:

with t as (
     select '12.45% - 42.32%' as val 
    ) 
select cast(SUBSTRING(val, 1, charindex('%', val) - 1) as float) as minval, 
     cast(replace(substring(val, len(val) - charindex(' ', reverse(val))+2, 100), '%', '') as float) as maxval 
from t 
1

功能是相當接近。你只需要使用數字和補充了一點:

with C as 
    (
    select cast(substring(S.Value, S1.Pos, S2.L) as decimal(16,2)) as Number, 
      stuff(s.Value, 1, S1.Pos + S2.L, '') as Value 
    from (select @String+' ') as S(Value) 
     cross apply (select patindex('%[0-9,.]%', S.Value)) as S1(Pos) 
     cross apply (select patindex('%[^0-9,.]%', stuff(S.Value, 1, S1.Pos, ''))) as S2(L) 
    union all 
    select cast(substring(S.Value, S1.Pos, S2.L) as decimal(16,2)), 
      stuff(S.Value, 1, S1.Pos + S2.L, '') 
    from C as S 
     cross apply (select patindex('%[0-9,.]%', S.Value)) as S1(Pos) 
     cross apply (select patindex('%[^0-9,.]%', stuff(S.Value, 1, S1.Pos, ''))) as S2(L) 
    where patindex('%[0-9,.]%', S.Value) > 0 
) 
    select Number 
    from C 
相關問題