views:

275

answers:

2

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.

+1  A: 

Check out TRIM function http://www.1keydata.com/sql/sql-trim.html

SELECT TRIM(LEADING '0' FROM fieldWithLeadingZeroes)
Draco Ater
Cool. It doesn't seem to work, though - I get a syntax error. Is this a newer feature of SQL...? I'm using SQL Server 2005
froadie
MS-SQL does not support SQL99 Syntax for this; should work for the other sql server types, though
John
I also tried it with SQL Server and it did not work. It is supported in another DBMS I just now tried, though.
Mark Wilkins
No use for SQL Server. Uncool
gbn
@Mark Wilkins - which? (just out of interest)
froadie
@froadie: It is Advantage Database Server. I am one of the developers on it (bias alert). The ironic thing is that I didn't realize we supported this particular syntax of TRIM until I looked at this question.
Mark Wilkins
+7  A: 

Find 1st non-zero character, substring to end (can put 2 billion for max types)

LTRIM is optional, really

DECLARE @MyVar varchar(8000)

SET @MyVar = '000foobar'
SELECT LTRIM(SUBSTRING(@MyVar, PATINDEX ('%[^0]%', @MyVar), 8000))
SET @MyVar = '000000  oh my lord'
SELECT LTRIM(SUBSTRING(@MyVar, PATINDEX ('%[^0]%', @MyVar), 8000))
gbn
Wow. Nice. Thanks... I could never have come up with this myself, I'm still scared of patterns and regular expressions. :)
froadie
PATINDEX/LIKE is quite simple compared to RegEx...
gbn