Login or Sign Up to become a member!
LessThanDot Sit Logo

LessThanDot

Community Wiki

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.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot friendfeed Lessthandot facebook Lessthandot rss

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

Navigation

Google Ads

Trim Leading Zeroes

From Wiki

Jump to: navigation, search

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.

  1. DECLARE  @t  TABLE(
  2.                    ColZeroes VARCHAR(30)
  3.                    )
  4.  
  5. INSERT INTO @t
  6. SELECT '0000123456_PF_20110531_P_F'
  7. UNION ALL
  8. SELECT '0001234567_PF_20110531_P_F'
  9. UNION ALL
  10. SELECT 'This does not have'
  11.  
  12. SELECT ColZeroes,
  13.        CASE
  14.          WHEN PATINDEX('%[^0]%',ColZeroes) > 0 THEN SUBSTRING(ColZeroes,PATINDEX('%[^0]%',ColZeroes),LEN(ColZeroes))
  15.          ELSE ColZeroes
  16.        END
  17. FROM   @t

818 Rating: 2.9/5 (7 votes cast)