It can be overly complicated, but it was fun.
- This first part is to get the last time on Monday.
- starts by creating a table that will contain all dates until the last Monday, and then sets the min of this table to the @mondaythisweek variable.
declare @dateholder table ( thedate date, theday varchar(10) ) declare @now datetime set @now = GETDATE() ;with mycte as ( select cast(@now as date) as "thedate", DATENAME(dw,@now) as "theday" union all select cast(DATEADD(d,-1,"thedate") as date) as "thedate", DATENAME(DW,DATEADD(d,-1,"thedate")) as "theday" from mycte where "theday" <> 'Monday' ) insert into @dateholder select * from mycte option (maxrecursion 10) declare @mondaythisweek date set @mondaythisweek = ( select min(thedate) from @dateholder )
- This part creates a table from @mondaythisweek until next Sunday.
;with mon_to_sun as ( select @mondaythisweek as "dates", DATENAME(dw,@mondaythisweek) as "theday" union all select cast(DATEADD(d,1,"dates") as date) as "dates", DATENAME(dw,cast(DATEADD(d,1,"dates") as date)) as "theday" from mon_to_sun where "theday" <> 'Sunday' ) select * from mon_to_sun option(maxrecursion 10)
user38858
source share