Select 1
From RoomBookSchedule
Where Location_ID = @Location_ID
And isnull(IsDeleted,0) = 0
And (SlotStart > @SlotStart And SlotStart <= @SlotEnd)
-- Assumption: There are no overlapping rows in your table.
DECLARE @RoomBookSchedule TABLE
(
SlotStart SMALLDATETIME ,
SlotEnd SMALLDATETIME
);
INSERT INTO @RoomBookSchedule
VALUES ( '20141212 08:30:00', '20141212 09:30:00' ),
( '20141212 09:30:00', '20141212 10:30:00' ),
( '20141212 12:30:00', '20141212 13:30:00' ),
( '20141212 13:30:00', '20141212 14:30:00' );
DECLARE @SlotStart SMALLDATETIME = '20141212 10:30:00';
DECLARE @SlotEnd SMALLDATETIME = '20141212 11:30:00';
-- @SlotStart and @SlotEnd must be in the same gap.
WITH Data
AS ( SELECT RBS.SlotStart ,
RBS.SlotEnd ,
LAG(RBS.SlotEnd, 1, '19000101') OVER ( ORDER BY RBS.SlotStart ) AS PreviousSlotEnd
FROM @RoomBookSchedule RBS
UNION ALL
SELECT '20790606' ,
'20790606' ,
MAX(RBS.SlotEnd)
FROM @RoomBookSchedule RBS
)
SELECT *
FROM Data D
WHERE @SlotStart BETWEEN D.PreviousSlotEnd AND D.SlotStart
AND @SlotEnd BETWEEN D.PreviousSlotEnd AND D.SlotStart;
-- Without LAG()
WITH Data
AS ( SELECT RBS.SlotStart ,
RBS.SlotEnd ,
COALESCE(( SELECT MAX(I.SlotEnd)
FROM @RoomBookSchedule I
WHERE I.SlotEnd <= RBS.SlotStart
), '19000101') AS PreviousSlotEnd
FROM @RoomBookSchedule RBS
UNION ALL
SELECT '20790606' ,
'20790606' ,
MAX(RBS.SlotEnd)
FROM @RoomBookSchedule RBS
)
SELECT *
FROM Data D
WHERE @SlotStart BETWEEN D.PreviousSlotEnd AND D.SlotStart
AND @SlotEnd BETWEEN D.PreviousSlotEnd AND D.SlotStart;
.
-- Assuming that a slot is always 1h and start always at hh:30:00.
-- Slot available, when no row found.
WITH Data
AS ( SELECT CAST(RBS.SlotStart AS DATE) AS DateDay ,
DATEDIFF(MINUTE, '00:30:00', CAST(RBS.SlotStart AS TIME)) / 60 AS SlotNo
FROM @RoomBookSchedule RBS
)
SELECT *
FROM Data D
WHERE D.DateDay = CAST(@SlotStart AS DATE)
AND D.SlotNo = DATEDIFF(MINUTE, '00:30:00', CAST(@SlotStart AS TIME)) / 60;
Can you provide a sample of data so we can work it out?