About this question
If local temp tables are only available to the current session, and sp_ExecuteSql creates a new session to execute the dynamic SQL string passed into it, how can that dynamic SQL query access a temp table created in the session that executes sp_ExecuteSql. In other words, why does this work: SELECT 1 AS TestColumn INTO #TestTempTable DECLARE @DS NVARCHAR(MAX) = 'SELECT * FROM #TestTempTable' EXEC sp_EXECUTESQL @DS
Results:
My understanding for the reason why I can't do the opposite (create the temp table in Dynamic SQL and then access it outside the dynamic SQL query in the executing session) is because sp_ExecuteSql executes under a new session.