Although you can write code that extrapolates the dates (Such as VikramJain's recursive CTE for SQL Server) it's CPU heavy. If you have large numbers of records, over large ranges of time, you're iteratively building large amounts of data. And you're doing it every time you query your data. By far the most CPU efficient method is simply to have another table.
If you think of your database in terms of Dimension tables and Fact tables, your start and end dates are just keys to an implied Dimension of Time
. Instead of being implicit, be explicit, and create a Calendar
table. Then it's trivial...
SELECT
yourTable.code,
calendar.calendar_date
FROM
yourTable
INNER JOIN
calendar
ON calendar.calendar_date >= yourTable.fromDate
AND calendar.calendar_date < yourTable.toDate
This potentially saves huge amounts of CPU load, and massively simplifies your queries.
Once you have the table, pre-populated with dates covering everything you will ever need, many messy date manipulations become simple indexable lookups.
You can even add to that table meta-data such as...
- start_of_week
- start_of_month
- financial_year
- etc, etc
Some people criticise this as inelegant. Personally I feel the opposite:
- It caches messy date based calculations
- It explicity creates a dimension table
It's even used by TeraData to very good effect: sys_calendar.calendar
.