Does SQL have a function that returns the weekday of a date? In MS Access Weekday(1/26/07) will return 6. Is there something similar in SQL?
thanks! so it's DATEPART(dw,'date')
Play it safe - wherever you are in the World! Whenever I deal with datepart(dw,...) I capture what it returns for a known date and take it from there. For example:
declare @dowSat intdeclare @dowSun int-- capture these for known dates as they may vary based on SET DATEFIRSTset @dowSat=datepart(dw,'2006-10-28')set @dowSun=datepart(dw,'2006-10-29')
If you then want to check a date for a Saturday or Sunday you compare it with @dowSat or @dowSun.
The value that datepart(DW,MyDate) returns depends on the setting of datefirst.
This code will always return a value of 0 for Monday, 1 for Tuesday,..., 6 for Sunday, no matter what the setting of datefirst is.
If you want your week to start with 0 for Sunday, 1 for Monday, etc., use this:
If you want the weekdays to be numbered from 1 to 7, instead of 0 to 6, add 1 to the results above:
"This code will always return a value of 0 for Monday, 1 for Tuesday,..., 6 for Sunday, no matter what the setting of datefirst is."
Why would BOL seem to refute what you are saying?
The week (wk, ww) datepart reflects changes made to SET DATEFIRST. January 1 of any year defines the starting number for the week datepart, for example: DATEPART(wk, 'Jan 1, xxxx') = 1, where xxxx is any year.
The weekday (dw) datepart returns a number that corresponds to the day of the week, for example: Sunday = 1, Saturday = 7. The number produced by the weekday datepart depends on the value set by SET DATEFIRST, which sets the first day of the week.
That is the point of the code I posted. Since it doesn't use the DATEPART function, the setting of DATEFIRST has no effect on it.
It finds the day of the week by calculating the difference in days between 1753-01-01 and your date, and then using that result finding the modulus of 7. Since 1753-01-01 is a Monday, the modulus will return a 0 for Monday, 1 for Tuesday, through a 6 for Sunday.
I guess I just know because it is the very first date that SQL Server supports, and I only had to look it up one time.
In any case, DATENAME(dw,'17530101') would be a better built in function, since it also does not depend of the setting of datefirst. DATENAME does depend on the language setting though.