Click here to Skip to main content
15,885,720 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Just for knowledge:
I want to filter my query with dates. from Date and To date but i want to filter according to Month and year of both dates.
e.g
SQL
Select * from #Table where myDate between (Month(FromDate) AND Year(FromDate)) AND (Month(ToDate) AND Year(Todate))


What should be the exact syntax for this?
Let me know if question isnt clear
Posted
Updated 5-Aug-14 0:00am
v2
Comments
Wombaticus 5-Aug-14 6:11am    
If it was me, I'd convert FromDate to a date representing the 1st of the month of FromDate, and ToDate to the 1st of the month following ToDate (both simple operations doable with a single line of code each) then use a simple SQL statement with these:
select * from #Table where myDate between FromDate and ToDate
Otherwise you're going to have some rather ugly SQL to deal with...
Schatak 5-Aug-14 6:30am    
Alright, and how about years?

Not like that!

Instead, remove the day part from all three dates, and use them.
C#
DATEADD(month, DATEDIFF(month, 0, MyDateColumnOrValue), 0)
Will convert a date to the 1st of the month, so you might want something like:
SQL
... WHERE DATEADD(month, DATEDIFF(month, 0, myDate), 0) BETWEEN 
          DATEADD(month, DATEDIFF(month, 0, FromDate), 0) AND
          DATEADD(month, DATEDIFF(month, 0, ToDate), 0)
 
Share this answer
 
Comments
Schatak 5-Aug-14 6:26am    
then do i need to take care of years?
OriginalGriff 5-Aug-14 6:31am    
No, because you are "flattening" all dates to the first of the month: so the year is automatically ok.
Schatak 5-Aug-14 6:49am    
Thanks alot, +5.
it works :)
OriginalGriff 5-Aug-14 7:04am    
You're welcome!
Hi,

Try this...


SQL
Select * from #Table 
where 
MONTH(myDate ) BETWEEN MONTH(FromDate) AND MONTH(ToDate)
AND 
YEAR(myDate ) BETWEEN YEAR(FromDate) AND YEAR(ToDate)



I have not checked it, so you can be back if did not get desired output.


Hope this will help you.


Cheers
 
Share this answer
 
Comments
Schatak 5-Aug-14 6:47am    
It works but query taking time to load. and above solution seems better option, But thanks for the effort and reply
Magic Wonder 5-Aug-14 7:09am    
Yup....your welcome.

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