SQL Server daily maintenance ninth: TempDB optimization

Overview of TEMPDB

Tempdb globally stores internal objects, user objects, temporary tables, temporary objects, and stored procedures created by SQL Server operations. Each database instance has only one tempdb, so there may be performance and disk space bottlenecks. The following are the ways to use tempdb space:
Insert picture description here
various forms of available space and excessive DDL/DML operations will cause tempdb to be overloaded. This will cause irrelevant programs running on the server to run slowly or fail.
  Some common problems of tempdb are as follows:
  -Use up all the storage space of
  tempdb-Slow query caused by I/O bottleneck when reading tempdb.
  -Excessive DDL operations cause a bottleneck on the system tables.
  -Distribution competition

TEMPDB commonly used commands

  • TempDB current setting
use tempdb
go
WITH    cte
          AS (
              SELECT    DB_NAME(database_id) AS name,
                        mf.name AS db_filename,
                        mf.physical_name,
                        CAST((mf.size / 128.0) AS DECIMAL(20, 2)) AS initial_size_MB,
                        CAST((df.size / 128.0) AS DECIMAL(20, 2)) AS actual_size_MB,
                        CASE mf.is_percent_growth
                          WHEN 0 THEN STR(CAST((mf.growth / 128.0) AS DECIMAL(10, 2))) + ' MB'
                          WHEN 1 THEN STR(mf.growth) + '%'
                        END AS auto_grow_setting
              FROM      sys.master_files mf
                        JOIN sys.database_files df ON mf.name = df.name
              WHERE     mf.database_id = DB_ID()
             )
    SELECT  *,
            actual_size_MB - initial_size_MB AS change_in_MB_since_restart
    FROM    cte;

Insert picture description here

  • TempDB usage query
SELECT DB_NAME(us.database_id) as DB_Name,
us.internal_objects_alloc_page_count / 128 AS Space_MB_Internal
, us.internal_objects_dealloc_page_count / 128 AS Space_MB_dealloc_Internal, us.internal_objects_alloc_page_count
, SUBSTRING(st.text, (ex.statement_start_offset/2)+1,
        ((CASE ex.statement_end_offset
          WHEN -1 THEN DATALENGTH(st.text)
         ELSE ex.statement_end_offset
         END - ex.statement_start_offset)/2) + 1) AS statement_text --, pl.query_plan
FROM sys.dm_db_session_space_usage us
join sys.dm_exec_requests ex
on ex.session_id = us.session_id
and us.internal_objects_alloc_page_count > 0
left join sys.dm_exec_connections co
on us.session_id = co.session_id
CROSS APPLY sys.dm_exec_sql_text(co.most_recent_sql_handle ) AS st
  • TEMPDB use detail query
#
SELECT top 10 t1.session_id,                                                      
t1.internal_objects_alloc_page_count,  t1.user_objects_alloc_page_count,  
t1.internal_objects_dealloc_page_count , t1.user_objects_dealloc_page_count,  
t3.login_name,t3.status,t3.total_elapsed_time  
from sys.dm_db_session_space_usage  t1   
inner join sys.dm_exec_sessions as t3   
on t1.session_id = t3.session_id   
where (t1.internal_objects_alloc_page_count>0   
or t1.user_objects_alloc_page_count >0  
or t1.internal_objects_dealloc_page_count>0   
or t1.user_objects_dealloc_page_count>0)  
order by t1.internal_objects_alloc_page_count desc

# TEMPDB运用量计算
select <参考internal_objects_alloc_page_count>*8/1024/1024 as [Size_GB]

# TEMPDB运用SQL语句查询
select s.text,p.*
from master.dbo.sysprocesses p   
cross apply sys.dm_exec_sql_text(p.sql_handle) s  
where spid = <Session_id>

  • TEMPDB test statement (you can quickly use TEMPDB for testing)
SELECT *  
from sys.dm_db_session_space_usage  t1,sys.dm_db_session_space_usage  t2,sys.dm_db_session_space_usage  t3,sys.dm_db_session_space_usage  t4,sys.dm_db_session_space_usage  t5
order by 1,2,3,4,5,6,7,8 desc

TEMPDB optimization suggestions

  1. Set the file increment to a reasonable size to avoid too small increment of the tempdb database file. If the increment of the file is too small compared to the amount of data written to tempdb, tempdb may need to expand continuously, which will affect performance.

  2. Create as many files as needed to maximize the disk width. Using multiple files can reduce tempdb storage contention and achieve greater scalability. However, do not create too many files, as this operation may reduce performance and increase management overhead. As a general principle, create a data file (used to explain any association mask settings) for each CPU in the server, and then adjust the number of files up and down as needed. Please note that dual-core CPUs will be treated as two CPUs.

  3. Pre-allocate space for all tempdb files by setting the file size to a value sufficient to accommodate the typical workload in the environment. This prevents tempdb from expanding too frequently and affecting performance. The tempdb database should be set to grow automatically, but this setting will be used to increase disk space when unexpected situations occur.

  4. Make each data file the same size so that the performance of proportional filling can be optimized.

  5. Place the tempdb database in the fast I/O subsystem. If there are many directly connected disks, use disk striping.

  6. Place the tempdb database on a disk other than the disk used by the user database.

TEMPDB position adjustment

※ The following process is just a demonstration of position adjustment, not an actual optimization step.
By default, TempDB may be created along with system tables and placed on the system disk. According to [Place the tempdb database in the fast I/O subsystem. If there are many directly connected disks, please use disk striping] and [place the tempdb database on a disk other than the disk used by the user database]. We need to refer to the following methods to optimize the storage location of TEMPDB files.

  1. Check the logical name of tempdb and its location. You can use the following statement:
SELECT name, physical_name
FROM sys.master_files
WHERE database_id = DB_ID('tempdb');

Insert picture description here
Physical file:
Insert picture description here
2. Execute TEMPDB path change command

USE master;
GO
ALTER DATABASE tempdb 
MODIFY FILE (NAME = tempdev, SIZE = 10MB, MAXSIZE = 10MB, FILEGROWTH = 10%, FILENAME = 'D:\tempdb\tempdb.mdf');
GO
ALTER DATABASE tempdb 
MODIFY FILE (NAME = temp2, SIZE = 10MB, MAXSIZE = 10MB, FILEGROWTH = 10%, FILENAME = 'D:\tempdb\tempdb_mssql_2.ndf');
GO
ALTER DATABASE tempdb 
MODIFY FILE (NAME = temp3, SIZE = 10MB, MAXSIZE = 10MB, FILEGROWTH = 10%, FILENAME = 'D:\tempdb\tempdb_mssql_3.ndf');
GO
ALTER DATABASE tempdb 
MODIFY FILE (NAME = temp4, SIZE = 10MB, MAXSIZE = UNLIMITED, FILEGROWTH = 10%, FILENAME = 'D:\tempdb\tempdb_mssql_4.ndf');
GO
ALTER DATABASE  tempdb 
MODIFY FILE (NAME = templog, SIZE = 10MB, MAXSIZE = UNLIMITED, FILEGROWTH = 10%, FILENAME = 'D:\tempdb\templog.ldf');
GO

Parameter explanation: https://docs.microsoft.com/zh-cn/sql/t-sql/statements/alter-database-transact-sql-file-and-filegroup-options?view=sql-server-ver15
Insert picture description here

Insert picture description here
Microsoft SQL Server Management Studio information view:
Insert picture description here

  1. SQL Server database service restart

Service name: SQL Server
Insert picture description here

  1. Check the logical name of tempdb and its location. You can use the following statement:
SELECT name, physical_name
FROM sys.master_files
WHERE database_id = DB_ID('tempdb');

Insert picture description here
Physical file:
Insert picture description here

  1. The original TEMPDB file can be deleted to free up space

This step requires manual operation, the system will not automatically delete the old TEMPDB file
Insert picture description here

Common mistakes of TEMPDB

Insert picture description here

  1. Errors caused by insufficient transaction logs, it is recommended to change the recovery mode to Sample
The transaction log for database 'tempdb' is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases
数据库 'tempdb' 的事务日志已满。若要查明无法重用日志中的空间的原因,请参阅 sys.databases 中的 log_reuse_wait_desc 列。
  1. Errors caused by insufficient data storage, it is recommended to optimize SQL statements or increase TEMPDB files
"Could not allocate space for object 'dbo.TempTable_xxxx' in database 'db_yyyy' because the 'PRIMARY' filegroup is full. Create disk space by deleting unneeded files, dropping objects in the filegroup, adding additional files to the filegroup, or setting autogrowth on for existing files in the filegroup."
消息 1105,级别 17,状态 2,第 1 行
无法为数据库 'tempdb' 中的对象 'dbo.SORT temporary run storage:  140737503494144' 分配空间,因为 'PRIMARY' 文件组已满。请删除不需要的文件、删除文件组中的对象、将其他文件添加到文件组或为文件组中的现有文件启用自动增长,以便增加可用磁盘空间。

Guess you like

Origin blog.csdn.net/weixin_38623994/article/details/112557011