在SQL Server 2005中,有两种方法可以创建临时表:
declare @tmp table (Col1 int, Col2 int);
or
create table #tmp (Col1 int, Col2 int);
这两者之间有什么区别?关于@tmp是否仍然使用tempdb,或者是否所有事情都发生在内存中,我读过相互矛盾的意见。
在哪些情况下,一个会优于另一个?
在SQL Server 2005中,有两种方法可以创建临时表:
declare @tmp table (Col1 int, Col2 int);
or
create table #tmp (Col1 int, Col2 int);
这两者之间有什么区别?关于@tmp是否仍然使用tempdb,或者是否所有事情都发生在内存中,我读过相互矛盾的意见。
在哪些情况下,一个会优于另一个?
当前回答
@wcm -实际上nit选择表变量不只是Ram -它可以部分存储在磁盘上。
临时表可以有索引,而表变量只能有主索引。如果速度是一个问题,表变量可以更快,但显然如果有很多记录,或者需要搜索聚集索引的临时表,那么临时表将更好。
好的背景文章
其他回答
另一个主要区别是表变量没有列统计信息,而临时表有。这意味着查询优化器不知道表变量中有多少行(它猜测是1),如果表变量实际上有大量行,这可能导致生成高度非优化的计划。
对于所有相信临时变量只存在于内存中的人
首先,表变量不一定存在于内存中。在内存压力下,属于表变量的页可以被推到tempdb。
在这里阅读文章:TempDB::表变量vs本地临时表
@wcm -实际上nit选择表变量不只是Ram -它可以部分存储在磁盘上。
临时表可以有索引,而表变量只能有主索引。如果速度是一个问题,表变量可以更快,但显然如果有很多记录,或者需要搜索聚集索引的临时表,那么临时表将更好。
好的背景文章
临时表(##temp/#temp)和表变量(@table)之间的区别如下:
Table variable (@table) is created in the memory. Whereas, a Temporary table (##temp/#temp) is created in the tempdb database. However, if there is a memory pressure the pages belonging to a table variable may be pushed to tempdb. Table variables cannot be involved in transactions, logging or locking. This makes @table faster then #temp. So table variable is faster then temporary table. Temporary table allows Schema modifications unlike Table variables. Temporary tables are visible in the created routine and also in the child routines. Whereas, Table variables are only visible in the created routine. Temporary tables are allowed CREATE INDEXes whereas, Table variables aren’t allowed CREATE INDEX instead they can have index by using Primary Key or Unique Constraint.
在哪些情况下,一个会优于另一个?
对于较小的表(小于1000行),使用临时变量,否则使用临时表。