这可能过于复杂,但很有趣。
--这第一部分是获取最近发生的星期一。
-- 它首先创建一个表,该表将保存所有日期直到最近的星期一,然后将该表的最小值设置为@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
)
-- 这部分创建了一个从@mondaythisweek 到下周日的表格
;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)