This function was originally contributed by other visitors. Below is an example of a set based approach to the problem.
This script requires a numbers table (see SqlServerCentral article http://www.sqlservercentral.com/columnists/mcoles/2547.asp for more details)
Please note that this code is uses SQL2005 features
Enjoy!
Robert Cary
http://tsqlland.blogspot.com