Shrinking databases

When moving databases around, often people will truncate the logs and/or run DBCC SHRINKDATABASE but those only reduce the actual used space. They don’t actually shrink the database files themselves. DBCC SHRINKFILE is a bit picky in that in you pass it the logical file names. If you have the normal setup where you create a database with MDF, LDF and NDF, then it can get cumbersome to look up those names. What I use is the following piece of SQL which will shrink all the files for the current database. Note that SHRINKFILE only works on the current database.

USE [YourDatabaseGoesHere]
go
IF DATABASEPROPERTYEX(N'{0}', N'Status') IS NOT NULL BEGIN DECLARE @fileName SYSNAME 
    DECLARE @command NVARCHAR(1024) 
    DECLARE curFiles CURSOR 
        FOR SELECT [name] FROM sys.database_files 
    OPEN curFiles 
    FETCH NEXT FROM curFiles INTO @fileName
    WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @command = 'DBCC SHRINKFILE(' + @fileName + ', 0, TRUNCATEONLY);'
        PRINT @command
        EXEC(@command)
        FETCH NEXT FROM curFiles INTO @fileName
    END
END;

Happy Coding!

Advertisement

About JohnHowell

I am a professional software developer with over 20 years of experience. I currently specialize in Microsoft technologies such as VS, TFS, C#, VB.Net, WCF, WPF, WW, etc.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s