2013-05-28 98 views
2

我有一個名爲「細節」的表,我在這裏存儲作業的開始日期和結束日期。我還有一個名爲「樹葉」的表,它也有開始日期和結束日期字段。我需要在沒有周末和假期的情況下查找用戶最近的可用日期。SQL查詢查找可用的未來日期,除了週末

DECLARE @PackagerLastAssignedDate DATETIME 

SELECT @PackagerLastAssignedDate = MAX(EndDate) FROM detail WHERE userId = 1 

SELECT lveStartDate,lveEndDate FROM Leaves WHERE UserId = 1 and lveStartDate > @PackagerLastAssignedDate 

在此先感謝 Berlin.M

回答

1

嘗試這一個 -

DECLARE 
     @DateFrom DATETIME 
    , @DateTo DATETIME 

SELECT 
     @DateFrom = '20130101' 
    , @DateTo = '20130202' 

SELECT [Date] 
FROM (
    SELECT [Date] = DATEADD(DAY, sv.number, t.DateFrom) 
    FROM (
     SELECT 
       DateFrom = @DateFrom 
      , diff = DATEDIFF(DAY, @DateFrom, @DateTo) 
    ) t 
    JOIN [master].dbo.spt_values sv ON sv.number <= diff 
    WHERE sv.[type] = 'p' 
) t2 
WHERE DATENAME(WEEKDAY, [Date]) NOT IN ('Saturday', 'Sunday') 
    AND NOT EXISTS (
     SELECT 1 
     FROM dbo.Leaves l 
     WHERE l.UserId = 1 
      AND t2.[Date] BETWEEN l.lveStartDate AND l.lveEndDate 
    ) 
+0

這隻會消除了週末。我需要避免其他表「葉子」的一些具體的日期。除了週末和樹葉之外,我需要選擇接下來的3個可用日期。明確....? – Berlin

+0

請嘗試更新的答案。 – Devart

+0

是的,工作......謝謝...... – Berlin