;

3 Ways to Get or Extract the Month From a Date in SQL Server


Tutorialsrack 22/02/2021 SQL SQL Server

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.

MONTH() Function

This function is used to extract the Month from a Date. And this function takes the one parameter which is the Date.

Example - MONTH() Function in SQL Server
DECLARE @date date = '2021-2-22';
SELECT MONTH(@date) as 'Month';
Output

Month

-----------

2

DATEPART()Function

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.

Example - DATEPART()Function in SQL Server
DECLARE @date date = '2020-10-25';
SELECT DATEPART(month, @date);
Output

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.

Example - DATEPART() FUNCTION in SQL Server
DECLARE @date date = '2021-2-22'
SELECT 
  DATEPART(month, @date) AS month,
  DATEPART(mm, @date) AS mm,
  DATEPART(m, @date) AS m;
Output

month       mm          m

----------- ----------- -----------

2           2           2

 

FORMAT() Function

In SQL Server 2012, the FORMAT() function is introduced which is used to format a value with the specified format.

Example - FORMAT() Function in SQL Server
DECLARE @date date = '2021-2-22';
SELECT FORMAT(@date, 'MM')  as 'Month';
Output

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!


Related Posts



Comments

Recent Posts
Tags