Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better techniques for trimming leading zeros in SQL Server?

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.

like image 874
Cade Roux Avatar asked Mar 19 '09 14:03

Cade Roux


People also ask

How do I remove zeros from a number in SQL?

SELECT CEIL((AVG(salary)) - (AVG(REPLACE(salary, '0', '')))) AS avg_salary FROM employees; REPLACE() : used to remove 0 from salary. AVG() : used to calculate average salary.

Which functions will help trim leading spaces in SQL?

SQL Server TRIM() Function The TRIM() function removes the space character OR other specified characters from the start or end of a string. By default, the TRIM() function removes leading and trailing spaces from a string. Note: Also look at the LTRIM() and RTRIM() functions.


1 Answers

SUBSTRING(str_col, PATINDEX('%[^0]%', str_col+'.'), LEN(str_col)) 
like image 95
Arvo Avatar answered Sep 21 '22 22:09

Arvo