我正在尝试将开始日设置为星期六
SET DATEFIRST 6 -- Sets start day to Saturday
然后在本周开始到本周结束之间获取所有GameDate。但它需要在当天完成。例如:如果当天是星期四,而本周末是星期五,我不想这样做:
DECLARE @StartWeek datetime Set @StartWeek = DATEADD(w, 0, DATEADD(w, DATEDIFF(w, 0,GETDATE()), -5))
DECLARE @EndWeek datetime Set @EndWeek = DATEADD(w, 0, DATEADD(w, DATEDIFF(w, 0,GETDATE()), 1))
因为这会使接下来的5天显示出来。 如果CurrentDay是星期四,我不希望在接下来的5天内出现。只是每周的GameDates。
这是我到目前为止所得到的:
DECLARE @DateTable Table (DateofWeek Date) -- Creates table
DECLARE @DateToday Date SELECT DAY(GETDATE()) 'Current Day' -- Gets current date
DECLARE @StartWeek datetime Set @StartWeek = DATEADD(w, 0, DATEADD(w, DATEDIFF(w, 0,GETDATE()), -5)) --This is the part thats wrong
DECLARE @EndWeek datetime Set @EndWeek = DATEADD(w, 0, DATEADD(w, DATEDIFF(w, 0,GETDATE()), 1)) --This is the part thats wrong
SET DATEFIRST 6 -- Sets start day to Saturday
SELECT DATEDIFF ( DAY, @DateToday, @EndWeek) AS Diffrence_End
SELECT DATEDIFF ( DAY, @DateToday, @StartWeek) AS Diffrence_Start
FROM @DateTable
WHILE @DateToday >= @EndWeek AND @DateToday <= @StartWeek -- Shows all gameDates between StartWeek and Endweek
BEGIN
SELECT DATEDIFF ( DAY, @DateToday, @EndWeek)
Insert Into @DateTable
SELECT *
FROM @DateTable
END;
一些查询可能是错误的,尤其是最后一部分。
我希望自己清楚明白,如果有任何问题,请不要犹豫,问我!
答案 0 :(得分:1)
看看:
-- Sets start day to Saturday SET DATEFIRST 6 -- Creates table DECLARE @DateTable Table ([DateofWeek] date); -- StartDate = DATEPART(DW, ... ) = 1 DECLARE @StartDate date; SET @StartDate = DATEADD(day, (DATEPART(dw, GETDATE()) - 1) * -1, GETDATE()); -- EndDate = StartDate + 6 days DECLARE @EndDate date; SET @EndDate = DATEADD(day, 6, @StartDate); -- Generates table values DECLARE @CurrentDate date; SET @CurrentDate = @StartDate; WHILE @CurrentDate <= @EndDate BEGIN INSERT INTO @DateTable ([DateofWeek]) VALUES (@CurrentDate); SET @CurrentDate = DATEADD(day, 1, @CurrentDate); END --Check it SELECT *, DATENAME(dw, DateOfWeek) as Name FROM @DateTable;
GO
DateofWeek | Name :------------------ | :-------- 18/03/2017 00:00:00 | Saturday 19/03/2017 00:00:00 | Sunday 20/03/2017 00:00:00 | Monday 21/03/2017 00:00:00 | Tuesday 22/03/2017 00:00:00 | Wednesday 23/03/2017 00:00:00 | Thursday 24/03/2017 00:00:00 | Friday
dbfiddle here