Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.
Trim Leading Zeroes
From Wiki
One of the top asked question in SQL Server forums is how to strip leading zeroes from a character field.
The Ten Most Asked SQL Server Questions And Their Answers blog has this question (9) answered. I want to present a different answer.
The code below demonstrates the use of PATINDEX function to search for first non-0 character in a field.
- DECLARE @t TABLE(
- ColZeroes VARCHAR(30)
- )
- INSERT INTO @t
- SELECT '0000123456_PF_20110531_P_F'
- UNION ALL
- SELECT '0001234567_PF_20110531_P_F'
- UNION ALL
- SELECT 'This does not have'
- SELECT ColZeroes,
- CASE
- WHEN PATINDEX('%[^0]%',ColZeroes) > 0 THEN SUBSTRING(ColZeroes,PATINDEX('%[^0]%',ColZeroes),LEN(ColZeroes))
- ELSE ColZeroes
- END
- FROM @t



LTD Social Sitings
Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.