我是否可以安全地假设我使用tempdb
来编写临时表的存储过程,我最好将它们切换到表变量以获得更好的性能?
3 回答
@Table can be faster as there is less "setup time" since the object is in memory only.
@Tables have a lot of catches though.
You can have a primary key on a @Table but thats about it. Other indexes Clustered NonClustered for combinations of columns are not possible.
Also if your table is going to contain any real data volumes (more then about 200 maybe 1000 rows) then accessing the table will be slower. Especially when you will probably not have a useful index on it.
#Tables are a pain in procs as they need to be dropped when debugging, They take longer to create. and they take longer to setup as you need to add indexs as a second step. But if you have lots of data then its #tables every time.
Even in cases where you have less then 100 rows of data in a table you may still want to use #Tables as you can create a usefull index on the table.
In summary i use @Tables most of the time for the ease when doing simple proc etc. But anything that need to perform should be a #Table.
临时表的性能更好。如果使用表变量并且变量中的数据太大,SQL Server 会自动将变量转换为临时表。
就像几乎所有与数据库相关的问题一样,它取决于您尝试做什么。因此,如果没有更多信息,很难回答。
所以我的回答是,试一试,看看执行计划。以最低的成本使用最快的方式。
@Tables 没有统计信息,因此执行计划需要更多的猜测。因此建议的上限为 1000 行。#Tables 有统计信息,但这些可以在调用之间缓存。如果每次 SP 运行时您的基数都显着不同,那么您每次都希望REBUILD
如此RECOMPILE
。当然,这是一项开销,但必须与垃圾计划的成本相平衡。
两种类型都会对 TempDB 进行 IO。
所以不,@Tables 不是灵丹妙药。