|
此文章由 乱码 原创或转贴,不代表本站立场和观点,版权归 oursteps.com.au 和作者 乱码 所有!转贴必须注明作者、出处和本声明,并保持内容完整
原帖由 marklan001 于 2011-1-24 20:43 发表 ![](http://www.oursteps.com.au/bbs/images/common/back.gif)
个人感觉Temp Table,Table Variable and CTE适用的场合不同
1. DATE SET很大且需要INDEX的时候用应当用Temp Table,不需要INDEX的时候用Table Variable。
2. 当SERVER内存充足时,Temp Table,Table Variable会保存在内存 ...
仔细查了一下资料,得到下面的东西:
关于temp table(inside ms sql server tsql programming,chaper2):
Temporary tables are created in tempdb, regardless of the database context of your session. They have physical representation in tempdb, although when they're small enough and Microsoft SQL Server has enough memory to spare, their pages will reside in cache. SQL Server will persist the temporary table's pages on disk when there is too little free memory.
关于table variable(inside ms sql server tsql programming,chaper2):
To dispel what probably is the most widespread myth involving table variables, let me state that they do have physical representation in tempdb, very similar to temporary tables. As proof, run the following code that shows which temporary tables currently exist in tempdb by querying metadata info, creates a table variable, and queries metadata info again:
SELECT TABLE_NAME FROM tempdb.INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE '%#%';
GO
DECLARE @T TABLE(col1 INT);
INSERT INTO @T VALUES(1);
SELECT TABLE_NAME FROM tempdb.INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE '%#%';
When I ran this code, the first batch returned no output, while the second returned #0CBAE877, which is the name of the temporary table in tempdb that represents the table variable @T. Of course, you will probably get a different name when you run this code. But the point is to show that there is a hidden temporary table created behind the scenes. Just like temporary tables, a table variable's pages will reside in cache when the table is small enough and when SQL Server has enough memory to spare. So the discussion about aspects of working with temporary tables with regard to tempdb applies to table variables as well.
---------
还有sql server central 的一篇文章:
http://www.sqlservercentral.com/Forums/Topic415829-338-1.aspx
cte performance最大的好处是可以让sql inline,让sql server engine自己作优化,这也是为什么几个cte之间无法用profiler来做tracing,逻辑上清晰它跟temp table/table varialbe是一样的,没什么优势。
[ 本帖最后由 乱码 于 2011-1-25 11:28 编辑 ] |
|