天天看點

SQL Server使用sys.master_files計算tempdb大小不正确

一直習慣使用sys.master_files來統計資料庫的大小以及使用情況,但是發現sys.master_files不能準确統計tempdb的資料庫大小資訊。如下所示:

SQL Server使用sys.master_files計算tempdb大小不正确

在Windows視窗裡,你會看到這些檔案實際大小為18G多,而不是1G大小,而使用sys.master_files統計的Size(GB)僅僅是tempdb檔案的初始化大小,當然,你在SSMS裡面使用UI去檢視tempdb的屬性發現其大小值又是正确的,

SQL Server使用sys.master_files計算tempdb大小不正确
SQL Server使用sys.master_files計算tempdb大小不正确

如果你用Profile跟蹤看看具體SQL如下,你會發現,它統計的資料來源于視圖sys.database_files

sys.database_files的具體定義如下

sys.master_files的具體定義如下:

從上面SQL腳本可以看到,統計資料庫的大小分别來自于sys.sysprufiles 和master.sys.sysbrickfiles這兩個表,然後我們就很難再深入了解具體的原因了。在https://connect.microsoft.com/SQLServer/feedback/details/377223/sys-master-files-does-not-show-accurate-size-information 這個連結裡面,對tempdb相關的問題有一些描述:

1. The view sys.master_files is something new and is updated asynchronously. It doesn't updates immediately.

2. When you re-start your SQL Server, SQL Server will re-create tempdb based on sys.master_files.

3. The sys.master_files tell you about any tempdb data file which was there on your system (the number of tempdb files) with which your server have started.

4. While sys.database_files shows currently used tempdb files. Its quite possible that not all tempdb data files came online.

5. You can read the errorlog look for any error meesage did any of the files did not come online.

6. After you started sql server somebody might have executed SQL commands to remove or add tempdb files.

大體意思,sys.master_files中的資料是異步更新的,而不是同步更新的。它不會立即更新。當你重新開機你的SQL Server時,SQL Server啟動時候都會根據sys.master_files中值重新建立、初始化tempdb檔案大小。而sys.database_files顯示目前使用的tempdb檔案。 很可能并非所有的tempdb資料檔案都線上。 是以,如果要查詢tempdb的準确大小,就要使用sys.database_files來查詢!