I have some varchar data that has numeric values in it, and I'm trying to strip out only the numeric part. I'm doing this as part of a stored proc that is doing a lot of other stuff at the same time, so I'm hoping to do this as part of an inline query.
My data values in this column look like this (added single ticks to show ends of varchars):
'1.25', '< 5 min', '2.35 minutes', '50.43 min'
What I want to get out of this column is: 1.25, 5, 2.35, 50.43
What my problem seems to be is how to determine the length of the numeric values in the single select, so I can lop off the characters at the end. Other than just choosing a value (my numbers are not always the same length), I'm not sure what I can do. My reason for wanting the numeric value only is because I need to convert it to a float for its destination value.
Here's what I've tried:
SUBSTRING(my_data, PATINDEX('%[0-9]%', my_data), 4)
It's a little complicated, but it works for your examples.
declare @val varchar(10)
select @val='50.43 min'
select
case
when PATINDEX('%[a-z]%',col) = 0
then col
else rtrim(SUBSTRING(col,1,PATINDEX('%[a-z]%',col)-1))
end
from
( select SUBSTRING(@val,PATINDEX('%[0-9]%',@val),PATINDEX('%[0-9]%',@val)
+len(@val)+1) as col ) t
Here you can find documentation about string functions.