我在SQL Server Management Studio中有一个表,其中包含数字范围的列作为字符串。我试图找到一种方法从字符串中提取数值并将它们插入到新表中。
例如,在表格中,我将值12.45% - 42.32%
作为字符串。我希望能够获得12.45
和42.32
并将其插入到包含min_percent
和max_percent
列的新表格中。
我找到了几种使用SQL从字符串中提取单个数值的方法,并尝试从Extract numbers from a text in SQL Server修改函数(它返回多个整数,但不是小数),但到目前为止我还没有能够使它工作。提前感谢任何建议
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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