In this article, you will learn how to get or extract the months from a date in SQL Server(T-SQL). Here in this article, we are doing this in 3 ways to extract the month from a date. We are using the MONTH(), DATEPART(), FORMAT() functions to get or extract the month from a date in SQL Server.
Here are the examples to get or extract the date from the date in SQL Server.
This function is used to extract the Month from a Date. And this function takes the one parameter which is the Date.
DECLARE @date date = '2021-2-22';
SELECT MONTH(@date) as 'Month';
Month
-----------
2
This function returns a specified part of a date. And this function returns an output as an integer value. This function takes the two parameters: the first parameter is interval and the second parameter is the Date. Both parameters are required.
DECLARE @date date = '2020-10-25';
SELECT DATEPART(month, @date);
Month
-----------
2
In the above example, I used the month as an interval. You also have the other options like mm, m, etc., and the output will be the same. You can see this in the below given example.
DECLARE @date date = '2021-2-22'
SELECT
DATEPART(month, @date) AS month,
DATEPART(mm, @date) AS mm,
DATEPART(m, @date) AS m;
month mm m
----------- ----------- -----------
2 2 2
In SQL Server 2012, the FORMAT() function is introduced which is used to format a value with the specified format.
DECLARE @date date = '2021-2-22';
SELECT FORMAT(@date, 'MM') as 'Month';
Month
-----------
2
You can alternatively use MMMM with the FORMAT() function to get the full month name, or MMM to get the short month's name.
I hope this article will help you to understand how to get or extract the months from a date in SQL Server(T-SQL).
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments