02 January 2007

How to Pad Left a number?

Padding left a number using SQL Server is implemented using the REPLICATE TSQL function.
Here is an example to format a date:
DECLARE @Date VARCHAR(8)
SET @Date = CAST(YEAR(GETDATE()) AS VARCHAR(4))
SET @Date = @Date + REPLICATE('0', 2 - DATALENGTH(CAST(MONTH(GETDATE()) as VARCHAR))) + CAST(MONTH(GETDATE()) as VARCHAR) 
SET @Date = @Date + REPLICATE('0', 2 - DATALENGTH(CAST(DAY(GETDATE()) as VARCHAR))) + CAST(DAY(GETDATE()) as VARCHAR) 
SELECT @Date


Create a SQL Server function for padleft and padright and you job will be simplefied. Here is a good place to start.

1 comment:

Anonymous said...

Awesome! Just what I needed. Most tips on "padding" assume you want a predetermined number of 0's or whatever, but your tip on using REPLICATE lets you establish the total number of digits, and it pads left until you get that number.