Extract only numbers from a String in Sqlserver.

Hi all, Sometimes we have situation like when our required data (numeric) is part of the string and to process further we have to extract it first from the string. In this article I am trying to explain how to extract only numeric values from the string in sqlserver.

Logic: logic is quite simple. We will loop till the end of the string and take one character of the string at a time and check whether it is numeric or not, if it is than it is part of out required data, else move forward.

DECLARE @str nvarchar(100),@len int,@result nvarchar(100)

DECLARE @next int

set @str=’gy3k67mplw01A46bru9tf87′

SET @len=LEN(@str)

SET @result = ”

SET @next=3

 

WHILE(@len > 0)

      BEGIN

            set @result = @result + (SELECT case when SUBSTRING(@str,@next,1) LIKE ‘[0-9]’ THEN SUBSTRING(@str,@next,1) ELSE ” end)

            set @next = @next + 1

            set @len = @len – 1

      end

SELECT @result

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s