Click here to Skip to main content
16,004,653 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more: , +
Hello,
I'm using a SQL code to find Birthdays between dates, the query works perfectly when fromdate is 03-01-2016 and todate 03-31-2016 i.e. in one month only. But when I enter fromdate = 03/15/2016 todate = 04/15/2016 then it gives incorrect output as there are two months included...
Please Help...!!!

What I have tried:

SQL
SELECT registration_no,name,category,status,dob
From rpd
WHERE Datepart(day,dob) between datepart(day, @from_date)
and Datepart(day,@to_date) 
and 
Datepart(month,dob) between datepart(month, @from_date)
and Datepart(month,@to_date)
Posted

1 solution

Try with below query:
SQL
declare @from_date  datetime;
declare @to_date datetime;
set @to_date = '03/31/2016';
set @from_date = '03/01/2016';

select registration_no, name, category, status, dob
From rpd
where Datepart(month,dob) between datepart(month, @from_date)
and Datepart(month,@to_date) 
and (
(Datepart(day,dob) >= datepart(day, @from_date) and datepart(month, dob) = Datepart(month, @from_date))
OR
(Datepart(day,dob) <= datepart(day, @to_date) and datepart(month, dob) = Datepart(month, @to_date))
OR
(Datepart(month,dob) > datepart(month, @from_date) and datepart(month, dob) < Datepart(month, @to_date))
)
 
Share this answer
 
v4
Comments
Member 12133159 13-Feb-16 3:36am    
Thanks a lot, Mr. Manas
It worked perfectly.....

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900