0

我在 SQL Server Management Studio 中有一个表,其中的列包含数字范围作为字符串。我正在尝试找到一种从字符串中提取数值并将它们插入新表的方法。

例如,在表中,我将值12.45% - 42.32%作为字符串。我希望能够获取12.45并将42.32它们插入到带有列min_percent和的新表中max_percent

我找到了几种使用 SQL 从字符串中提取单个数值的方法,还尝试修改从SQL Server 中的文本中提取数字的函数(返回多个整数,但不返回小数),但到目前为止我还没有能够让它工作。在此先感谢您的任何建议

4

3 回答 3

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
于 2013-06-24T18:44:34.397 回答
1

Assuming your data is consistent, this should work fine, and has the added advantage of being easier on the eyes. Also consider decimal if you're going for precision.

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
于 2013-06-24T20:23:03.497 回答
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
于 2013-06-24T18:36:24.407 回答