Thursday, February 26, 2009

T-SQL - DBCC SHRINKDATABASE

The following command uses to shrink data and log files in a database and releasing unallocated spaces:

DBCC SHRINKDATABASE
( database_name | database_id | 0
   [ , target_percent ]
   [ , { NOTRUNCATE | TRUNCATEONLY } ]
)
[ WITH NO_INFOMSGS ]

target_percent
   this parameter is the percentage of free (unallocated) space which you want left in the database file.

NOTRUNCATE
   Just relocate allocated spaces from end of the file to unallocated spaces in front of the file without shrinking and resizing the file.

TRUNCATEONLY
   it causes to release all free space at the end of the file.

WITH NO_INFOMSGS
   This option suppresses all informational messages.

Notes:
  • Database can not be smaller than initial size which you mentioned when you created the database.
  • DBCC SHRINKDATABASE without either the NOTRUNCATE option or the TRUNCATEONLY, runs first with NOTRUNCATE followed by running with TRUNCATEONLY.
  • During backup you can not shrink a database and during shrinking you can not back up a database.
  • Most effective time for shrinking a database is after an operation that creates lots of unused space like TRUNCATE or DROP TABLE

Disadvantage of shrinking a database is about increasing fragmentation.

Examples:
-- It shrinks and keeps 15 percent free space in the database
DBCC SHRINKDATABASE (myDataBase, 15);
GO

-- The following command, shrinks the database to the last allocated extent.
DBCC SHRINKDATABASE (myDataBase, TRUNCATEONLY)
GO

To shrink a database using SSMS, you can right click on database name and choose TASKS from context menu then select SHRINK and point on Database.
            Right click
Database -----------> TASKS -> SHRINK -> Database
Share/Bookmark

No comments: