我想我参加聚会有点晚了,但我刚刚和这个摔跤了。这是我过去两年工作周生成的内容(假设周日是一周的开始,周六是结束):
Declare @workWeeks Table (
weekStart datetime,
weekEnd datetime,
weekText varchar(25)
)
Declare @count int,
@lastSunday datetime,
@nextSaturday datetime
Select @count = 0,
@lastSunday = DATEADD(DAY, DATEDIFF(DAY, -1, GETDATE()) / 7 * 7, -1),
@nextSaturday = DATEADD(MS, -3, DATEADD(DAY, DATEDIFF(DAY, -1, GETDATE()) / 7 * 7, 6)) -- Next Sunday minus 3 ms
While @count < 52
Begin
Insert Into @workWeeks Values(
DATEADD(WK, -@count, @lastSunday),
DATEADD(WK, -@count, @nextSaturday),
CONVERT(varchar, DATEADD(WK, -@count, @lastSunday), 101) + ' - ' + CONVERT(varchar, DATEADD(WK, -@count, @nextSaturday), 101))
Set @count = @count + 1
End
Select * From @workWeeks
你会得到这个:
weekStart weekEnd weekText
----------------------- ----------------------- -------------------------
2015-06-14 00:00:00.000 2015-06-20 23:59:59.997 06/14/2015 - 06/20/2015
2015-06-07 00:00:00.000 2015-06-13 23:59:59.997 06/07/2015 - 06/13/2015
2015-05-31 00:00:00.000 2015-06-06 23:59:59.997 05/31/2015 - 06/06/2015
2015-05-24 00:00:00.000 2015-05-30 23:59:59.997 05/24/2015 - 05/30/2015
...
您可以通过在用于设置@lastSunday 和@nextSaturday 的表达式末尾的日期调整值进行猴子调整,在此示例中分别为-1 和6,来更改考虑一周的开始和结束日期的内容。
但是,如果我正确地阅读了您的原始问题,您只需要本周的周一至周五,对吗?在这种情况下,只需在插入语句中的每个方向调整一天,如下所示:
-- For Mon thru Fri:
Insert Into @workWeeks Values(
DATEADD(WK, -@count, DATEADD(DD, 1, @lastSunday)),
DATEADD(WK, -@count, DATEADD(DD, -1, @nextSaturday)),
CONVERT(varchar, DATEADD(WK, -@count, DATEADD(DD, 1, @lastSunday)), 101) + ' - ' + CONVERT(varchar, DATEADD(WK, -@count, DATEADD(DD, -1, @nextSaturday)), 101))
你会得到这个:
weekStart weekEnd weekText
----------------------- ----------------------- -------------------------
2015-06-15 00:00:00.000 2015-06-19 23:59:59.997 06/15/2015 - 06/19/2015
2015-06-08 00:00:00.000 2015-06-12 23:59:59.997 06/08/2015 - 06/12/2015
2015-06-01 00:00:00.000 2015-06-05 23:59:59.997 06/01/2015 - 06/05/2015
2015-05-25 00:00:00.000 2015-05-29 23:59:59.997 05/25/2015 - 05/29/2015
...