简体   繁体   中英

Shrink the database in SQL Server

I have a database which is almost full and we have some options to deal with this:

  1. we can increase the db file size
  2. shrink the database

Before I choose the first option, I want to know how can I check the database size and how much data is really in there so that I may can shrink the database to get some free space.

So see where you have unused space , what file is how big use the following query....

Use DatabaseName
GO

Select name                                             AS [FileName]
     , size/128.0                                       AS [FileSize(MB)]
     , fileproperty(name, 'SpaceUsed')/128.0            AS [Space_Used(MB)]
     , (size - fileproperty(name, 'SpaceUsed')) /128.0  AS [FreeSpace(MB)] 
From dbo.sysfiles
GO

Finally when you have decided to shrink a file with lots of free space you can use DBCC shrinkfile command to do so.

USE DatabaseName
GO
DBCC SHRINKFILE ('FileName', 10)   --<-- will shrink it to 10 MB
GO

Note

If any of the unused space was occupied by the BLOB data type(text, ntext, xml etc) column, you may not be able to claim back that unused space unless you drop and recreate the table again.

You can get this information a couple of different ways. In SSMS you can right click on the database, choose properties and look at files. You data and log files will display an "Initial" value indicating size.

You can right click the DB, click on Tasks and Shrink, then Files and the data file should be the default displayed. This will show you your size and free space.

You can also run a script showing you all the size and location info for your databases. There are several out there you can find with a quick Google Search.

Additionally, there are some built in SPs that can get you that info as described here The fourth query in particular shows you the amount of free space.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM