Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Table variable poor performance on insert in SQL Server Stored Procedure

We are experiencing performance problems using a table variable in a Stored Procedure.

Here is what actually happens :

DECLARE @tblTemp TABLE(iId_company INT)

INSERT INTO @tblTemp(iId_company)
  SELECT id FROM .....

The SELECT returns 138 results, but inserting in the TABLE variable takes 1min15 but when I use a temp table with the same SELECT, woops, takes 0sec :

CREATE TABLE #temp (iId_company INT)

INSERT INTO #temp(iId_company)
  SELECT id FROM ...

What could cause the behavior ?

like image 996
MaxiWheat Avatar asked Oct 29 '09 13:10

MaxiWheat


People also ask

How can we increase the performance of insert query in SQL Server?

Drop Index before Insertion of Data We should drop the index before insertion of a large amount of data. This makes the insert statement run faster. Once the inserts are completed, you can recreate the index again.

Does table variable need to be dropped?

Insert data into a table variable. We do not require dropping the table variable. As mentioned earlier, the scope of the table variable is within the batch. The scope of it lasts at the end of the batch or procedure.

What is option recompile in SQL Server?

What is the RECOMPILE option? The compilation is the process when a query execution plan of a stored procedure is optimized based on the current database objects state. This query execution plan is often stored in the cache to be quickly accessed. Recompilation is the same process as a compilation, just executed again.


1 Answers

Use a temporary table. You will see much better performance.

A detailed explanation for the reasoning behind this is beyond the scope of the initial question however to summarise:

  • A table variable is optimized for one row, by SQL Server i.e. it assumes 1 row will be returned.
  • A table variable does not create statistics.

Google temp table Vs. table variable for a wealth of resources and discussions. If you then need specific assistance, fire me an email or contact me on Twitter.

like image 145
John Sansom Avatar answered Sep 17 '22 20:09

John Sansom