-1
   >=DateAdd("ww",-9,Date()-Weekday(Date(),0)+1))

I have the above function in some SQL coding that I have inherited and am struggling to work out what it is actually calculating can anyone help?

T Steele
  • 1
  • 1

1 Answers1

1

Consider this SQL with the statement deconstructed into parts.
It was tested in sql-server 12, and uses the GETDATE() instead of the Date() function.

select 
GETDATE() as today, 
@@DATEFIRST as first_day_of_the_week_number,
DATEPART(WEEKDAY,GETDATE()) as current_day_number_of_the_week, 
GETDATE()-DATEPART(WEEKDAY,GETDATE()) as previous_saturday, 
GETDATE()-DATEPART(WEEKDAY,GETDATE())+1 as previous_sunday,
DATEADD("ww",-9,GETDATE()-DATEPART(WEEKDAY,GETDATE())+1) as previous_sunday_9_weeks_back;

So it would give the sunday of 9 weeks back.

Note that it assumes that @@DATEFIRST equals 7.
If @@DATEFIRST equals 1 then it would return the monday of 9 weeks back.

LukStorms
  • 28,916
  • 5
  • 31
  • 45
  • 2
    That actually depends entirely on the value of [`@@DATEFIRST`](https://msdn.microsoft.com/library/ms187766). (But the `WeekDay` function is likewise ambiguous with a second argument of `0`.) – Jeroen Mostert Jun 01 '16 at 10:29
  • @Jeroen Wasn't aware of that t-sql quirck. Thanks for the insight. – LukStorms Jun 01 '16 at 11:19