Remove Leading Zeros and Alphabetic Characters using PATINDEX

Rajnilari2015
Posted by Rajnilari2015 under Sql Server category on | Points: 40 | Views : 800
In this scenario, our objective is to remove the Leading Zeros and Alphabetic Characters from a string using PATINDEX

DECLARE @somevalue VARCHAR(50) = '0000abcdef1234590789005'; --set the initial value  // 'xyz0000abcdef1234590789005';

DECLARE @nonZeroPosition INT -- variable to store the occurance of first non zero value position

SELECT @nonZeroPosition = PATINDEX('%[^[0a-z]%',@somevalue) -- This pattern ensures the search position should encounter a non-zero value in the entire string

SELECT RemoveLeadingZerosAndAlphabets = SUBSTRING(@somevalue,@nonZeroPosition,(LEN(@somevalue)-(@nonZeroPosition - 1))) --Extract the needed substring.


RemoveLeadingZerosAndAlphabets
----------------------
1234590789005

Comments or Responses

Login to post response