• Read this article:

    http://www.sqlservercentral.com/articles/T-SQL/62867/

    You'll find your solution in there.

    _____________
    Code for TallyGenerator