Friday, April 17, 2009

Add leading zeros to a number in a MS SQL query

To add leading '0's to a column when length is less than 5


SELECT CASE WHEN LEN(rtrim(COLUMN)) < 5 THEN REPLICATE('0', 5 - LEN(rtrim(COLUMN))) + rtrim(COLUMN) ELSE rtrim(COLUMN) END

OR

SELECT RIGHT('00000' + RTRIM(COLUMN), 5)

OR

SELECT RIGHT(REPLICATE('0',5) + CONVERT(varchar( 6 ) , 1.2) ,5)