Home » Script to get database sizes in SQL Server

Script to get database sizes in SQL Server

by Vlad Drumea
0 comment

This post contains a script I’ve put together to get database sizes in SQL Server along with some additional info like file counts per file types and their sizes in GB.

For the whole instance

The following query retrieves the following information, one record per database:

  • Database – the name of the database
  • DatabaseState – the state of the database (duh)
  • DataFiles – number of data files (.mdf and .ndf)
  • DataFilesSizeGB – the total size of the data file(s) in GB
  • LogFIles – number of transaction log files (.ldf) – note: 99% of the time there is no valid reason to have more than one transaction log file per database.
  • LogFileSizeGB – the total size of the transaction log file(s) in GB
  • FILESTREAMContainers – the number of FILESTREAM containers – at the disk level these are actually directories
  • FSContainersSizeGB – the total size of the FILESTREAM container(s) in GB
  • DatabaseSizeGB – the total size of the database in GB

You might ask yourself “isn’t the internet full of scripts that do the same thing?”, and the answer is “yes, but there’s a catch”.
In this case the catch being that, although there are some great examples out there, the ones I’ve found rely solely on sys.master_files so they end up omitting FILESTREAM container sizes altogether.

Since FILESTREAM size information is not returned by the system-wide view sys.master_files, but by the database-level view sys.database_files, I had to use a temp table and populate it via a cursor with the FILESTREAM info for each database with such containers.

Output example

Result set example for the above query SEO script database sizes SQL Server


Note that I’m not excluding system databases from the output but, if needed, that can be done by adding WHERE d.[database_id] > 4 to the query.

For a specific database

If needed, you can run this script in the context of a specific database to get the files and size info for that database alone.

Conclusion

The post is pretty much self-explanatory, I needed a script to return database size info in a certain way and without omitting FILESTREAM containers.

You may also like

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.