Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL take just the numeric values from a varchar

Say i have a few fields like the following:

abd738927
jaksm234234
hfk342
ndma0834
jon99322

Type: varchar.

How do I take just the numeric values from this to display:

738927
234234
342
0834
99322

Have tried substring however the data varies in length, and cast didnt work either due to being unable to convert, any ideas?

like image 828
JsonStatham Avatar asked Jul 04 '12 17:07

JsonStatham


People also ask

How do I select a numeric value from a varchar column in SQL?

In SQL Server, we can use the ISNUMERIC() function to return numeric values from a column. We can alternatively run a separate query to return all values that contain numeric data.

How extract only numbers from alphanumeric string in SQL?

To extract the first number from the given alphanumeric string, we are using a SUBSTRING function. In the substring function, we are extracting a substring from the given string starting at the first occurrence of a number and ending with the first occurrence of a character.


2 Answers

Here's the example with PATINDEX:

select SUBSTRING(fieldName, PATINDEX('%[0-9]%', fieldName), LEN(fieldName))

This assumes (1) the field WILL have a numeric, (2) the numerics are all grouped together, and (3) the numerics don't have any subsequent characters after them.

like image 110
Sean Avatar answered Oct 14 '22 22:10

Sean


Extract only numbers (without using while loop) and check each and every character to see if it is a number and extract it

   Declare @s varchar(100),@result varchar(100)
    set @s='as4khd0939sdf78' 
    set @result=''

    select
        @result=@result+
                case when number like '[0-9]' then number else '' end from 
        (
             select substring(@s,number,1) as number from 
            (
                select number from master..spt_values 
                where type='p' and number between 1 and len(@s)
            ) as t
        ) as t 
    select @result as only_numbers 
like image 30
compcobalt Avatar answered Oct 14 '22 23:10

compcobalt