Let me explain the situation
I have two tables:
-One is to store the equipment faults, with their own Start Date and End Date.
-Other to store the breaks, each break have a Start Date and End Date.
For example the fault begin at 9:10 and finish at 9:16. The break begin at 9:14 and finish at 9:18, The fault time is 4 minutes And 2 minutes of the fault don’t count because ocurred on a break. I need get the “2 minutes” value to include it in a report
To calculate it, I use a Scalar-valued Function:
DECLARE @Time int;
SET @Time = 0;
IF (@BreakStartDate > @FaultStartDate) AND (@BreakEndDate < @FaultEndDate)
SET @Time = DATEDIFF(SECOND, @BreakStartDate, @BreakEndDate);
ELSE IF (@FaultStartDate > @BreakStartDate) AND (@FaultEndDate < @BreakEndDate)
SET @Time = DATEDIFF(SECOND, @FaultStartDate, @FaultEndDate);
ELSE IF (@FaultStartDate < @BreakStartDate) AND ((@FaultEndDate > @BreakStartDate) AND (@FaultEndDate < @BreakEndDate))
SET @Time = DATEDIFF(SECOND, @BreakStartDate, @FaultEndDate);
ELSE IF (@FaultEndDate > @BreakEndDate) AND ((@FaultStartDate > @BreakStartDate) AND (@FaultStartDate < @BreakEndDate))
SET @Time = DATEDIFF(SECOND, @FaultStartDate, @BreakEndDate);
RETURN @Time
I need to validate all scenarios, if the fault start first and finish on the break, etc…
My question is, exist a function that do this automatically?
or a more elegant solution?
I was doing something similar with a time entry tool and needed to detect overlap between entered times. If all you really need is “I have a fault. There will be 1 Break during the Fault period. Give me the amount of time during which they’re co-incident”, then your function is on the right track.
When I did mine, I found exploring test cases visually was better than a truth table, and both were better than prose or code.
…etc.
As for doing this elegantly, I’d point out that if there is any overlap between the two lapses, you always wind up wanting the larger start date. Like so:
…and similar for the smallest end date. Because our zone of interest is when both have started and neither have finished. So your logic can become:
If I had to do what you stated, this is probably what I’d go with.
That said, in analyzing your question, I’m wondering if you don’t have to worry about multiple breaks per fault, if you are trying to do this for all faults in a result set, if you’re aggregating “time per equipment per week” or something. If so, you want another approach. But that’s another answer.