based on another question SQL Server: How can you turn a series of consecutive begin and end datetimes into a single begin-end range?
I search a recursive way to get the last date of downtime. I have 3 downtime linked. I want to know when my service will be available.
Sample
DECLARE @Downtime AS TABLE(id int, beginDT datetime, endDT datetime)
INSERT INTO @Downtime VALUES('a','09:00','11:00')
INSERT INTO @Downtime VALUES('b','10:00','12:00')
INSERT INTO @Downtime VALUES('c','12:00','13:00')
INSERT INTO @Downtime VALUES('d','15:00','16:00')
DECLARE @TimeParam AS DATETIME
SET @TimeParam ='1900-01-01 11:00:00.000'
At 11:00, I'm in downtime (id=1 or 2, doesn't matter). My question is, "When the service will be available (not down)?"
the answer, on the sample, is 13:00. Because we got a downtime from 9 to 11 (id=1), the id=2 give us 11 to 12, and id=3 show 12 to 13. So , it will be down from 9 to 13.
I need an sql query to found that. A recursive while the begin/end is between the end of one of the other.
I try something like that but its illegal syntax
;WITH myDates(beginDT,endDT)
AS
(
SELECT beginDT, enddt
FROM @Downtime D1
WHERE @TimeParam BETWEEN begindt AND endDT
UNION ALL
SELECT beginDT, endDT
FROM @Downtime D2
WHERE
(SELECT TOP 1 Max(enddt)
FROM myDates )
BETWEEN begindt AND endDT
)
SELECT * FROM myDates
More sample
INSERT INTO @Downtime VALUES('e','12:00','17:00')
INSERT INTO @Downtime VALUES('f','15:00','19:00')
INSERT INTO @Downtime VALUES('g','19:00','20:00')
INSERT INTO @Downtime VALUES('h','20:00','21:00')
INSERT INTO @Downtime VALUES('i','21:00','22:00')
INSERT INTO @Downtime VALUES('j','22:00','23:00')
INSERT INTO @Downtime VALUES('k','23:00','23:01')
INSERT INTO @Downtime VALUES('l','22:00','23:05')
INSERT INTO @Downtime VALUES('m','22:00','23:06')
INSERT INTO @Downtime VALUES('n','22:00','23:05')
INSERT INTO @Downtime VALUES('o','22:00','23:17')
INSERT INTO @Downtime VALUES('p','23:17','23:22')
INSERT INTO @Downtime VALUES('q','23:22','23:23')
INSERT INTO @Downtime VALUES('r','23:25','23:30')
the end of downtime should be 23:23.