2017-03-23 54 views
-1

我想開始一天設置到週六SQL - 獲取當前日之間的所有日期,並開始和

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日內將得到顯示。 如果當天是星期四,我不想在接下來的5天內顯示。只是每週的比賽日期。

這是我走到這一步:

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; 

一些查詢的可能是錯誤的,尤其是最後一部分。

我希望我自己清楚,如果有任何問題請不要猶豫,問我!

回答

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

相關問題