I don't think it's an issue of the queries being "large".
More likely the two while loops *cough* generate a huge number of execution plans being generated and displayed leading to the error message.
Regardless of the original question: there's most likely more than one alternative to speed up this process and to get rid of the loops.
But this would require something to test against (DDL, sample data, expected result...).