简体   繁体   中英

sql server date range criteria

I am working on asp.net project. I have two dates stored in database for a vacancy. Posting date and deadline date. I want that If a user searches for any vacancy with date range then if vacancy's start date or end date falls in that range then it should be selected. Like if user selects date range March 10 to April 10 and vacancy start date is MArch 1 and deadline date is 20 march then it should be shwon.

dummy sql

select *
from vacancies v
where v.start date in date range or
      v. end date in date range

What will be sql for it

If you realise that the start date and the deadline just form another range, then this is simply a query to find all overlaps between the user specified range and the vacancy ranges:

declare @StartRange datetime
declare @EndRange datetime
select @StartRange='20140310',@EndRange='20140410'

select
    *
from vacancies v
where v.startdate <= @EndRange and
      @StartRange <= v.deadline

(It may need adjustments for <= or < depending on whether you consider either range to have inclusive or exclusive endpoints).

The basic logic is - two ranges overlap if the first range starts before the second one ends, and the second range starts before the first one ends.

This does also pick up eg vacancies which have a start date before the user specified range and a deadline date after the user specified range. That doesn't match your dummy sql but would usually be desirable (ie the vacancy is open throughout the user specified range)

You want to do something like:

SELECT * 
FROM Vacancies v
WHERE v.StartDate Between @UserProvidedStartDate and @UserProvidedEndDate
   OR v.EndDate Between @UserProvidedStartDate and @UserProvidedEndDate

This assumes you have parameters that are passed with the users search criteria.

The issue I see with this is that you will return vacancies where the deadline has passed. If you exclude the vacancy start date from the query, you will only show vacancies where the deadline is within the criteria. In which case you would just do:

SELECT * 
FROM Vacancies v
WHERE v.EndDate Between @UserProvidedStartDate and @UserProvidedEndDate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM