Monday, September 1, 2008

SQL - add zeros to the left

Ever needed to add zeros to the left of your string?
For example: instead of "1", you need "0001" displayed.
All this from SQL ...

I think this is an easy way of doing that:





select replicate('0', 6-len(convert(varchar(50), 'aaa'))) + convert(varchar(50), 'aaa')





You need to change the '6' if longer, and 'aaa' is your string ...

what do you think?
comment!

3 comments:

Gops said...

Thanks for this tip. This was very useful.

Anonymous said...

another way is :
select right(cast('000' as varchar(3))+cast('aa' as varchar(4)),4)

Unknown said...

Very useful tip. Thanks a lot

sureshrw