Format int to varchar in a specific way

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.
MariaHaltAsked:
Who is Participating?
 
Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
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)
0
 
MariaHaltAuthor Commented:
Perfect!  Thank you.
0
 
Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
Thanks for the grade.  Good luck with your project.  -Jim
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.