Convert Month Number to Month Name in SQL Server

One of my blog readers mailed me asking a simple way to convert a month number to month name. Here’s the simplest way in my opinion:

DECLARE @Mth smallint
SET
@Mth = 11
SELECT DateName(mm,DATEADD(mm,@Mth,-1)) as [MonthName]

OUTPUT

image

Similarly if you want to list all the month names for a year using a T-SQL statement, you can do this:

SELECT Number + 1 as [MonthNumber],
DateName(mm,DATEADD(mm,Number,0)) as [MonthName]
FROM master..spt_values
WHERE Type = 'P' and Number < 12

OUTPUT

image

5 comments:

  1. Another method


    DECLARE @Mth smallint
    SET @Mth = 11
    select datename(month,'2000'+cast(@Mth as char(2))+'01')


    Madhivanan

    http://beyondrelational.com/blogs/madhivanan

    ReplyDelete
  2. I try like explanation above to get month name uset datename function and ok.
    thank a lot for it.

    see it on my sql tutorial

    ReplyDelete
  3. thanks it worked for me.

    ReplyDelete
  4. Thanks a lot , that works perfect

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete