[英]Sql query for selecting records in between Date range
我正在尝试编写一个查询,用于基于以下条件选择记录:
它们应该在开始日期和结束日期之间。
我有类似的记录:
EventId| EventName| Event_Category| Event_StartDate| Event_EndDate| 1 | aaa | 4 | 2014-06-10 | 2014-06-15 | 2 | bbb | 5 | 2014-06-10 | 2014-06-15 | 3 | ccc | 6 | 2014-06-10 | 2014-07-11 | 4 | ddd | 5 | 2014-06-01 | 2014-07-10 | 5 | eee | 5 | 2014-06-10 | 2014-06-014 |
存储过程:
create proc usp_filterevnts @Categoryid int, @StartDate date, @EndDate date as begin select * from Events Where Event_Category=@Categoryid and ( Event_Startdate>@StartDate and Event_Enddate<@EndDate ) end
如果我执行sp为
exec usp_filterevnts 5,'2014-06-09','2014-06-16'
它应显示第5类记录的记录,其开始日期和结束日期在“ 2014-06-09”和“ 2014-06-16”之间。即第二条记录,第五条记录。
我的存储过程是否正确?
select * from Events Where Event_Category=@Categoryid and (Event_Startdate between @StartDate and @EndDate) and (Event_Enddate between @StartDate and @EndDate)
(取决于表的大小,以及日期字段是否具有索引...)
您的原始语法,但包含> =和<=
之间导致表扫描,如果表很小,则扫描不会太大。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.