2016-02-04 304 views
0

我們正在爲員工休假的日期範圍選擇器SQL日期範圍

例如我將用戶2016年1月作爲一個例子,我們的系統從週日經過週六

如果員工從一月14日至20日需要一個假期,他們應該在日期範圍10-16和17-23也

我只是想不出如何寫一個SQL查詢,將其限定爲那些2個日期。

我有的是:

DECLARE @WeekRangeStart DATETIME ='2016/01/10'; 
DECLARE @WeekRangeEnd DATETIME = '2016/01/16'; 

SELECT [ID], 
     [EmpName], 
     [EmpType] 
FROM Vacations 
WHERE VacationStartDate >= @WeekRangeStart OR VacationEndDate >= @WeekRangeStart 

--OUTPUT 
--ALL DAYS BEFORE THIS WOULD BE TRUE... 
--1/14/2016 >= 1/10/2016 TRUE 
--1/20/2016 >= 1/10/2016 TRUE 
-- NEXT WEEK 
--1/14/2016 >= 1/17/2016 FALSE 
--1/20/2016 >= 1/17/2016 TRUE 
-- NEXT WEEK 
--1/14/2016 >= 1/24/2016 FALSE 
--1/20/2016 >= 1/24/2016 FALSE 
--ALL DAYS AFTER THIS DAY WOULD BE FALSE... 

,但這隻適用於對已通過的事情,但如果我是一個每天預定在三月,我會始終顯示在時間表,因爲我的開始日期會更大比今天。我應該如何限制它僅限於該範圍?

+0

很確定DATEPART()函數是你在這裏需要的。 –

+0

在WHERE子句是不正確你的範圍中的重疊的邏輯。看看這個問題: http://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap – jrook

回答

0
DECLARE @WeekRangeStart DATETIME ='2016/01/10'; 
DECLARE @WeekRangeEnd DATETIME = '2016/01/16'; 

SELECT [ID], 
    [EmpName], 
    [EmpType] 
FROM Vacations 
WHERE VacationStartDate between @WeekRangeStart and @WeekRangeEnd 
    or VacationEndDate Between @WeekRangeStart and @WeekRangeEnd 
+0

如果他們採取2個月的假期你,需要仰視的重疊,這可能會失敗日期範圍 –

0

這可能會有用。使用遞歸CTE我得到了休假跨越所有日期。然後回到它跨越了周,按提供的每週範圍。

DECLARE @WeekRangeStart DATETIME ='2016/01/10'; 
DECLARE @WeekRangeEnd DATETIME = '2016/01/16'; 
DECLARE @VacationStartDate DATETIME = '2016-01-14' 
DECLARE @VacationEndDate DATETIME = '2016-01-20' 


;WITH cte AS 
    (
    SELECT @VacationStartDate AS Dates 
    UNION ALL 
    SELECT DATEADD(dd, 1, dates) 
    FROM cte 
    WHERE dates < @VacationEndDate 
) 

SELECT DISTINCT 
DATEADD(dd, -(DATEPART(dw, dates)-1), dates) AS WeekStartDate, 
DATEADD(dd, 7-(DATEPART(dw, dates)), dates) AS WeekEndDate 
FROM cte 
WHERE dates BETWEEN @WeekRangeStart AND @WeekRangeEnd