Question

DECLARE @SEASONSTARTDATE date = '1900-03-26'
DECLARE @SEASONENDDATE date = '1900-12-31'

With Above data, how do you check if its within the current MONTH and DAY Range.

For example today's date is 2014-04-25 (year is irrelevant), which would mean the above data is valid since its within 3/26 and 12/31.

EDIT :

declare @SOMEDATA TABLE(
    SEASON_START_DATE datetime,
    SEASON_END_DATE datetime
)

INSERT INTO @SOMEDATA
VALUES ('1900-03-26','1900-12-31')

SELECT * FROM @SOMEDATA
WHERE DATEPART(MONTH,GETDATE()) BETWEEN DATEPART(MONTH,SEASON_START_DATE) AND DATEPART(MONTH,SEASON_END_DATE)
AND DATEPART(DAY,GETDATE()) BETWEEN DATEPART(DAY,SEASON_START_DATE) AND DATEPART(DAY,SEASON_END_DATE)

The above should have returned me a result because the current date is in the valid range of 3/26 and 12/31.

The above is not valid because I've broken down the date into month first and compared the months to be in range, and then did the same with day, how can this be done so that it compares just Month and Day with current Month / day to see if the current month/day is within range?

Was it helpful?

Solution

DATEPART returns integer. Use >= and <= instead of BETWEEN. See if this helps.

Also, seems you have a logical issue there.
For the end date you check only the DAY,
for the start date, you check only the MONTH.

This seems wrong to me.

Try this:

DECLARE @DT datetime

SET @DT = getdate()
DECLARE @m1 int
SET @m1 = DATEPART(MONTH, SEASON_START_DATE)
DECLARE @m2 int
SET @m2 = DATEPART(MONTH, SEASON_END_DATE)
IF (@m2 < @m1) 
   BEGIN
        SET @m2 = @m2 + 12

        DECLARE @m int
        SET @m = DATEPART(MONTH, @DT)
        IF (@m >= 1 and @m <= @m2) BEGIN SET @m = @m + 12 END
   END


SELECT * FROM @SOMEDATA
WHERE 
@m * 100 + DATEPART(DAY,@dt) >= 
    @m1 * 100 + DATEPART(DAY,SEASON_START_DATE)
AND
@m * 100 + DATEPART(DAY,@dt) <=  
    @m2 * 100 + DATEPART(DAY,SEASON_END_DATE)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top