问题
I am trying to write a query for selecting records based on:
- They should belong to particular category
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