Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to retrieve only numerical values from a string in sql

What I have tried:

I tried with patindex but i can't able to iterate through the loop
Posted
Updated 3-May-18 21:16pm

What you want to do will not be achieved by some basic PATINDEX, you will need to run a loop for the string and get every numeric value out of it. Consider the following SQL function as an example.

SQL
CREATE FUNCTION NumbersFromString (@string VARCHAR(100))
RETURNS VARCHAR(100)
AS
   BEGIN
     DECLARE @loc INT
     --Get the location of the first letter in the string that is not a number.
     SET @loc = PATINDEX('%[^0-9]%', @string )
       BEGIN
         --Iterate till there is a non-numeric letter in the string.
         WHILE @loc > 0
           BEGIN
             --Replace the letter found at the location with ''.
             SET @string = STUFF(@string , @loc, 1, '' )
             --Set location to next letter.
             SET @loc = PATINDEX('%[^0-9]%', @string )
           END
       END
       --Return result.
       RETURN ISNULL(@string, 0)
    END;
 
Share this answer
 
Comments
Maciej Los 4-May-18 2:02am    
Good one!
GKP1992 4-May-18 2:03am    
Thanks again.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900