Algorithms to trim leading zeroes from a SQL field?

Posted by froadie on Stack Overflow See other posts from Stack Overflow or by froadie
Published on 2010-03-16T19:51:19Z Indexed on 2010/03/16 20:01 UTC
Read the original article Hit count: 315

Filed under:
|
|
|

I just came across the interesting problem of trying to trim the leading zeroes from a non-numeric field in SQL. (Since it can contain characters, it can't just be converted to a number and then back.)

This is what we ended up using:

SELECT REPLACE(LTRIM(REPLACE(fieldWithLeadingZeroes,'0',' ')),' ','0')

It replaces the zeroes with spaces, left trims it, and then puts the zeroes back in. I thought this was a very clever and interesting way to do it, although not so readable if you've never come across it before.

Are there any clearer ways to do this? Any more efficient ways to do this? Or any other ways to do this period? I was intrigued by this problem and would be interested to see any methods of getting around it.

© Stack Overflow or respective owner

Related posts about sql

Related posts about sql-server