Creating a date range in SQL

I didn’t want a user to be able to add overlapping date ranges. I also wanted to warn them like Robot from “Lost in Space” would do it. Combining these two noble goals, I came up with this:

DECLARE @PromoCount INT
DECLARE @DateFrom DATETIME = ‘9/11/12’
DECLARE @DateTo DATETIME = ‘9/12/12 23:59:59’

SELECT @PromoCount = COUNT(*) 
FROM Promo
WHERE (DateFrom BETWEEN @DateFrom AND @DateTo)
OR (DateTo BETWEEN @DateFrom AND @DateTo)

IF @PromoCount > 0
  BEGIN
     SELECT ‘Danger Will Robinson’
  END

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: