测试建立表变量先后,tempdb的空间大小,目前使用sp_spaceused获得大小,也能够使用视图sys.dm_db_file_space_usage缓存
use tempdb go Set nocount on Exec sp_spaceused /*插入数据以前*/ declare @tmp_orders table ( list_no int,id int) insert into @tmp_orders(list_no,id) select ROW_NUMBER() over( order by Id ) list_no,id from Test.dbo.Orders Select top(1) name,object_id,type,create_date from sys.objects Where type='U' Order by create_date Desc Exec sp_spaceused /*插入数据以后*/ Go Exec sp_spaceused /*Go以后*/
执行结果以下:测试
能够看到:spa
1) 在表变量建立完毕,同时批处理语句没有结束时,临时库的空间增大了接近9M空间。建立表变量的语句结束后,空间释放code
2)在临时库的对象表sys.objects中可以查询到刚刚建立的表变量对象对象
继续验证是否发生IO操做,使用视图sys.dm_io_virtual_file_statsblog
在建立表变量先后执行以下语句:ip
select db_name(database_id) database_name,* from sys.dm_io_virtual_file_stats(db_id('tempdb'), NULL)
测试结果以下:内存
1* 建立表变量前it
2*建立表变量后io
declare @tmp_orders table ( list_no int,id int) insert into @tmp_orders(list_no,id) select ROW_NUMBER() over( order by Id ) list_no,id from Test.dbo.Orders --查询tempdb库中最后建立的对象 Select top(1) name,object_id,type,create_date from sys.objects Where type='U' Order by create_date Desc --查询内存中缓存页数 SELECT count(*)AS cached_pages_count ,name ,index_id FROM sys.dm_os_buffer_descriptors AS bd INNER JOIN ( SELECT object_name(object_id) AS name ,index_id ,allocation_unit_id FROM sys.allocation_units AS au INNER JOIN sys.partitions AS p ON au.container_id = p.hobt_id AND (au.type = 1 OR au.type = 3) UNION ALL SELECT object_name(object_id) AS name ,index_id, allocation_unit_id FROM sys.allocation_units AS au INNER JOIN sys.partitions AS p ON au.container_id = p.partition_id AND au.type = 2 ) AS obj ON bd.allocation_unit_id = obj.allocation_unit_id WHERE database_id = db_id() GROUP BY name, index_id ORDER BY cached_pages_count DESC
测试结果以下:
能够看到表变量建立后,数据页面也会缓存在Buffer Pool中。但所在的批处理语句结束后,占用空间会被释放。
3. 结论
SQL Server在批处理中建立的表变量会产生IO操做,占用tempdb的空间,以及内存bufferPool的空间。在所在批处理结束后,占用会被清除