Thursday, January 28, 2010

Leading zeros in tsql

select right ('StringOfZerosAsManyAsMaxNeededMoreIsOK'
+ cast ( AnIntegerLiteralOrIntVariable as varchar)
, IntLiteralWhichIsTotalLengthOfNeededString)

declare @counter int
set @counter = 126
select right ('000000' + cast ( @counter as varchar) , 6 )

result:
000126


declare @counter int
set @counter = 12345678
select right ('000000000' + cast ( @counter as varchar) , 6 )

result:
345678



declare @counter int
set @counter = 123
select right ('00' + cast ( @counter as varchar) , 6 )

result:
00123



declare @counter int
set @counter = 123
select right ('0000' + cast ( 123 as varchar) , 9 )

result:
000126

No comments:

Post a Comment