Pad a string with leading zeros in SQL Server

The problem is:-

I have a string that is up to 5 characters long when its first created in SQL Server 2008 R2.
I would like to pad it with leading zeros, so if its original value was '1' then new value would be '00001' Or if its original value was '23' the new value is '00023' OR if its original value is '12345' then new value is the same as original value.
Solution is:-
If the field is already a string, this will work
 SELECT RIGHT('00000'+ISNULL(field,''),5)
If you want nulls to show as '00000'
It might be an integer -- then you would want
 SELECT RIGHT('00000'+CAST(field AS VARCHAR(5)),5) 
OR
SELECT REPLACE(STR(field ,5),' ','0')
Reference taken from StackOverFlow.

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form