Does this date range overlap that date range? Use this T-SQL function to find out.
UPDATE: There is a far simpler way to do this. It turns out all the cases in the above example can be handled by the one condition:
If @StartDate1 <= @EndDate2 AND @StartDate1 <= @EndDate1 then the date ranges overlap. See full example below:
/*************************************************************
--Purpose: Returns 1 is two date ranges overlap, 0 if they don't
--
--Created By: Mark Daunt
--Example Usage:
SELECT dbo.fnOverlaps('20040101', '20040630', '20040615', '20050101')
**************************************************************
--Handles the following cases of overlapping date ranges
|---------|
S1 E1
|----|
S2 E2
|---------|
S1 E1
|------------|
S2 E2
|---------|
S1 E1
|----|
S2 E2
|---------|
S1 E1
|---------|
S2 E2
|---------|
S1 E1
|--------------|
S2 E2
*/
CREATE FUNCTION dbo.fnOverlaps
(
@StartDate1 DATETIME,
@EndDate1 DATETIME,
@StartDate2 DATETIME,
@EndDate2 DATETIME
)
RETURNS BIT
AS BEGIN
DECLARE @RetVal BIT
IF @StartDate1 <= @EndDate2 AND @StartDate1 <= @EndDate1
SET @RetVal = 1
ELSE
SET @RetVal = 0
RETURN @RetVal
END
posted on Thursday, October 21, 2004 3:05 PM