数据文件shrink

This article explores the usage of TempDB and different ways to shrink the TempDB database in SQL Server

本文探讨了TempDB的用法以及在SQL Server中缩小TempDB数据库的不同方法

Each instance of Microsoft SQL Server has a system database TempDB. It is a backbone for the SQL Server instance. Let’s review the TempDB database and its usage with ways to shrink the TempDB database in the further sections of this article.

Microsoft SQL Server的每个实例都有一个系统数据库TempDB 。 它是SQL Server实例的骨干。 让我们在本文的其他部分中回顾一下TempDB数据库及其用法,以及如何缩小TempDB数据库的方法。

关于TempDB的一些要点 (Few important points about TempDB)

  • TempDB is a global resource (available for all connected user) system database TempDB是全局资源(可供所有连接的用户使用)系统数据库
  • SQL Server recreates the TempDB database each time SQL Service restarts. During restart, it takes a copy of MDF and LDF from the model database. The size and number of MDF and LDF files reset to preconfigured size 每次重新启动SQL Service时,SQL Server都会重新创建TempDB数据库。 重新启动期间,它将从模型数据库中获取MDF和LDF的副本。 MDF和LDF文件的大小和数量重置为预配置的大小
  • SQL Server does not perform recovery on the TempDB, and previous data is lost SQL Server不会在TempDB上执行恢复,并且以前的数据会丢失
  • TempDB database is always in the Simple recovery model, and we cannot take database backup for it TempDB数据库始终处于简单恢复模型中,因此我们无法为其进行数据库备份
  • We cannot roll back transactions in the TempDB because it minimally logs the transactions 我们无法在TempDB中回滚事务,因为它最少地记录了事务

TempDB使用情况摘要 (TempDB Usage Summary)

  • Usually, we create local temporary tables (# naming conventions) and global temporary tables (## naming conventions) to prepare intermediate tables. SQL Server creates those temporary tables in the TempDB database 通常,我们创建本地临时表(#命名约定)和全局临时表(##命名约定)以准备中间表。 SQL Server在TempDB数据库中创建这些临时表
  • We can create or rebuild an index in TempDB using the SORT_IN_TEMPDB= ON clause. SQL Server performs all sorting calculations in the TempDB instead of the database on which the object belongs 我们可以使用SORT_IN_TEMPDB = ON子句在TempDB中创建或重建索引。 SQL Server在TempDB中而不是对象所属的数据库中执行所有排序计算
  • SQL Server uses the TempDB for the Read COMMITTED SNAPSHOT isolation level. SQL Server uses the row versioning for each record. The old version also gets an additional 14 bytes in the TempDB to track the row versioning SQL Server将TempDB用于读取已提交快照隔离级别。 SQL Server对每条记录使用行版本控制。 旧版本还在TempDB中获得额外的14个字节来跟踪行版本控制
  • Internal objects such as Cursor work tables, Spool operations, Intermediate sorts operations such as GROUP BY, ORDER BY, UNION, DBCC CHECKDB, Temporary large object storage, Service broker event notification 内部对象,例如游标工作表,假脱机操作,中间排序操作,例如GROUP BY,ORDER BY,UNION,DBCC CHECKDB,临时大对象存储,Service Broker事件通知
  • In the Multiple Active Result Sets (using MultipleActiveResultSets=True), SQL Server uses the versioning and stores that in the TempDB 在多个活动结果集中(使用MultipleActiveResultSets = True),SQL Server使用版本控制并将其存储在TempDB中

You can go through these articles, Configuration, operations and restrictions of the TempDB SQL Server system database and How to monitor the SQL Server TempDB database to get more details on the TempDB database.

您可以阅读以下文章, TempDB SQL Server系统数据库的配置,操作和限制以及如何监视SQL Server TempDB数据库以获取有关TempDB数据库的更多详细信息。

收缩TempDB活动概述 (Overview of Shrink TempDB activity)

Starting from SQL Server 2016, the installation wizard automatically detects the CPU cores and creates the necessary number of database files for the TempDB. It also sets the maximum growth of individual files to 64 MB.

从SQL Server 2016开始,安装向导将自动检测CPU内核并为TempDB创建所需数量的数据库文件。 它还将单个文件的最大增长设置为64 MB。

In the following screenshot, you can see the TempDB configuration for my demo SQL instance.

在以下屏幕截图中,您可以看到我的演示SQL实例的TempDB配置。

For this demonstration, I will disable the Autogrowth for the TempDB database.

对于此演示,我将禁用TempDB数据库的自动增长。

  • Note: Please do not ever do this on the production instance; I am doing it on my test instance for demo purposes only 注意:请勿在生产实例上执行此操作; 我在测试实例上进行此操作仅出于演示目的

Execute the following query to create a local temporary table and insert data into it.

执行以下查询以创建本地临时表并将数据插入其中。

CREATE TABLE #TempTable (col1 char(1000), col2 char(1000))SET NOCOUNT ON;DECLARE @i INT = 1BEGIN TRANWHILE @i <= 150000BEGININSERT INTO #TempTable values ('A','B')SET @i += 1ENDCOMMIT TRANDROP TABLE #TempTable

It gives the following error message. SQL Server could not increase the size of the TempDB log file and unable to perform the transaction. You might think that we disabled the autogrowth, and if we enable autogrowth to resolve the issue. Consider this situation like the TempDB log file grown to the size of the disk, and you do not have sufficient free space in the disk for the log file to grow.

它给出以下错误信息。 SQL Server无法增加TempDB日志文件的大小,并且无法执行事务。 您可能会认为我们禁用了自动增长功能,并且如果启用了自动增长功能就可以解决此问题。 考虑这种情况,例如TempDB日志文件增长到磁盘大小,并且磁盘中没有足够的可用空间来增长日志文件。

Let’s enable the autogrowth for data files with a maximum size of 20MB for each data file. We can see that log file growth for the TempDB is enabled, and it does not have maximum file size.

让我们为数据文件启用自动增长,每个数据文件的最大大小为20MB。 我们可以看到TempDB的日志文件增长已启用,并且没有最大文件大小。

Let’s rerun the query to fill up TempDB and see the error message. SQL Server primary filegroup does not have free space.

让我们重新运行查询以填充TempDB并查看错误消息。 SQL Server主文件组没有可用空间。

At this point, if you try to refresh SQL instance as well, you get a similar error message.

此时,如果您也尝试刷新SQL实例,则会收到类似的错误消息。

收缩TempDB数据库的不同方法 (Different ways to shrink TempDB database)

You can look at the disk usage by top tables report to check what are the objects consuming space in the TempDB. Right-click on the TempDB-> go to Reports-> Standard Reports-> Disk Usage by Top Tables.

您可以按顶部表格报告查看磁盘使用情况,以检查哪些对象占用了TempDB中的空间。 右键单击TempDB->转到“报告”->“标准报告”->“按顶级表的磁盘使用情况”。

In this screenshot, we can see #TempTable is consuming the space in the TempDB.

在此屏幕截图中,我们可以看到#TempTable正在占用TempDB中的空间。

You can drop the existing object in the TempDB, and it should release the space for you. It is not possible every time to drop objects, especially in the production instance. We could lose all previous work due to this.

您可以将现有对象放在TempDB中,它应该为您释放空间。 不可能每次都放下对象,尤其是在生产实例中。 因此,我们可能会丢失所有以前的工作。

使用DBCC SHRINKFILE收缩TEMPDB (Shrink TEMPDB using DBCC SHRINKFILE)

We can use the DBCC SHRINKFILE command to shrink the data or log file for the TempDB. We do not need a restart of SQL Service in this case.

我们可以使用DBCC SHRINKFILE命令来缩小TempDB的数据或日志文件。 在这种情况下,我们不需要重新启动SQL Service。

DBCC SHRINKFILE(logical_filename, size_in_MB)

Execute the following query to get individual file size in TempDB.

执行以下查询以获取TempDB中的单个文件大小。

SELECT name, file_id, type_desc, size * 8 / 1024 [TempdbSizeInMB]
FROM tempdb.sys.database_files
ORDER BY type_desc DESC, file_id;

Let’s try to shrink TempDev data file using the DBCC SHRINKFILE command.

让我们尝试使用DBCC SHRINKFILE命令缩小TempDev数据文件。

DBCC SHRINKFILE(tempdev,10)

It performs the shrink, and you get the following output.

它执行收缩,并获得以下输出。

You can further try to shrink the file.

您可以进一步尝试缩小文件。

DBCC SHRINKFILE(tempdev,0)

In this way, we need to shrink the individual data or log files.

这样,我们需要缩小单个数据或日志文件。

使用DBCC SHRINKDATABASE命令收缩TEMPDB (Shrink TEMPDB using DBCC SHRINKDATABASE command)

We can also shrink the TempDB database using the DBCC SHRINKDATABASE command. The Syntax for the command is as follows.

我们还可以使用DBCC SHRINKDATABASE命令来缩小TempDB数据库。 该命令的语法如下。

DBCC SHRINKDATABASE(TempDB, ‘target_percentage_of_free_space’);

Let’s use this command to shrink TempDB and leave 10 percent free space.

让我们使用此命令缩小TempDB并保留10%的可用空间。

DBCC SHRINKDATABASE(tempdb, 10);

It performs the database level shrink, and you get the following output.

它执行数据库级别的收缩,并获得以下输出。

You can check the size of the data and log files for the database using tempdb.sys.database_files.

您可以使用tempdb.sys.database_files检查数据库的数据和日志文件的大小。

使用ALTER DATABASE命令调整TempDB的大小 (Resize TempDB using ALTER DATABASE command)

We can use the Alter command to resize the tempdb files. Suppose the initial size of the data and log is 1 GB, we can use this command to set it at a lower level.

我们可以使用Alter命令来调整tempdb文件的大小。 假设数据和日志的初始大小为1 GB,我们可以使用此命令将其设置为较低的级别。

The following command resizes the TempDEV and TempLog file initial size to 100 MB.

以下命令将TempDEV和TempLog文件的初始大小调整为100 MB。

USE master;GOALTER DATABASE tempdbMODIFY FILE (NAME = tempdev, SIZE=100Mb);GOALTER DATABASE tempdbMODIFY FILE (NAME = templog, SIZE=100Mb);GO

We need to restart SQL Services for this setting to take effect.

我们需要重新启动SQL Services才能使此设置生效。

使用SSMS收缩TempDB (Shrink TempDB using SSMS)

We can use the SSMS GUI method to shrink the TempDB as well. Right-click on the TempDB and go to Tasks. In the tasks list, click on Shrink, and you can select Database or files.

我们也可以使用SSMS GUI方法来缩小TempDB。 右键单击TempDB,然后转到“任务”。 在任务列表中,单击“收缩”,然后可以选择“数据库”或“文件”。

Both Database and Files options are similar to the DBCC SHRINKDATABASE and DBCC SHRINKFILE command we explained earlier.

“数据库”和“文件”选项都与我们之前介绍的DBCC SHRINKDATABASE和DBCC SHRINKFILE命令相似。

重新启动SQL Services以收缩TempDB数据库 (Restart SQL Services to Shrink TempDB database)

It should be the last option to recycle the TempDB database and resolve the disk space-related issues due to the TempDB data or log file space. In the production instance, it is difficult to find the downtime to restart the SQL Service. Therefore, you should consider the other options first and do it as a last option.

应该是回收TempDB数据库并解决由于TempDB数据或日志文件空间而导致的磁盘空间相关问题的最后一个选择。 在生产实例中,很难找到停机时间来重新启动SQL Service。 因此,您应该首先考虑其他选项,并将其作为最后一个选项。

如果您尝试缩小Tempdb,但不会释放空间怎么办? (What if you try to shrink Tempdb, but it does not release space?)

Sometimes you try to shrink the TempDB database and the command shows successful, but you do not see any free space in the database. It might be due to active transactions, versioning or objects required for the SQL Server in the TempDB as per the current workload.

有时,您尝试缩小TempDB数据库,并且命令显示成功,但是在数据库中看不到任何可用空间。 根据当前工作负载,这可能是由于TempDB中SQL Server所需的活动事务,版本控制或对象所致。

Referencing to Microsoft article, we should shrink the TempDB when the SQL Server is in idle mode or the single-user mode.

参考Microsoft文章 ,当SQL Server处于空闲模式或单用户模式时,我们应该缩小TempDB。

We can still try to shrink the TempDB using the following method.

我们仍然可以尝试使用以下方法缩小TempDB。

  • Execute the DBCC DROPCLEANBUFFERS command to flush cached indexes and data pages

    执行DBCC DROPCLEANBUFFERS命令以刷新缓存的索引和数据页

    CHECKPOINT;GODBCC DROPCLEANBUFFERS;GO
    
  • Execute the DBCC FREEPROCCACHE command to clear the procedural cache

    执行DBCC FREEPROCCACHE命令以清除过程缓存

    DBCC FREEPROCCACHE;GO
    

Now, try to shrink the database using the earlier methods. You should give preference to DBCC SHRINKFILE instead of the DBCC SHRINKDATABASE command.

现在,尝试使用早期方法缩小数据库。 您应该优先使用DBCC SHRINKFILE而不是DBCC SHRINKDATABASE命令。

在单用户模式下收缩TempDB (Shrink TempDB in Single user mode)

Sometimes you cannot start the SQL Services due to TempDB size, and you require to reset the initial size using the alter database command. Suppose you executed the alter database command to resize the tempdb data file, but accidentally you specified the initial size of the file that is not feasible as per your free disk space. You tried to restart SQL Service, but it could not start because there is not sufficient free space in the drive to create the TempDB files.

有时由于TempDB的大小而无法启动SQL Services,并且您需要使用alter database命令重置初始大小。 假设您执行了alter database命令来调整tempdb数据文件的大小,但是偶然地您指定了该文件的初始大小,这对于您的可用磁盘空间是不可行的。 您尝试重新启动SQL Service,但由于驱动器中没有足够的可用空间来创建TempDB文件而无法启动。

You need to start SQL Services in minimal configuration mode and resize the TempDB files.

您需要以最小配置模式启动SQL Services并调整TempDB文件的大小。

SQL Services should be in the stopped state to use the minimal configuration mode.

SQL Services应该处于停止状态以使用最小配置模式。

  • Open a command prompt with administrative privilege 以管理员权限打开命令提示符
  • Go to the SQL Server Binary folder. In my SQL instance, the path for the BINN folder is as follows

    转到“ SQL Server Binary”文件夹。 在我SQL实例中,BINN文件夹的路径如下

    C:\Program Files\Microsoft SQL Server\MSSQL15.SQL2019CTP\MSSQL\Binn

    C:\ Program Files \ Microsoft SQL Server \ MSSQL15.SQL2019CTP \ MSSQL \ Binn

    If you are not sure about the path, right-click on SQL Service in SQL Server Configuration Manager and the properties page, you can look at Binary path

    如果不确定路径,请在“ SQL Server配置管理器”和属性页中右键单击“ SQL服务”,可以查看“二进制路径”。

  • Execute the following command in administrative prompt ( for my SQL2019CTP instance)

    在管理提示下执行以下命令(对于我SQL2019CTP实例)

    sqlservr.exe -s SQL2019CTP -c -f

    sqlservr.exe -s SQL2019CTP -c -f

    It starts SQL Services in minimal configuration mode, and you can see it as a warning message as well

    它以最小配置模式启动SQL Services,您也​​可以将其视为警告消息。

  • Open another command prompt and connect to the SQL server using the SQLCMD

    打开另一个命令提示符并使用SQLCMD连接到SQL Server

    • Note: Only one administrator can connect to SQL Server at this time. If you try to connect, you get the following error message

      注意:此时,只有一名管理员可以连接到SQL Server。 如果您尝试连接,则会收到以下错误消息

    Now, we can run the alter database command to resize the TempDB. You need to run the alter database command for eachtempdb file

    现在,我们可以运行alter database命令来调整TempDB的大小。 您需要为每个tempdb文件运行alter database命令

    USE master;GOALTER DATABASE tempdbMODIFY FILE (NAME = tempdev, SIZE=100Mb);GOALTER DATABASE tempdbMODIFY FILE (NAME = templog, SIZE=100Mb);GO
    
  • Return the administrative command prompt in which we started SQL Service in minimal configuration mode and press CTRL+C to exit

    返回以最小配置模式启动SQL Service的管理命令提示符,然后按CTRL + C退出

  • Start the SQL Services using the SQL Server Configuration Manager and verify the changes using the following query

    使用SQL Server配置管理器启动SQL Services,并使用以下查询验证更改

    SELECT name, file_id, type_desc, size * 8 / 1024 [TempdbSizeInMB]FROM sys.master_filesWHERE DB_NAME(database_id) = 'tempdb'ORDER BY type_desc DESC, file_id GO
    

    In the screenshot, we can see that initial size for the TempDev and TempLog file is 100 MB

    在屏幕截图中,我们可以看到TempDev和TempLog文件的初始大小为100 MB

结论 (Conclusion)

In this article, we explored the importance of the TempDB database in SQL Server and various methods to shrink the TempDB database. You should be aware of all these methods and take appropriate actions if required.

在本文中,我们探讨了SQL Server中的TempDB数据库的重要性以及缩小TempDB数据库的各种方法。 您应该了解所有这些方法,并在需要时采取适当的措施。

翻译自: https://www.sqlshack.com/overview-of-the-shrink-tempdb-database-in-sql-server/

数据文件shrink

数据文件shrink_SQL Server中的Shrink TempDB数据库概述相关推荐

  1. 使用T-SQL导入多个文件数据到SQL Server中一文的疑惑

    - 今天,由于毕业论文需要,我想弄数据转换,所以看了一看T-SQL,oracle实在没时间去学,好在SQL我还是很熟悉,所以打算看一看,写一些存储过程来完成任务. 我无意中在csdn上找到这样一篇文章 ...

  2. SQL Server 中4个系统数据库,Master、Model、Msdb、Tempdb

    SQL Server 中4个系统数据库,Master.Model.Msdb.Tempdb master   数据库       master   数据库记录   SQL   Server   系统的所 ...

  3. sql数据透视_SQL Server中的数据科学:取消数据透视

    sql数据透视 In this article, in the series, we'll discuss understanding and preparing data by using SQL ...

  4. Tableau学习Step2一数据文件的读取与统计图、表的概述

    Tableau学习Step2一数据文件的读取与统计图.表的概述 本文首发于博客冰山一树Sankey,去博客浏览效果更好. 一. 前言 本教程通过一个案例从浅到深来学习Tableau知识 案例概述: 二 ...

  5. SQL Server 中4个系统数据库详细介绍

    SQL Server 中4个系统数据库,Master.Model.Msdb.Tempdb. (1)Master数据库是SQL Server系统最重要的数据库,它记录了SQL Server系统的所有系统 ...

  6. 控制文件和数据文件丢失,有全备份恢复数据库的方法

    控制文件和数据文件丢失,有全备份恢复数据库的方法 控制文件丢失,即使有全备份也难恢复数据库,因为备份信息是存在于控制文件的. 刚看论坛精华帖,Feng讲的dbms_backup_restore包还是很 ...

  7. 导出数据在SQL Server中作为INSERT INTO

    我正在使用SQL Server 2008 Management Studio并且有一个我想要迁移到其他数据库服务器的表. 有没有选项将数据导出为插入SQL脚本? #1楼 您还可以从以下位置查看SQL ...

  8. sql azure 语法_Azure SQL Server中的CREATE DATABASE语句概述

    sql azure 语法 In this article, we will review CREATE DATABASE statement in the Azure SQL database wit ...

  9. Sql Server中判断表或者数据库是否存在

    SQL Server中判断数据库是否存在: 法(一): select * From master.dbo.sysdatabases where name='数据库名' 法(二): if db_id(' ...

最新文章

  1. 普适方案|资管新规落地,资管领域存量市场竞争激烈。专家:得转型(附产品推广)
  2. uniGUI试用笔记(二)
  3. 手动实现一个速度仪表盘
  4. php引擎,php基于什么引擎
  5. PHP notice/warning 对性能的影响
  6. C++标准转换运算符:dynamic_cast
  7. 如何mysql学籍管理系统_MySQL基础-学生管理系统数据库设计
  8. 编译原理实验二【语法分析程序设计】
  9. 上传pdf图片 文件
  10. 微信小程序自定义modal模态框
  11. python分块处理功能_Python自然语言处理学习笔记之信息提取步骤分块(chunking)...
  12. Linux烤机脚本测试io,sipp测试脚本用于媒体测试
  13. 智能视频抠图_黑科技 !人工智能抠图神器来了,抠图原来如此简单【918期】...
  14. 用C/汇编代码实现imx6ull点灯
  15. Acwing2041. 干草堆
  16. 基于JavaSwing开发学生信息管理系统(SQLServer数据库版本) 毕业设计 课程设计 大作业
  17. 前端HTML上传图片传BASE64数据,图片太大进行压缩
  18. ESP32A1S开发之智能家居 语音唤醒 语音命令控制(持续更新)
  19. 使用ffmpeg调用摄像头录制视频(C#)
  20. JS面试题汇总(Es6)

热门文章

  1. sql server列转行怎么提高效率_行转列、列转行
  2. python写一个数据库的界面_Python GUI教程(十四):在PyQt5中使用数据库
  3. jQuery-点击按钮页面滚动到顶部,底部,指定位置
  4. vue2.0中transition组件的用法
  5. 移动磁盘显示由于IO设备错误,无法运行此项请求要怎样寻回资料
  6. 初解vue脚手架vue-cli,及demo示例(一)
  7. 卸载驱动出现:rmmod: can't change directory to '/lib/modules': No such file or directory
  8. PADS无模命令总结
  9. 在Module中使用自定义过滤器,来统一对站内所有请求响应的输出内容进行采集或更改。...
  10. 在实际项目中应用NHibernate