Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. SQL Server
  3. Question
SQL Server

If sp_ExecuteSql creates a new session, how come I can access a local temp table created (prior to it's execution) outside of the dynamic SQL?

Asked by Abhi Subramaniam Apr 23, 2021 5.1K views 1 answer
Share

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:

Temp Table Results from Dynamic SQL Select

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.

Your answer

1 Answer

More SQL Server discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest SQL Server Blogs

Guides, tips and career advice on SQL Server from JanBask experts.