The title doesn't quite capture what I mean, and this may be a duplicate.
Here's the long version: given a guest's name, their registration date, and their checkout date, how do I generate one row for each day that they were a guest?
Ex: Bob checks in 7/14 and leaves 7/17. I want
('Bob', 7/14), ('Bob', 7/15), ('Bob', 7/16), ('Bob', 7/17)
as my result.
Thanks!
If you have a "Tally" or "Numbers" table, life get's real simple for things like this.
Here's how to build a "Tally" table.
For more information on what a "Tally" table is in SQL and how it can be used to replace While loops and the "Hidden RBAR" of reursive CTEs that count, please see the following article.
http://www.sqlservercentral.com/articles/T-SQL/62867/
I usually do this with a trick using row_number() on some table. So:
The calculation for seq goes pretty fast, since no calculation or ordering is required. However, you need to be sure the table is big enough for all time spans.
I would argue that for this specific purpose the below query is about as efficient as using a dedicated lookup table.
Results:
Presumably you'll need this as a set, not for a single member, so here is a way to adapt this technique:
Results:
As @Dems pointed out, this could be simplified to:
This may work for ya:
I would create a trigger to create extra records and run it upon checkout. Alternatively, you can have a daily midnight job doing the same (if you need up-to-date info in your database).