r/SQL • u/Glum-Molasses-4181 • May 07 '26
SQL Server SQL2018 - variable date ranges
Hi - I need help with a variable date range formula. I need to capture data from Jun 1 of the previous year through May 31 of current year. The query needs to be able to run anytime through the year and needs to work in future years. So this year it would be 6/1/25 -5/31/26, but next year would be 6/1/26-5/31/27. I can't figure how without hardcoding the dates. I found a formula but it only works with earlier versions of sql. Can anyone assist?
0
Upvotes
View all comments
Show parent comment
2
u/gumnos May 07 '26
Just for the record, because
getdate()might not be atomic, you might encounter weird conditions around midnight of Dec 31st into Jan 1st.leaving
@startdatein 2024 and@enddatein 2026.You can make it reliable by using
getdate()once and then using that value in your above values: