Question

I'm trying to create custom week numbers and ranges based on user entered Week Start Day.

I'm passing that User defined day with SET Datefirst = @Userdefinedvalue (using a function to map my weekday start values to T-SQL's). Also I have a function to gets me the last day of the current week.

What is the best approach for this?

My Goal is: if I select Tuesday as my start day of the week the Stored Procedure to generate my week numbers and start/end dates based on my selection for the entire year

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top