Thursday 5 December 2013

Getting number from alphanumeric string in SQL Server

 Suppose ,
            We have string which is containing numbers,character,special character.Requirement is we want only numbers .We don't want characters ,special character etc.I created function which will only return  number.

Create function fnOnlyNumbers(@Value varchar(255))
 returns varchar(255)
 begin
 if PATINDEX('%[0-9]%',@Value)>0
 begin
 while  isnumeric(@Value)=0
 begin
 set @Value=ltrim(rtrim(REPLACE(REPLACE (@Value, SUBSTRING (@Value ,PATINDEX ( '%[!@#$a-z`?><.,/A-Z() *&]%' , @Value ),1),'') ,' ','')))
 end
 end
 return  case when  isnumeric(@Value)=1 then   @Value else Null end
 end


How to run :
select dbo.fnOnlyNumbers('sss1$2>>34 ')
Output : 1234

Note : If we are not passing any value then we will get Null value.




No comments:

Post a Comment

First Database In Sql Server