測試建立表變量先後,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的空間。在所在批處理結束後,佔用會被清除