Table variable poor performance on insert in SQL S

2019-01-18 23:53发布

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 ?

4条回答
ら.Afraid
2楼-- · 2019-01-19 00:30

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.

查看更多
霸刀☆藐视天下
3楼-- · 2019-01-19 00:37

Generally, for smaller sets of data, a table variable should be faster than a temp table. For larger sets of data, performance will fall off because table variables don't support parallelism (see this post).

With that said, I haven't experienced, or found experience with such a small set of data being slower for a table variable vs a temp table.

查看更多
Root(大扎)
4楼-- · 2019-01-19 00:41

Not that it should matter but what does your select look like? I had an issue in SQL Server 2005 where my select on it's own ran relatively fast for what my query was doing say 5 minutes to return all the data over the wire about 150,000 rows. But when I tried to insert that same select into a temp table or table variable the statement ran for more than 1 hour before I killed it. I have yet to figure out what really was going on. I ended up adding the query hint force order and it started inserting faster.

查看更多
beautiful°
5楼-- · 2019-01-19 00:41

Key point about temp tables also is that you can put indexes, etc on them whereas you can't with table variables.

查看更多
登录 后发表回答