Skip to content
Advertisement

SQL Server – find people between date range excluding the year

I have a table EMPLOYEE containing Employee info as mentioned below:

I want to list all the employees whose DOB is in the given range.

I have a filter condition to ‘include year in date comparison’, which when selected ‘NO’, the employee DOB day and DOB month only should be considered for comparison. and not the year.

For example: If I enter the date range as ‘1970-01-01’ and ‘1980-02-27’ and the filter is selected as ‘NO’ then it should search for only those employees whose DOB is greater than equal to JAN-01 and less than equal to FEB-27.

When selected ‘Yes’, it is simply date range as mentioned in above query.

Here is what I have tried so far:

It works when I pass the date range where the FROM date has smaller number month than the TO date month.

For example: It doesnt work when I pass the date range as ‘1970-12-01’ to ‘1980-01-31’. It should list the employees whose DOB is in DEC and JAN month.

Need help please.

Advertisement

Answer

Sample Data;

This is the query I’ve made. Tried to cover for every eventuality.

  • First part of the where clause checks if the @date_from and @date_to are the same date, then only returns these.
  • Second part checks if the day of year for @date_from comes before @date_to. If it does then return everything between these days of the year.
  • Final part checks if the day of year for @date_to comes before @date_from then it gets everything with the day of year after @date_from or before @date_to

The results for this one come out as this;

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement