Table variable poor performance on insert in SQL Server Stored Procedure

≡放荡痞女 提交于 2019-11-28 11:13:48

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.

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.

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!