mjyazdani
mjyazdani

Reputation: 2035

How can I get the month number (not month name) from a date in SQL Server?

How can I get the month number in sql? I use the following code but it returns the month name.

SELECT DATENAME(mm, GETDATE())

Upvotes: 35

Views: 110148

Answers (8)

Raman Mehta
Raman Mehta

Reputation: 1

We can use the SQL Function: MONTH(DATE) as a parameter. It will return the month number.

Upvotes: -3

ExplodingPony
ExplodingPony

Reputation: 57

You can also use this to pad the month number

SELECT RIGHT('00' + RTRIM( CAST( DATEPART( MONTH, GETDATE() ) AS varchar(2)) ) , 2)

Upvotes: 3

Sunil
Sunil

Reputation: 1

This will return with two char in case of Jan-Sep:

SELECT CASE WHEN LEN(MONTH(GETDATE())) = 1 THEN '0' + CAST(MONTH(GETDATE()) AS VARCHAR(2)) 
WHEN LEN(MONTH(GETDATE())) = 2 THEN CAST(MONTH(GETDATE()) AS VARCHAR(2)) END

Upvotes: 0

Vishwanath Dalvi
Vishwanath Dalvi

Reputation: 36621

Use datepart function with m extension.

SELECT DATEPART(m, getdate())

Upvotes: 51

Paul J
Paul J

Reputation: 476

Use the month function - SELECT MONTH(GETDATE())

Upvotes: 16

CloudyMarble
CloudyMarble

Reputation: 37566

Use Datepart:

DATEPART(mm,getdate());

Upvotes: 4

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26737

Try the below:

SELECT DATEPART(mm,getdate())

Upvotes: 2

Daniel Kelley
Daniel Kelley

Reputation: 7737

You want DATEPART:

select datepart(mm, getdate())

Upvotes: 3

Related Questions