Better techniques for trimming leading zeros in SQL Server?

Cade Roux picture Cade Roux · Mar 19, 2009 · Viewed 281k times · Source

I've been using this for some time:

SUBSTRING(str_col, PATINDEX('%[^0]%', str_col), LEN(str_col))

However recently, I've found a problem with columns with all "0" characters like '00000000' because it never finds a non-"0" character to match.

An alternative technique I've seen is to use TRIM:

REPLACE(LTRIM(REPLACE(str_col, '0', ' ')), ' ', '0')

This has a problem if there are embedded spaces, because they will be turned into "0"s when the spaces are turned back into "0"s.

I'm trying to avoid a scalar UDF. I've found a lot of performance problems with UDFs in SQL Server 2005.

Answer

Arvo picture Arvo · Mar 19, 2009
SUBSTRING(str_col, PATINDEX('%[^0]%', str_col+'.'), LEN(str_col))