Acrobatics field--Shrinking database data file

Source: Internet
Author: User

--=====================================================================

Some friends encountered some difficulties in shrinking the database files, found that there is a large amount of space left or deleted a large amount of data, or can not shrink the database, this is why?

--====================================================================

To shrink a database file, first we need to determine how much space can be shrunk, since shrinking the file is shrinking according to extent, so we need to find out how many unallocated partitions there are.

--========================================================--view space and shrink space for each file under the current database--FILESIZE_MB: Space occupied by the current file--SHRINK_SPACE_MB: Maximum space that can be shrunk (space occupied by unused extents)SELECT db_name() asdatabasename,f.name,f.physical_name,f.size*8.0/1024x768  asFilesize_mb,u.total_page_count,u.allocated_extent_page_count,u.allocated_extent_page_count/8  asAllocated_extent_count,u.unallocated_extent_page_count,u.unallocated_extent_page_count/8  asUnallocated_extent_count,u.unallocated_extent_page_count*8/1024x768  asSHRINK_SPACE_MB fromsys.database_files FINNER JOINsys.dm_db_file_space_usage U onF.file_id=U.file_id

or use

-- ========================================== -- -Displays fragmentation information for the data and indexes of the specified table or view.  --use (totalextents-usedextents) *8/1024 to get a space that can be shrunk (in megabytes)
DBCC Showfilestats

--===========================================================

In some cases, a lot of data is deleted, but the amount of space that can be shrunk is still very small. Let's take a step-by-step analysis of the lookup.

First we look at the usage of extent on the database

--===========================================--view the usage of each partition of the database TetDB1CREATE TABLE#TmpExtentInfo ([file_id] INT,    [page_id] BIGINT,    [Pg_alloc] INT,    [ext_size] INT,    [object_id] BIGINT,    [index_id] INT,    [Partition_number] INT,    [partition_id] BIGINT,    [Iam_chain_type] VARCHAR( $),    [pfs_bytes] VARCHAR( $))GOINSERT  into#TmpExtentInfoEXEC('DBCC Extentinfo ("'TestDB1"')')


With all extent usage, we can look for unused space on the allocated data area

--==========================================================--find data pages that are not used on an assigned extentSELECT object_name(object_id) astablename,index_id,SUM(ext_size-PG_ALLOC)*8.0/1024x768  asUNUSEDSPACEINALLOCATEDEXTENT_MB from#TmpExtentInfoGROUP  by object_id, index_idORDER  byUnusedspaceinallocatedextent_mbDESC

For user objects with a large amount of unused space above, you can rebuild the index to release the partition.

--============================================================================================

If not found, we need a deeper step to the data page usage

--===================================--create temporary tables to hold index fragmentation informationCREATE TABLE#TmpPageFrag (ObjectNameChar(255), ObjectIdint, IndexNameChar(255), IndexIDint, LVLint, Countpagesint, CountRowsint, Minrecsizeint, Maxrecsizeint, Avgrecsizeint, Forreccountint, Extentsint, Extentswitchesint, Avgfreebytesint, Avgpagedensityint, Scandensitydecimal, Bestcountint, Actualcountint, Logicalfragdecimal, Extentfragdecimal);--===================================--using DBCC SHOWCONTIG to get index fragmentation informationINSERT  into#TmpPageFragEXEC('DBCC showcontig with Tableresults, all_indexes;')--==================================--finding a large index of fragmentationSELECT *  from#TmpPageFragORDER by countpages* (100-avgpagedensity)/100 DESC 

Of course we can also use the following script to find

SELECT object_name(object_id) asTableName,* fromSys.dm_db_index_physical_stats (db_id(),NULL,NULL,NULL,'SAMPLED')ORDER  byPage_count*( --Avg_fragmentation_in_percent)DESC


Find more fragmented indexes and can release more data pages with index maintenance

--===========================================================================================

Because shrinking the database file moves the allocated page from the end of the data file to the Unassigned page in front of the file, we need to first locate which "allocated page" is at the end of the data file, because the data page has an offset in the file = Page id*8192, so the larger the page ID of the data page, the more the end of the file, So we need to find the object with the largest page ID

--===========================================--view the usage of each partition of the database TetDB1CREATE TABLE#TmpExtentInfo ([file_id] INT,    [page_id] BIGINT,    [Pg_alloc] INT,    [ext_size] INT,    [object_id] BIGINT,    [index_id] INT,    [Partition_number] INT,    [partition_id] BIGINT,    [Iam_chain_type] VARCHAR( $),    [pfs_bytes] VARCHAR( $))GOINSERT  into#TmpExtentInfoEXEC('DBCC Extentinfo ("'TestDB1"')')--==========================================================--find objects at the end of a data fileSELECT object_name(object_id) asTableName,* from#TmpExtentInfoORDER  bypage_idDESC

These indexes are then rebuilt so that the data page can be moved to the front of the file, avoiding excessive data page movement when shrinking the file.

--=============================================================================

Next is the contraction, this is nothing to say, if you want to shrink the space is relatively large, can be divided into small space low shrinkage.

--============================================================================

In shrinking the database process, we should always pay attention to the blocking situation oh, meet a long-running business, pro, don't be calm Oh!

--===========================================================================

After finishing the call, is still the sister town stickers.

PS: I will try to put a little fresh pictures to prevent some brothers to work time to see her sister was caught, the impact is not good!!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.