Thanks for posting the sample data and DML.
I'm not clear on what you want the output to be. If you can post that maybe we can come up with a way to do this without having to do this in a loop and instead do it set based.
Gary Johnson
Sr Database Engineer