Questo potrebbe essere eccessivamente complicato, ma è stato divertente.
- Questa prima parte è per ottenere l'ultimo lunedì.
- Inizia creando una tabella che manterrà tutte le date fino al lunedì più recente, quindi imposta il minimo di tale tabella sulla variabile @mondaythisweek.
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
)
--Questo parte crea una tabella da @mondaythisweek alla prossima domenica
;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)
È necessario dare uno sguardo a questa risposta [Get primo giorno della settimana in SQL Server] (http://stackoverflow.com/a/7169656/1297603) – Yaroslav