I prefer another method for determining if a date is on a Sunday.
The method that SQLScholar mentioned works well, but it depends on the datefirst setting. The default datefirst setting is based on the default language for your login. It looks like most of the world has a default datefirst of 7 (Germany, France, Spain, Italy, Croatia, Greece, Russia, England, etc...). The rest of the world has a default date setting of 1 (US, Japan, Portugal, Brazil, Korea, etc...).
You can see a full list by running this query:
[tt]Select * From sys.syslanguages[/tt]
There is another way to determine if a date falls on a Sunday, one that doesn't depend on the datefirst setting.
January 7, 1900 happens to be a Sunday.
Calculate the number of days between the TestDate and Jan 7, 1900.
Determine the remainder of integer division when dividing by 7. If the remainder is 0, your test date is a Sunday.
Take a look at this code:
Code:
Declare @Temp Table(TestDate DateTime)
Insert Into @Temp Values('20120708')
Insert Into @Temp Values('20120709')
Insert Into @Temp Values('20120710')
Insert Into @Temp Values('20120711')
Insert Into @Temp Values('20120712')
Insert Into @Temp Values('20120713')
Insert Into @Temp Values('20120714')
Select TestDate,
DatePart(Weekday,TestDate),
Case When DatePart(Weekday,TestDate) = 1
Then 1
Else 0
End As IsSunday,
Case When DateDiff(day, '19000107', TestDate) % 7 = 0
Then 1
Else 0
End As AnotherIsSunday
From @Temp
Set DateFirst 1
Select TestDate,
DatePart(Weekday,TestDate),
Case When DatePart(Weekday,TestDate) = 1
Then 1
Else 0
End As IsSunday,
Case When DateDiff(day, '19000107', TestDate) % 7 = 0
Then 1
Else 0
End As AnotherIsSunday
From @Temp
Set DateFirst 7
Select TestDate,
DatePart(Weekday,TestDate),
Case When DatePart(Weekday,TestDate) = 1
Then 1
Else 0
End As IsSunday,
Case When DateDiff(day, '19000107', TestDate) % 7 = 0
Then 1
Else 0
End As AnotherIsSunday
From @Temp
When you copy/paste this code to a query window and run it, you'll see that that the "IsSunday" values change based on the DateFirst setting, but the "AnotherIsSunday" does not depend on DateFirst.
I haven't tested, but I suspect the DatePart method may be slightly faster, but I doubt you'll notice a difference in performance. In my opinion, the "diff and mod" method performance nearly as well, but does not suffer from differences in language or datefirst settings, making it the better choice.
-George
Microsoft SQL Server MVP
My Blogs
SQLCop
twitter
"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom