SQL code to test a date range against existing ranges in a table

The following slice of code will search a table and return any rows where there is a clash between the date range in the row (ValidFrom and ValidTo) and the date range in the variables (@InTo and @InFrom).

Null dates are treated as either infinite past or infinite future accordingly.

WHERE
NOT (
(@InTo < ValidFrom AND @InTo IS NOT NULL AND ValidFrom IS NOT NULL)
OR
(@InFrom > ValidTo AND @InFrom IS NOT NULL AND ValidTo IS NOT NULL)
)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>