Given month number, how will you get month name in SQL Server without using CASE statement?

 Posted by Niladri.Biswas on 7/19/2012 | Category: Sql Server Interview questions | Views: 2461 | Points: 40

We can use the DATENAME function for accomplishing the task.This function is used to
return a single string part of a date/time.

The general syntax is :
DATENAME ( datepart , date )

So if we specify the datepart as month number, we will get the month name component from this function.

Now, given any month number, we will first construct the first day of the month as under

CAST('10' + '/1/1900' AS DATETIME)

where 10 is month number

So, since we have now constructed the date, now we can easily apply the DATEPART function to obtain the month number

DECLARE @MonthNumber INT = 10

SELECT [Month Name] = DATENAME(MONTH,CAST('10' + '/1/1900' AS DATETIME))

/* Result */
Month Name

Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response