Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the month and day with leading 0's in SQL? (e.g. 9 => 09)

Tags:

sql

tsql

DECLARE @day CHAR(2)  SET @day = DATEPART(DAY, GETDATE())  PRINT @day 

If today was the 9th of December, the above would print "9".

I want to print "09". How do I go about doing this?

like image 516
JJ. Avatar asked Dec 10 '12 15:12

JJ.


People also ask

How do I add leading zeros to a month in SQL?

SQL Server doesn't provide leading zeroes in a month selection, so you'll have to add them yourself. The easiest way to do this is probably to create a two- or three-digit string and taking a RIGHT() substring to select the rightmost two digits.

How do I get the month and day from a date in SQL?

The EXTRACT() function returns a number which represents the month of the date. The EXTRACT() function is a SQL standard function supported by MySQL, Oracle, and PostgreSQL. If you use SQL Server, you can use the MONTH() or DATEPART() function to extract the month from a date.


2 Answers

Pad it with 00 and take the right 2:

DECLARE @day CHAR(2)  SET @day = RIGHT('00' + CONVERT(NVARCHAR(2), DATEPART(DAY, GETDATE())), 2)  print @day 
like image 59
twoleggedhorse Avatar answered Oct 02 '22 13:10

twoleggedhorse


For SQL Server 2012 and up , with leading zeroes:

 SELECT FORMAT(GETDATE(),'MM')  

without:

SELECT    MONTH(GETDATE()) 
like image 45
Sajjan Sarkar Avatar answered Oct 02 '22 12:10

Sajjan Sarkar