如何查找导致tempdb增长的SQL语句?


26

服务器(SQL Server 2008)的tempdb每月增加几次,达到500GB +。是否有可能找出导致该问题的SQL语句?这个问题通常不是由造成create table #temp...; insert into #temp...select ... into #temp...而又复杂的连接。

某些tempdb文件的Initial Size每次也会自动设置为更大的值。怎么预防呢?

有时,缓存的计划会阻止调整大小/缩小文件。如何找到哪个持有tempdb?


1
抱歉,将近凌晨2点,我无法完全回答这个问题,但是当您等待其他答案时,这些URL可能会派上用场-mssqltips.com/sqlservertip/1432/…google.com/search?q=哪个+查询+使用+ tempdb
亚伦·伯特兰

Answers:


27

您可以使用三种DMV来跟踪tempdb的使用情况:

前两个可让您在查询和会话级别跟踪分配。第三个跟踪版本存储,用户和内部对象之间的分配。

以下示例查询将为您分配每个会话:

SELECT
  sys.dm_exec_sessions.session_id AS [SESSION ID]
  ,DB_NAME(database_id) AS [DATABASE Name]
  ,HOST_NAME AS [System Name]
  ,program_name AS [Program Name]
  ,login_name AS [USER Name]
  ,status
  ,cpu_time AS [CPU TIME (in milisec)]
  ,total_scheduled_time AS [Total Scheduled TIME (in milisec)]
  ,total_elapsed_time AS    [Elapsed TIME (in milisec)]
  ,(memory_usage * 8)      AS [Memory USAGE (in KB)]
  ,(user_objects_alloc_page_count * 8) AS [SPACE Allocated FOR USER Objects (in KB)]
  ,(user_objects_dealloc_page_count * 8) AS [SPACE Deallocated FOR USER Objects (in KB)]
  ,(internal_objects_alloc_page_count * 8) AS [SPACE Allocated FOR Internal Objects (in KB)]
  ,(internal_objects_dealloc_page_count * 8) AS [SPACE Deallocated FOR Internal Objects (in KB)]
  ,CASE is_user_process
             WHEN 1      THEN 'user session'
             WHEN 0      THEN 'system session'
  END         AS [SESSION Type], row_count AS [ROW COUNT]
FROM 
  sys.dm_db_session_space_usage
INNER join
  sys.dm_exec_sessions
ON  sys.dm_db_session_space_usage.session_id = sys.dm_exec_sessions.session_id

如果要跟踪一段时间的使用情况,请考虑使用sp_whoisactive收集数据,如Kendra Little所示


3
谢谢。会话的占用空间[SPACE Allocated FOR USER Objects (in KB)][SPACE Deallocated FOR USER Objects (in KB)]实际占用的空间是否不同?
u23432534

4

问题可能有多种来源:

  • 表变量或临时表的用法
  • sql server在tempdb中将中间结果集作为工作表创建-通常用于排序目的(通常是缺少索引/过期统计信息的标志)
  • sql server决定预先评估表值函数的结果集,在这种情况下,它将数据存储在tempdb中
  • 使用选项重新创建索引 SORT_IN_TEMPDB = ON
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.