My question is similar to this MySQL question, but intended for SQL Server:
Is there a function or a query that will return a list of days between two dates? For example, lets say there is a function called ExplodeDates:
SELECT ExplodeDates('2010-01-01', '2010-01-13');
This would return a single column table with the values:
2010-01-01
2010-01-02
2010-01-03
2010-01-04
2010-01-05
2010-01-06
2010-01-07
2010-01-08
2010-01-09
2010-01-10
2010-01-11
2010-01-12
2010-01-13
I'm thinking that a calendar/numbers table might be able to help me here.
Update
I decided to have a look at the three code answers provided, and the results of the execution - as a % of the total batch - are:
- Rob Farley's answer : 18%
- StingyJack's answer : 41%
- KM's answer : 41%
Lower is better
I have accepted Rob Farley's answer, as it was the fastest, even though numbers table solutions (used by both KM and StingyJack in their answers) are something of a favourite of mine. Rob Farley's was two-thirds faster.
Update 2
Alivia's answer is much more succinct. I have changed the accepted answer.
A few ideas:
If you need the list dates in order to loop through them, you could have a Start Date and Day Count parameters and do a while loop whilst creating the date and using it?
Use C# CLR Stored Procedures and write the code in C#
Do this outside the database in code
Before you use my function, you need to set up a "helper" table, you only need to do this one time per database:
here is the function:
use this:
output:
this few lines are the simple answer for this question in sql server.
Perhaps if you wish to go an easier way, this should do it.
But the temporary table is a very good approach also. Perhaps shall you also consider a populated calendar table.
This query works on Microsoft SQL Server.
Now let's look at how it works.
The inner query merely returns a list of integers from 0 to 9999. It will give us a range of 10,000 values for calculating dates. You can get more dates by adding rows for ten_thousands and hundred_thousands and so forth.
This part converts the string to a date and adds a number to it from the inner query.
Then we convert the result into the format you want. This is also the column name!
Next we extract only the distinct values and give the column name an alias of aDate.
We use the where clause to filter in only dates within the range you want. Notice that we use the column name here since SQL Server does not accept the column alias, aDate, within the where clause.
Lastly, we sort the results.
In case you want to print years starting from a particular year till current date. Just altered the accepted answer.