Khades (9/4/2012)
Thank you once again. I appreciate your help.What does the dbo.Tally table hold? I notice we keep querying the N column.
A "Tally" table (sometimes called a "Numbers" table) is just a table with a large column of sequentially ordered numbers which can be joined to other tables to avoid using cursors or while loops.
This article will giet you started on the subject: http://www.sqlservercentral.com/articles/T-SQL/62867/
BTW, in my last post above I did include some WHILE loops which could almost certainly be replaced by joining to a tally table. But it was late when I posted that and I wanted to go home. 😛
Besides, in my particular case where I'm using a function very similar to this, the number of loops are likely to be minimal as these stray characters only occur infrequently and I'm using the function against a single block of code at a time and not in a SELECT statement. If using this function in a SELECT statement it would be worth the effort to try and replace them with some sort of non-looping construct.