Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Temp Tables in a Stored Procedure will it cause recompilation of execution plan

If I have Temp Tables being created in a stored procedure's definition and then dropping them when I am done with them will it result in recompilation of execution plan?

For stored procedures every time its called? Any personal Experience? Any explanation please?

As when the temp tables are dropped at the end of every call, the execution plan becomes invalid. Does SQL Server still keep hold of the execution plan and reuse on next call or does it recompile it every time its called.

like image 403
M.Ali Avatar asked Oct 27 '13 20:10

M.Ali


People also ask

Can you use temp tables in Stored Procedures?

Stored procedures can reference temporary tables that are created during the current session. Within a stored procedure, you cannot create a temporary table, drop it, and then create a new temporary table with the same name.

Should I drop temp table in stored procedure?

If you are wondering why it is not required to drop the temp table at the end of the stored procedure, well, it is because when the stored procedure completes execution, it automatically drops the temp table when the connection/session is dropped which was executing it. Well, that's it.

What is the benefit of executing a query in a temporary table?

The key advantage of using temporary tables is that they are visible only to the current session and they are dropped automatically when the session is closed.

What happens to temp table in SQL Server?

A Local Temp Table is available only for the session that has created it. It is automatically dropped (deleted) when the connection that has created it, is closed.


1 Answers

Dropping of a temporary table doesn't matter. If a table is created (either permanent or temporary), all statement after that statement are recompiled (even if they don’t refer to the table). Calls to executable objects using EXEC aren’t recompiled. That's because SQL Server can create the plan after the objects are created. (In this case, the temp. table.)

You can monitor recompilation using Extended Events and its sql_statement_recompile or SQL Trace / SQL Server Profiler SQL:StmtRecompile.

  1. A statement starts to execute. SP:StmtStarting or SQL:StmtStarting is raised
  2. The statement is recompiled. SQL:StmtRecompile is raised. SP:StmtStarting or SQL:StmtStarting is raised again
  3. The statement is finished. SP:StmtCompleted or SQL:StmtCompleted is raised

Not the whole procedure is recompiled but only individual statements.

like image 155
E.K. Avatar answered Sep 27 '22 23:09

E.K.