I found a in my archives I do not know who wrote it so therefore I can not give them the credit for it.
SELECT
startdate_from = t1.startdate,
enddate_from = t1.enddate,
startdate_to = t2.startdate,
enddate_to = t2.enddate,
potential_error_id = t2.ID,
error_msg =
CASE
WHEN DATEDIFF(d, t1.enddate, t2.startdate) < 0 THEN 'Error: An overlap exists in date ranges'
WHEN DATEDIFF(d, t1.enddate, t2.startdate) = 0 THEN 'Error: [enddate_from] equals [startdate_to]'
WHEN DATEDIFF(d, t1.enddate, t2.startdate) = 1 THEN 'OK, so far ...'
WHEN DATEDIFF(d, t1.enddate, t2.startdate) = 2 THEN 'Error: Date ' + CAST( DATEADD(d, -1, t2.startdate) AS VARCHAR) + ' is missing.'
WHEN DATEDIFF(d, t1.enddate, t2.startdate) > 2 THEN 'Error: Two or more dates are missing in ranges'
END
FROM
Test t1, Test t2
WHERE
t2.ID > 1 AND
t1.ID = t2.ID - 1
The query assumes that the ID column and date ranges have a linear ascending order as you originally posted.
Hope this helps ...
JP
Jaime E. Maccou
Applications Analyst
|