[英]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. 因此,
1/1/2014
至1/1/2015
有效,但1/1/2014
至3/1/2015
无效。 They are inputting the dates in a date picker in a SSRS report. 他们正在SSRS报告中的日期选择器中输入日期。
WHERE "view"."myDate" between @firstDate and @secondDate
Is there logic I can put in the WHERE
cause that can put these restrictions into affect? 我可以在
WHERE
原因中添加可以使这些限制生效的逻辑吗?
You could add a DATEDIFF check to the WHERE clause to limit the range to a year; 您可以在WHERE子句中添加DATEDIFF检查,以将范围限制为一年。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.