Skip to content
Advertisement

Return Date Ranges based based on a given interval between two given dates in SQL

I am trying to get a list of all DateRanges of a given interval between two dates.

For example if I have the dates 2015-04-01 and 2015-06-20 and when the interval is 20 the result should be

Here is the query I am trying

Its returning the below result which is not exactly as my expected result above

Here as you can see, there is an extra row outside the given dates and also interval between second row onward is 19 days, not 20. I understand its because I am adding a Day to the first field after union all

Please help me to fix this query or please suggest a better way to implement the same.

Advertisement

Answer

Changes to your recursive cte should be

use CASE to check for ending date. If it is greater than the required end date, set it to @EndDateTime

Also the WHERE condition should be

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