?
Solved

Leading zeros conversion from int to char(4)

Posted on 2008-02-04
3
Medium Priority
?
1,391 Views
Last Modified: 2010-04-21
I wish to convert an integer to a decimal character array with leading zeroes using TSQL.

eg
declare @s1 char(4)
declare @n int
set @n = 2

<conversion code goes here>

print @s1

I expect to see an output of '0002'

0
Comment
Question by:alcindor
3 Comments
 
LVL 75

Accepted Solution

by:
Aneesh Retnakaran earned 2000 total points
ID: 20816283
SET @s1 = RIGHT( '0000' + cast(@n as varchar ) , 4 )
0
 
LVL 17

Expert Comment

by:Shanmuga Sundaram
ID: 20816362
Also can be used as (similar to above but with little change)

declare @s1 char(4)
declare @n int
set @n = 2
set @s1=RIGHT(REPLICATE('0',4)+CONVERT(varchar(7),@n),4)
print @s1

0
 
LVL 2

Author Closing Comment

by:alcindor
ID: 31427844
Thanks for the prompt reply, exactly what I needed.

Roger
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Windocks is an independent port of Docker's open source to Windows.   This article introduces the use of SQL Server in containers, with integrated support of SQL Server database cloning.
This shares a stored procedure to retrieve permissions for a given user on the current database or across all databases on a server.
Via a live example, show how to shrink a transaction log file down to a reasonable size.
Stellar Phoenix SQL Database Repair software easily fixes the suspect mode issue of SQL Server database. It is a simple process to bring the database from suspect mode to normal mode. Check out the video and fix the SQL database suspect mode problem.

589 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