Sql-server – How to SELECT an ‘entry’ that spans adjacent months

sql serversql-server-2008

I have an Event table (used in a calendar application I am working on) that holds the following columns:

  • EventName
  • StartDate
  • EndDate

The events stored in said table get shown one month at a time, and that is working great, except that it does not return any events that span over into an adjacent month. For example, an event that runs from 2/25 - 3/05.

I will only get events for the current month, provided the EndDate is also within the month under consideration.

I know that this has to do with the statements I am writing. This is what I currently have:

  SELECT * 
    FROM Events 
   WHERE StartDate >= '2/1/2011' 
     AND EndDate   <  '3/1/2011' 
ORDER BY StartDate

The dates above are dynamic.

Best Answer

I keep the following bit of ASCII art around that I drew a few years back as reference for dealing with matching ranges, reformatted, as it was originally in POD; in your case, you're using the second one, which only matches example 3:

Interval Matching

 .........A============B......... Search Range
 ...x--y..|............|......... (never match)
 .........|............|...x--y.. (never match)
 ......x--|--y.........|......... (1)
 ......x--|------------|---y..... (2)
 .........|...x-----y..|......... (3)
 .........|..........x-|----y.... (4)
  • Intersection ... matches examples 1,2,3,4

    A <= y && B >= x

  • (item fully contained by search range) ... matches example 3 only.

    A <= x && B >= y

  • (item fully includes search range) ... matches example 2 only.

    A >= x && B <= y