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


get Month from a date field as 00 format.

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


Sometimes we need to fetch the month field from a date time with a sql query. At that time we use the datepart method of sql.
But it gives us the result like 1,2,3,4....

Suppose we need to get the result as 01,02,03,04.... Then we can use right method with replicate or simple right method to do so.
Take a look on the following sql query which give the proper result.


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


or



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


Output :


01
02
03
04
....

Thank You.

Reference: http://msahoo.wordpress.com/2010/05/12/how-to-get-the-result-as-00-format-for-month-or-date-of-a-date-from-sql/


Article by Manoranjan Sahoo
If it helps you then Rate this. Best Regards, Manoranjan Sahoo http://www.dotnetsquare.com Blog: http://blog.msahoo.net

Follow Manoranjan Sahoo or read 63 articles authored by Manoranjan Sahoo

Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: