Execution plan over query with temp tables

Diego Jancic picture Diego Jancic · Jan 11, 2012 · Viewed 21.7k times · Source

I've a stored procedure that does something like this:

SELECT Id
INTO #temp
FROM table
WHERE ...

DELETE FROM #temp
INNER JOIN table2 ON a=b
WHERE ...

But it's running slowly. When I try to view the Execution Plan I can't since the SQL Server Management Studio says "Msg 208, Level 16, State 0, Line 31 Invalid object name '#temp'."

Is there any way to view the execution plan (or the execution details (not the plan)) for such script?

Answer

Conrad Frix picture Conrad Frix · Jan 11, 2012

SET SHOWPLAN_TEXT ON (or clicking on Display Estimated Execution Plan is SSMS) creates a plan instead of executing the SQL

Since this creates the #temp

SELECT Id
INTO #temp
FROM table
WHERE ...

this will fail

DELETE FROM #temp
INNER JOIN table2 ON a=b
WHERE ...

So solution is to add this to the top (or do the equivalent via SSMS)

SET SHOWPLAN_TEXT OFF
GO

SET STATISTICS PROFILE ON
GO