As a DBA for several servers, I get a lot of calls about disk space. The first thing I do is look for data files I can shrink to free up some space on the disk. Some of the servers I support contain several databases and it can take a while to figure out which data file will give me the most immediate relief.
The first thing you need is the drive information. You can get this from the extended stored procedure xp_fixeddrives, which returns the drive letter and how much space is free on the drive. The next thing you need to know is how much space is available in each data file. When you pull up the information in SSMS, Microsoft uses two different DBCC calls; one for the data files and one for the log files. Instead of using separate DBCC calls, you can call the fileproperty function and pass the name of the data file and the SpaceUsed parameters. This has to be run from the context of the database in which the data files are located, so you can use the sp_msforeachdb stored procedure to return the results for all databases.
Now that you have the drive information and the space used, you can join it to the sys.databases and sys.master_files tables to return one view of all the data. It is now possible to quickly determine the files that have the most free space and where they are located.
After copying and pasting the above into a SQL Server 2005 query window and running all of the code the result set will look something like this:
- With a little modification, you can schedule the script to shrink data files containing over X amount of free space on a drive with less than X amount of disk space.
- In a perfect world, DBA's would just be able to ask for more drive space and not have to worry about shrinking files. It is more efficient to give the database the room it needs instead of having to shrink them all the time. Until then, I guess I will keep using this script.
Last Update: 2008-06-02
About the author
View all my tips