• I used to write similar code like this for years and then discovered tally tables made it easier and faster IMHO.

    Here's an example:

    http://www.sqlservercentral.com/scripts/Miscellaneous/31913/