29 May 2006 11:31
tonyrogerson
Padding a string with leading zeros
I've need to do this a lot of times when outputing a fixed length data export where for instance a numeric column is 9 characters long and you need to prefix with leading 0's. This type of data export dates back to PL/1, COBOL era.
For a two character string you can do this...
declare
@number tinyint
set
@number = 2
select
case when len( @number ) = 1 then '0' else '' end + cast( @number as varchar(2) )
For a number that will be greater than two characters in length you can do this...
declare
@number int
declare @string varchar(10)
declare @size_of_fixed_string tinyint
set
@size_of_fixed_string = 10
set @number = 40
print
replicate( '0', @size_of_fixed_string )
set
@string = left( replicate( '0', @size_of_fixed_string ), @size_of_fixed_string - len( @number ) ) + cast( @number as varchar(10) )
print
@string
Filed under: SQL Server