Home > SQL Server 2005 > how to convert an integer to string and left pad it with zero’s?

how to convert an integer to string and left pad it with zero’s?

Here’s a quick and simple way of converting an integer to string (varchar) and left pad it with leading zeros like 00012. This example will get the result in 5 digits

select right(‘00000′ + cast(yourfield as varchar(5)), 5)

  1. November 20, 2008 at 4:49 pm | #1

    Nice!

    I`l use it in my tree sort stuff, like

    update #Tree
    set ObjectSortExpression = stuff(ObjectSortExpression, (ObjectLevel-1)*5 + 1, 5, cast(ObjectNumber as char(5)))
    where ObjectType = ‘Station’

    That require replace of cast(ObjectNumber as char(5) into your variant

  2. James Bower
    September 7, 2009 at 9:28 pm | #2

    Great blog, reading it through RSS feed as well

  1. No trackbacks yet.