Data Cogs Information Technology

posts - 131, comments - 251, trackbacks - 36

General

Search This Site

Powered by Google

Brisbane

Locations of visitors to this page

Information

Archives

Images

Blogs

CV etc.

Links For Me

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

Feedback

# re: T-SQL Function to Determine if two Date Ranges Overlap

You have a typo I think - the check should be
IF @StartDate1 <= @EndDate2 AND @StartDate2 <= @EndDate1
5/28/2008 11:18 PM | James

Post Comment

Title  
Name  
Url
Comment   
Protected by Clearscreen.SharpHIPEnter the code you see: