SQL Server CTE 问题

And*_*unt 5 sql-server query cte

这个问题参考了我的最后一个问题:SQL Server 08: Union over while

我正在编写一个 CTE 来执行该问题中描述的操作(在给定的天数内找到可用的时间段。

我写了一个 CTE,但我不太明白如何让我的日期增加和限制。就目前而言,它仅从 2011-07-30 (@ArrivalDate) 获取数据。任何人都可以向我解释如何正确增加它,以及我哪里出错了?

更新:我想出了一个更好的查询来获取所有可用的时间段

(SELECT TS.UKTNN, TS.TimeSlotID, TS.TimeSlotGroupID 
 FROM FittingCentreTimeSlotGroupTimeSlots TS)
EXCEPT
(Select BFD.UKTNN, BFD.TimeSlotID, BFD.TimeSlotGroupID 
 From BookedFittingDates BFD) 
Run Code Online (Sandbox Code Playgroud)

这是评论中要求的表结构:

TimeSlotGroup UKTNNTimeSlotGroupID,TimeSlotGroupDesc

TimeSlotGroupTimeSlots UKTNNTimeSlotIDTimeSlotGroupID,TimeSlotDesc

BookedDates UKTNNTimeSlotGroupIDTimeSlotID日期

这是我现有的 CTE 现在的样子

Use[DEV_UKTN_DATA]
GO 
DECLARE @UKTNN int;
DECLARE @ArrivalDate date;
DECLARE @NumDays int;
DECLARE @LoopDate date;

SET @UKTNN = 7;
SET @ArrivalDate = '2011-07-30';
SET @LoopDate = @ArrivalDate;
SET @NumDays = 2;

WITH GetTimeSlotsOnDays(TimeSlotGroupID, TimeSlotGroupDesc, TimeSlotID, TimeSlotDescription, AdditionalCost, UKTNN, CurrentDate, Distance)
AS
(
    SELECT TSG.TimeSlotGroupID, 
           TSG.TimeSlotGroupDesc, 
           TS.TimeSlotID, 
           TS.TimeSlotDescription, 
           TS.AdditionalCost,
           @UKTNN AS UKTNN,
           @ArrivalDate as CurrentDate,
           0 As Distance
    FROM FittingCentreBranchTimeSlotGroups TSG
    INNER JOIN FittingCentreTimeSlotGroupTimeSlots TS 
               ON TSG.TimeSlotGroupID = TS.TimeSlotGroupID AND 
                  TSG.UKTNN = TS.UKTNN
    WHERE TSG.UKTNN = @UKTNN AND
          TS.UKTNN = @UKTNN AND
          TS.TimeSlotGroupID = TSG.TimeSlotGroupID AND
          NOT EXISTS(
                SELECT * 
                FROM BookedFittingDates BFD 
                WHERE BFD.TimeSlotGroupID = TS.TimeSlotGroupID AND 
                      BFD.TimeSlotID = TS.TimeSlotID AND
                      BFD.UKTNN = @UKTNN AND
                      BFD.Date = @ArrivalDate)
          --@ArrivalDate <= DATEADD(DAY, @NumDays, @ArrivalDate) 

    UNION ALL --Recursion starts here

    SELECT TSG.TimeSlotGroupID, 
           TSG.TimeSlotGroupDesc, 
           TS.TimeSlotID, 
           TS.TimeSlotDescription, 
           TS.AdditionalCost,
           @UKTNN UKTNN,
           @ArrivalDate As CurrentDate,
           Distance + 1 As Distance
    FROM FittingCentreBranchTimeSlotGroups TSG
    INNER JOIN FittingCentreTimeSlotGroupTimeSlots TS 
               ON TSG.TimeSlotGroupID = TS.TimeSlotGroupID AND 
                  TSG.UKTNN = TS.UKTNN
    INNER JOIN GetTimeSlotsOnDays as GTSOD
               ON GTSOD.CurrentDate = DATEADD(DAY, Distance, @ArrivalDate)
)


SELECT *
FROM GetTimeSlotsOnDays GTSOD
WHERE GTSOD.CurrentDate = @ArrivalDate AND GTSOD.Distance = 0
ORDER BY GTSOD.TimeSlotGroupID ASC, GTSOD.TimeSlotID ASC
GO
Run Code Online (Sandbox Code Playgroud)

And*_*unt 2

我找到了这个问题的答案!

1) 创建一个返回包含所需日期的表的函数

2)对时间段和日期进行笛卡尔积

3)查找预订日期和笛卡尔积之间的例外情况