1

I have this query, which returns days of the week. The days of the week are 0-6(Mon-Fri).

select ID, DayOfWeek from MyTable

ID    DayOfWeek
1     0
2     0
3     4

Is there a way to substitute an alias for each int DayOfWeek? The enum isn't stored in the database so I can't join.

I want to be able to write a query and have it look like this:

ID    DayOfWeek
1     Monday
2     Monday
3     Friday
RJP
  • 4,016
  • 5
  • 29
  • 42

4 Answers4

8

You should consider storing the lookup in a new table... but just so you're aware of your options, you can also use the DATENAME(WEEKDAY) function:

SELECT DATENAME(WEEKDAY, 0)

Returns:

Monday

SQL Fiddle

Michael Fredrickson
  • 36,839
  • 5
  • 92
  • 109
2

If you can't store a table to join on, you can use a CASE:

SELECT ID,
    CASE DayOfWeek
        WHEN 0 THEN 'Monday'
        WHEN 1 THEN 'Tuesday'
        ...
    END AS DayOfWeek
FROM MyTable
lc.
  • 113,939
  • 20
  • 158
  • 187
2

You can try following:

SELECT ID, DATENAME(dw, DATEADD(d, DayOfWeek, CAST('2013-08-05' AS date)))
FROM MyTable

The logic is:

  1. Take a date you're sure is Monday ('2013-08-05' is)
  2. Add DayOfWeek days to that date
  3. Take DATENAME(dw) from that date

Edit

Or even simpler way: DATENAME(dw, DayOfWeek): Live demo

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
1
datename(weekday, DayOfWeek) 

should translate the int to a name.

Ryan
  • 414
  • 1
  • 5
  • 16