This may be excessively complicated, but it was tons of fun.
--This first part is to get the most recently occurred monday.
--It starts by creating a table which will hold all dates until the most recent monday, then sets the min of that 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 to the 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)