You haven't given us enough information to recreate your scenario - for example
@SS3Min
is not declared, then I get an error
Invalid object name '#P1'
and no-one is going to wade through that much code to try and recreate your tables for you.
As @jorgen_andersson asked - What are you trying to achieve?
There are far easier ways to determine an hierarchy. I give a worked example in my article
Processing Loops in SQL Server[
^] - it works on the principal that you don't need a loop!
SQL is (all relational databases are) set-based - avoid using loops in all but some very rare circumstances.