tags:

views:

6118

answers:

2

I am working on a SQL query that reads from a SQLServer database to produce an extract file. One of the requirements to remove the leading zeroes from a particular field, which is a simple VARCHAR(10) field. So, for example, if the field contains '00001A', the SELECT statement needs to return the data as '1A'.

Is there a way in SQL to easily remove the leading zeroes in this way? I know there is an RTRIM function, but this seems only to remove spaces.

+6  A: 
select substring(ColumnName, patindex('%[^0]%',ColumnName), 10)
Ian Horwill
This will have problems when the string is entirely made up of "0", since it will never match a non-"0" character.
Cade Roux
True. It will return all the unmodified string of zeros in this case. If this is a problem, the return value of patindex will have to be tested against zero.
Ian Horwill
A: 

Will your data always need to be stripped of the leading zeros? If so it would be more efficient interms of performance to fix the data in the table and when it is entered or imported than to run a function in every select.

HLGEM