SQL查询以查找除周末之外的可用未来日期

时间:2013-05-28 06:43:37

标签: sql sql-server-2012

我有一个叫做“详细信息”的表,我在那里存储工作的开始日期和结束日期。我还有一个名为“leaves”的表,它还有start startdate和leave enddate fields.I需要找到最近的可用日期没有周末和离开日期的用户

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 个答案:

答案 0 :(得分: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 
    )