Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query to get only numbers from a string

Tags:

sql

sql-server

I have data like this:

string 1: 003Preliminary Examination Plan    string 2: Coordination005   string 3: Balance1000sheet 

The output I expect is

string 1: 003 string 2: 005 string 3: 1000 

And I want to implement it in SQL.

like image 400
Avinash Mehta Avatar asked May 21 '13 10:05

Avinash Mehta


People also ask

How do I find only numbers 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 can I get only numbers from alphanumeric strings 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

First create this UDF

CREATE FUNCTION dbo.udf_GetNumeric (   @strAlphaNumeric VARCHAR(256) ) RETURNS VARCHAR(256) AS BEGIN   DECLARE @intAlpha INT   SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric)   BEGIN     WHILE @intAlpha > 0     BEGIN       SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' )       SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric )     END   END   RETURN ISNULL(@strAlphaNumeric,0) END GO 

Now use the function as

SELECT dbo.udf_GetNumeric(column_name)  from table_name 

SQL FIDDLE

I hope this solved your problem.

Reference

like image 50
Prahalad Gaggar Avatar answered Oct 20 '22 14:10

Prahalad Gaggar


Try this one -

Query:

DECLARE @temp TABLE (       string NVARCHAR(50) )  INSERT INTO @temp (string) VALUES      ('003Preliminary Examination Plan'),     ('Coordination005'),     ('Balance1000sheet')  SELECT LEFT(subsrt, PATINDEX('%[^0-9]%', subsrt + 't') - 1)  FROM (     SELECT subsrt = SUBSTRING(string, pos, LEN(string))     FROM (         SELECT string, pos = PATINDEX('%[0-9]%', string)         FROM @temp     ) d ) t 

Output:

---------- 003 005 1000 
like image 26
Devart Avatar answered Oct 20 '22 14:10

Devart