Archive for September, 2012

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

Leave a comment