在SQL Server 2005中,有两种方法可以创建临时表:

declare @tmp table (Col1 int, Col2 int);

or

create table #tmp (Col1 int, Col2 int);

这两者之间有什么区别?关于@tmp是否仍然使用tempdb,或者是否所有事情都发生在内存中,我读过相互矛盾的意见。

在哪些情况下,一个会优于另一个?


当前回答

@wcm -实际上nit选择表变量不只是Ram -它可以部分存储在磁盘上。

临时表可以有索引,而表变量只能有主索引。如果速度是一个问题,表变量可以更快,但显然如果有很多记录,或者需要搜索聚集索引的临时表,那么临时表将更好。

好的背景文章

其他回答

@wcm -实际上nit选择表变量不只是Ram -它可以部分存储在磁盘上。

临时表可以有索引,而表变量只能有主索引。如果速度是一个问题,表变量可以更快,但显然如果有很多记录,或者需要搜索聚集索引的临时表,那么临时表将更好。

好的背景文章

对于所有相信临时变量只存在于内存中的人

首先,表变量不一定存在于内存中。在内存压力下,属于表变量的页可以被推到tempdb。

在这里阅读文章:TempDB::表变量vs本地临时表

临时表(##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.

令我惊讶的是,没有人提到这两者之间的关键区别是临时表支持并行插入,而表变量不支持。您应该能够从执行计划中看出不同之处。下面是9频道和MSDN doc上的SQL workshop的视频。

这也解释了为什么应该对较小的表使用表变量,否则应该使用临时表,正如SQLMenace前面回答的那样。

另一个区别:

表var只能从创建它的过程中的语句中访问,而不能从该过程调用的其他过程或嵌套的动态SQL(通过exec或sp_executesql)访问。

另一方面,临时表的作用域包括调用过程和嵌套动态SQL中的代码。

如果由过程创建的表必须可以从其他被调用的过程或动态SQL中访问,则必须使用临时表。这在复杂的情况下非常方便。