The problem is that the RDBMS model isn't really designed for what you're trying to accomplish. I've done things like this in the past with a cursor, which may or may not be appropriate here. Why the (seemingly arbitrary) restriction of having to do this all server side? With a programming language, you can do this quite easily...
thor
Feel the white light, the light within
Be your own disciple, fan the sparks of will
For all of us waiting, your kingdom will come