-- 检查tempdb文件大小和可用空间 SELECT name AS [File Name], physical_name AS [Physical Name], size/128.0AS [Total Size in MB], size/128.0-CAST(FILEPROPERTY(name, 'SpaceUsed') ASINT)/128.0AS [Available Space in MB], [file_id], [type_desc] FROM tempdb.sys.database_files;
-- 检查当前tempdb使用情况 SELECT session_id, request_id, space_used_kb/1024as space_used_mb, space_used_kb/1024.0/1024.0as space_used_gb FROM sys.dm_db_session_space_usage WHERE space_used_kb >0 ORDERBY space_used_kb DESC;
-- 增加现有tempdb文件大小 USE master; GO ALTER DATABASE tempdb MODIFY FILE (NAME ='tempdev', SIZE = 新大小MB);
b. 添加新的 tempdb 文件:
1 2 3 4 5 6 7 8 9 10
-- 添加新的tempdb数据文件 USE master; GO ALTER DATABASE tempdb ADD FILE ( NAME ='tempdev2', FILENAME ='D:\SQL\tempdb2.mdf', SIZE = 初始大小MB, FILEGROWTH = 增长大小MB );
检查是否有大量临时对象占用空间:
1 2 3 4 5 6 7 8
-- 检查临时对象 SELECT obj.name, obj.create_date, OBJECT_SCHEMA_NAME(obj.object_id) as schema_name, obj.type_desc FROM tempdb.sys.objects obj WHERE obj.is_ms_shipped =0 ORDERBY obj.create_date DESC;
检查当前运行的进程:
1 2 3 4 5 6 7 8 9 10 11
-- 检查可能占用大量tempdb空间的查询 SELECT r.session_id, r.command, r.status, r.wait_type, r.wait_time, OBJECT_NAME(t.objectid) as object_name, t.text FROM sys.dm_exec_requests r CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) t WHERE r.session_id >50; -- 排除系统进程
优化建议:
a. tempdb 优化配置:
1 2 3 4 5
-- 设置tempdb文件的理想配置 USE master; GO ALTER DATABASE tempdb MODIFY FILE (NAME ='tempdev', SIZE =1024MB, FILEGROWTH =256MB);
b. 追踪 tempdb 使用情况:
1 2 3 4 5 6 7 8
-- 创建追踪标记来监控tempdb使用 CREATE EVENT SESSION [TempDB_Usage] ON SERVER ADD EVENT sqlserver.temp_table_creation_event, ADD EVENT sqlserver.temp_table_deletion_event ADD TARGET package0.event_file (SET filename=N'C:\TempDB_Usage.xel'); GO ALTER EVENT SESSION [TempDB_Usage] ON SERVER STATE =START;