codeBoy
codeBoy

Reputation: 533

Date Range Limitations SQL Server

I am wanting to limit the user to not be able to search for a time frame longer than a year. So 1/1/2014 to 1/1/2015 is valid, but 1/1/2014 to 3/1/2015 is not valid. They are inputting the dates in a date picker in a SSRS report.

WHERE "view"."myDate" between @firstDate and @secondDate

Is there logic I can put in the WHERE cause that can put these restrictions into affect?

Upvotes: 0

Views: 141

Answers (1)

Rhys Jones
Rhys Jones

Reputation: 5508

You could add a DATEDIFF check to the WHERE clause to limit the range to a year;

AND DATEDIFF(d, @firstDate, @secondDate) < 366

However, this will return nothing if the range exceeds a year. If you want the query to return upto a years worth of results then you could use something like this;

WHERE "view"."myDate" between @firstDate and 
    CASE 
        WHEN DATEDIFF(d, @firstDate, @secondDate) < 366 THEN @secondDate 
        ELSE DATEADD(d, 365, @firstDate) 
    END

If you want to raise an error if the user provides an invalid range then you would have to use a stored procedure for your data source and perform parameter validation. Something like this;

CREATE PROC dbo.GetMyData ( @firstDate date, @secondDate ) AS
BEGIN

    IF (DATEDIFF(d, @firstDate, @secondDate) > 365)
    BEGIN
        RAISERROR('Please restrict searches to less than a year.', 16, 1)
        RETURN
    END

    SELECT ...
    WHERE "view"."myDate" between @firstDate and @secondDate

END

Upvotes: 4

Related Questions