There was a question in the SQL forums that the user wanted to remove leading zeroes in the numbers from a varchar column. The column will have numbers, alphabets or alpha-numeric strings. Only numbers should be considered for removing the leading zeroes.
Consider the following set of data
create table #data (data varchar(10))
insert into #data
select '12345' as data union all
select '00123' as data union all
select '000A1' union all
select '00D21' union all
select '00021' union all
select 'ANPJH' union all
select '20000' union all
select '00E33'
There are two methods that I know
Method 1 : Use regular expression to find only the numbers and remove leading zeroes
select
data as before,
case when data not like '%[^0-9]%' then cast(cast(data as int) as varchar(10)) else data end as after
from
#data
Method 2 : Use Try_convert() function to find only the numbers and remove leading zeroes select
data as before,
case when try_convert(int,data) is not null then cast(cast(data as int) as varchar(10)) else data end as after
from
#data
Both the queries return the following set of data
before after
---------- ----------
12345 12345
00123 123
000A1 000A1
00D21 00D21
00021 21
ANPJH ANPJH
20000 20000
00E33 00E33
Note: Method 1 will work in all versions whereas method 2 works from version 2012 onwards