Here are three T-SQL functions that you can use to extract the month from a date in SQL Server.
MONTH()
The most obvious function to use is the MONTH()
function. This function accepts one argument: the date.
DECLARE @date date = '2020-10-25';
SELECT MONTH(@date);
Result:
10
DATEPART()
The DATEPART()
function accepts two arguments: the first argument is the part of the date that you want to extract, and the second argument is the actual date that you want to extract it from.
DECLARE @date date = '2020-10-25';
SELECT DATEPART(month, @date);
Result:
10
In this example I used month
as the first argument. You also have the option of using mm
or m
. Whichever one you use, the result is the same.
DECLARE @date date = '2020-10-25'
SELECT
DATEPART(month, @date) AS month,
DATEPART(mm, @date) AS mm,
DATEPART(m, @date) AS m;
Result:
+---------+------+-----+ | month | mm | m | |---------+------+-----| | 10 | 10 | 10 | +---------+------+-----+
FORMAT()
The FORMAT()
function can also be used to return the month.
DECLARE @date date = '2020-10-25';
SELECT FORMAT(@date, 'MM');
Result:
10
You can alternatively use MMMM
to return the full month name, or MMM
to return the short month name.