После попытки разными способами, наконец, проблема решена с помощью этой хранимой процедуры:
create procedure GetFreeHourByTable @Date date as
declare @startTime time(0), @endTime time(0), @day int
declare @dates table (day int, time time(0))
DECLARE cursor_shifts CURSOR
FOR SELECT
w.DayOfWeek, w.StartTime, w.EndTime
FROM
WorkingTimes w where w.DayOfWeek = DATEPART(dw, @Date) and w.IsDayOff = 0;
OPEN cursor_shifts;
FETCH NEXT FROM cursor_shifts INTO
@day,
@startTime,
@endTime;
WHILE @@FETCH_STATUS = 0
BEGIN
while @startTime < DATEADD(HOUR, -1, @endTime)
begin
set @startTime = DATEADD(HOUR, 1, @startTime)
insert into @dates values (@day, @startTime)
end
FETCH NEXT FROM cursor_shifts INTO
@day,
@startTime,
@endTime;
END;
CLOSE cursor_shifts;
DEALLOCATE cursor_shifts;
select t.*, d.* from @dates d, Tables t
where d.day = DATEPART(dw, @Date)
and not exists
(select * from Applications a
where a.tableId = t.id and a.registerDate = @Date and d.time between a.startTime and a.endTime)
, поэтому мы можем запросить бесплатные таблицы (по дате) с часами:
exec GetFreeHourByTable @Date = '2020-02-23';