The idea is to find the first day of the week. First, use SQL Server built in functions to move the start of the week to the Sunday (in the US) by subtracting datepart(wd)
. Actually datepart(wd)
returns values form 1 to 7 and we want them 0 to 6.
Then, add back in an offset based on your date of the week. Here is example code:
declare @offset int (case when @DateFirst = 'Mon' then 1
when @DateFirst = 'Tue' then 2
...
when @DateFirst = 'Sun' then 0
end);
select dateadd(dd, @offset - (datepart(wd, thedate) - 1)
thedate) as WeekStartDate