Can you describe in words exactly what the code is supposed to do? It looks like you have a hierarchy in there - have you explored some of the more conventional methods for resolving hierarchies?
Edit: is this really necessary? Can you supply some sample data of what might be encountered either side of such a join?
Where charindex(Ctn.containerCode, ISNULL(@container, Ctn.containerCode)) <> 0
AND charindex(P.partnerCode, ISNULL(@Partners, P.partnerCode)) <> 0
For fast, accurate and documented assistance in answering your questions, please read this article.
Understanding and using APPLY, (I) and (II) Paul White
Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden