Tom
Tom

Reputation: 1373

Get month numbe passing only month name

I want to get the month no when I only knows month name. (If month name January should return 1)

I tried this.

SELECT DATEPART(MM,'january 01 2011')

But here I want to pass whole date value(january 01 2011). But I only need to pass month name. (Without using 'Case')

Is there any way to do this?

Upvotes: 4

Views: 361

Answers (3)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

You can pass month name and append 01 2011 (or whatever other day + year you wish) to it, like this:

@declare monthName varchar(20);
@set monthName = 'january';

SELECT DATEPART(MM,monthName+' 01 2011')

or

SELECT MONTH(monthName+' 01 2011')

Upvotes: 5

Dhaval
Dhaval

Reputation: 2379

@declare monthName varchar(20);
@set monthName = 'JUNE';

SELECT DATEPART(MM,monthName+' 01 2014') //Monthname +'any date and year'

Upvotes: 0

Pரதீப்
Pரதீப்

Reputation: 93694

you can also use Case

DECLARE @month VARCHAR(15)='mar'

SELECT CASE @month
         WHEN 'Jan' THEN 1
         WHEN 'feb' THEN 2
         WHEN 'mar' THEN 3
         WHEN 'apr' THEN 4
         WHEN 'may' THEN 5
         WHEN 'jun' THEN 6
         WHEN 'jul' THEN 7
         WHEN 'aug' THEN 8
         WHEN 'sep' THEN 9
         WHEN 'oct' THEN 10
         WHEN 'nov' THEN 11
         WHEN 'dec' THEN 12
       END 

Upvotes: 0

Related Questions