You are doing it wrong!
Try:
exec(@SQL)
instead of:
EXECUTE sp_executesql @SQL
To use sp_executesql
the variable must be inside @SessionID
the quotes and it must be provided has input parameter. Check this for a full example!
You've to be aware that Dynamic SQL is a good port for SQL injections!
The temp table is out of scope after exec is done.'exec' or 'sp_executesql' are run in thier own scope.
Thus anything created like temp tables and variables are destroyed or out of scope as soon as execution is over .Think these like stored proc.
To fix the issue.Create the temp table in main code.. then insert into it using dynmic sql and then read it in main code.