Get all dates between two dates in SQL Server
Generate a series of dates in SQL Server using a recursive CTE. This handy method increments one day at a time, starting from your initial date until it accomplishes the set end date:
Plug in and execute to get all dates from January 1 to January 10, 2021.
Opting for high performance using set-based operations
Set-based operations outperform row-by-row traversing, improving query performance. Use an existing calendar table for straightforward and efficient retrieval:
Without a calendar table, leverage a numbers table or a sequence of integers to side-step performance dips from recursive CTEs.
Handling larger date ranges effectively
Scaling to address large date ranges requires avoiding the execution limits of recursive CTEs by leveraging a numbers table or clever techniques like the one shown here:
This yields the dates from January 1 to December 31, 2021, leveraging the system objects as a number generator, bypassing recursion.
Clarity and simplicity: Friends for life
For readability and maintainability, punt complex recursive CTEs in favor of a simple SELECT
statement where feasible. Use table-valued functions (TVFs) to encapsulate date generation logic, providing reusability benefits.
Building exceptions and customizations into your queries
Avoid infinite loops
For wide date ranges, the recursion limit of recursive CTEs may halt your journey. Set OPTION (MAXRECURSION 0)
at the query end to allow unlimited recursion - unrestricted time travels!
Custom date formats
In case formatted strings suit your style better than date data types, use CONVERT
or FORMAT
to get customized date displays:
Non-recursive spaces
Where recursion is not preferred, fall back on a while loop or tally table for date generation:
This loop traverses the date range, depositing each date into the @DateList
table avoiding recursion.
Was this article helpful?