Sql query for selecting records in between Date range

∥☆過路亽.° 提交于 2019-12-11 18:58:12

问题


I am trying to write a query for selecting records based on:

  1. They should belong to particular category
  2. They should be between Start date and End date.

    I have records like:

    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 |
    

    Stored procudure:

    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
    

    If i execute the sp as

      exec usp_filterevnts 5,'2014-06-09','2014-06-16' 
    

    It should display records of Category 5Th records , whose start date and end date between '2014-06-09' and '2014-06-16 ..ie 2nd record, 5 th record..

    Is my stored procedure correct for this??


回答1:


select * from Events Where Event_Category=@Categoryid and (Event_Startdate between @StartDate and @EndDate) and (Event_Enddate between @StartDate and @EndDate)



回答2:


(depending on table size, and whether the date field has an index...)

Your original syntax, but with >= and <= to be inclusive

Between causes a table scan, which won't matter too much if your table is small.



来源:https://stackoverflow.com/questions/24490986/sql-query-for-selecting-records-in-between-date-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!