0
votes

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

2
Did you try with BETWEEN ?Steve

2 Answers

0
votes

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 e.g. 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 (i.e. the vacancy is open throughout the user specified range)

0
votes

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