How to get the result as 00 format for month or date of a datetime from SQL?


One day i need to fetch the month part of a date field of my sql database. i tried the following code to get the month part :

select datepart(MONTH,[Date]) from tablename

but it gives the result as :


But I need as 01,02,03….

so I change the sql syntax as below :

SELECT RIGHT(REPLICATE('0', 2) + CAST(datepart(MONTH,[Date]) AS VARCHAR(2)), 2) FROM Tablename

or you can use simple :

SELECT RIGHT('0' + convert(varchar(2),datepart(MONTH,[Date])), 2) FROM <TableName>

it gives me the correct result…

Thank You.

How useful was this post?

Click on a star to rate it!

Leave a Reply

Your email address will not be published. Required fields are marked *