Pad varchar with leading zeros

  • I have a varchar (5) filed that I would like to pad with leading zeros. The length of each entry is from 1-5 chars long. If the length is less than 5 I would like to pad it with zeros to make it 5 characters long. I am not sure how to do this. Thanks for any help

    Kevin-

    Thanks For your continued Help.


    Thanks For your continued Help.

  • Nevermind. I was able to develop the correct syntax. the below worked well when length of field is 3:

    update table_name

    set field_name = ('00'+field_name)

    where len(field_name) = 3

    Thanks For your continued Help.


    Thanks For your continued Help.

  • If you want a generic function you could do it like this:

     
    
    SET field_name = RIGHT(REPLICATE('0',5) + field_name,5)

    -Dan


    -Dan

  • Or

    REPLICATE('0', 5-LEN(field_name)) + field_name

  • This worked like a charm!

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply