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?
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.
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.
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
For SQL Server 2012 and up , with leading zeroes:
SELECT FORMAT(GETDATE(),'MM')
without:
SELECT MONTH(GETDATE())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With