Sometime we need to pad leading zeros to numeric
values so that they can appear having same width
like 00001,0022,0934 etc.
Following code demonstrates the technique
to pad leading zeros in front of digits.
–Variable to hold max length
Declare @m_maxLength int
–Create a test table
Declare @m_testTable table (sampleValue int)
–Insert some sample values
Insert into @m_testTable values (1)
Insert into @m_testTable values (2)
Insert into @m_testTable values (19)
Insert into @m_testTable values (201)
Insert into @m_testTable values (20231)
–Calcualte the length of maximum number in the table
Select
@m_maxLength=Max(Len(convert(varchar,sampleValue)))
from @m_testTable
—Now select the values
Select
sampleValue,
Replicate(‘0′,@m_maxLength-Len(convert(varchar,sampleValue)))
+convert(varchar,sampleValue) as paddedValue
from @m_testTable