Tuesday, December 25, 2012

SQL Query: Removing Zero's

Today, we would consider a scenario of removing ZERO's from left side present in the column for one SQL Table.

Consider we are having following data in the table:


Select * from
[dbo].[RemoveZero]

Result:


Column1
0001
000100
100100
000 0001
00.001
01.001




and following is the result we are looking for:


Column1
1
100
100100
1
.001
1.001

So, how to do this? 
We can achieve the above result by using REPLACE and TRIM functionality

Below is the query which would produce the above result:

Select replace(ltrim(replace(numcol,'0',' ')),' ' ,'0') from 
[dbo].[RemoveZero]

So ,if you see:
a) We are replacing '0' with space by using Replace function
b) Then we are using LTRIM function as it would only Left trim the spaces from Left side
c) Then we are again replacing the spaces with Zero's , so this would bring back the zero anywhere already present.

Hope you would have liked this scenario.

No comments:

Post a Comment