Format int to varchar in a specific way

Posted on 2012-09-10
Last Modified: 2012-09-10
Hey, I have an int field that has values between 0 and 9999.  I want to convert it to a varchar(4) so that values less than 1000 appear with leading zeroes.  For example, a value of 25 would appear 0025 or 789 would appears as 0789.  I want to do this in a select statement.  Thanks.
Question by:MariaHalt
    LVL 65

    Accepted Solution

    Give this a whirl.  Test in SSMS by changing the @int value to anything you want, then once you're satisfied modify your code.

    Declare @int int = 123

    SELECT RIGHT('0000' + Cast(@int as varchar(10)),4)

    Author Closing Comment

    Perfect!  Thank you.
    LVL 65

    Expert Comment

    by:Jim Horn
    Thanks for the grade.  Good luck with your project.  -Jim

    Featured Post

    Highfive + Dolby Voice = No More Audio Complaints!

    Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

    Join & Write a Comment

    In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
    Entering time in Microsoft Access can be difficult. An input mask often bothers users more than helping them and won't catch all typing errors. This article shows how to create a textbox for 24-hour time input with full validation politely catching …
    This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function
    Via a live example, show how to setup several different housekeeping processes for a SQL Server.

    728 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now