Solved

script to check tables and indexes fragmentation

Posted on 2013-12-05
5
302 Views
Last Modified: 2013-12-07
Hello,

I search a script to check tables and indexes fragmentation on MS SQL SERVER 2005.

Thanks a lot
0
Comment
Question by:bibi92
  • 3
5 Comments
 
LVL 26

Accepted Solution

by:
Zberteoc earned 500 total points
Comment Utility
You can use the one bellow:
if object_id('tempdb..#idx_frg') is not null
	drop table #idx_frg
SELECT 
	DB_NAME(DB_ID()) AS DatabaseName,
    schemas.[name] AS SchemaName,
    objects.[name] AS ObjectName,
    indexes.[name] AS IndexName,
    objects.type_desc AS ObjectType,
    indexes.type_desc AS IndexType,
    dm_db_index_physical_stats.partition_number AS PartitionNumber,
    dm_db_index_physical_stats.page_count AS [PageCount],
    right('____'+cast(round(cast(dm_db_index_physical_stats.avg_fragmentation_in_percent as decimal(8,2)),2) as varchar),6) AS AvgFagmentationInPercent
into #idx_frg
FROM 
	sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, 'LIMITED') dm_db_index_physical_stats
	INNER JOIN sys.indexes indexes 
		ON dm_db_index_physical_stats.[object_id] = indexes.[object_id] 
		AND dm_db_index_physical_stats.index_id = indexes.index_id
	INNER JOIN sys.objects objects 
		ON indexes.[object_id] = objects.[object_id]
	INNER JOIN sys.schemas schemas 
		ON objects.[schema_id] = schemas.[schema_id]
WHERE 
	objects.[type] IN('U','V')
	AND objects.is_ms_shipped = 0
	AND indexes.[type] IN(1,2,3,4)
	AND indexes.is_disabled = 0
	AND indexes.is_hypothetical = 0
	AND dm_db_index_physical_stats.alloc_unit_type_desc = 'IN_ROW_DATA'
	AND dm_db_index_physical_stats.index_level = 0
	AND dm_db_index_physical_stats.page_count >= 1000
	--and indexes.[name]='location'
	--and objects.[name]='Photo'
order by 
	DatabaseName,
	SchemaName,
	ObjectName,
	IndexName
select 
	*, 
	case 
		when replace(AvgFagmentationInPercent,'_','') between 10.00 and 29.99 then 'Reindex' 
		else 'Rebuild' end as 'Action' 
from 
	#idx_frg where replace(AvgFagmentationInPercent,'_','')>10.00 
order by 
	AvgFagmentationInPercent desc

Open in new window

0
 
LVL 10

Expert Comment

by:PadawanDBA
Comment Utility
This should give you what you're looking for:

select
	*
from
	sys.dm_db_index_physical_stats( db_id( N'<databaseNameHere>' ), null, null, null, null );

Open in new window


You can play around with the mode option to fit your needs (it will take longer to run depending on how accurate you would like your detail).  Description of this DMF:  http://technet.microsoft.com/en-us/library/ms188917.aspx

Edit: I had just realized that index names would probably be useful...  i'm not going to bother with changing it, since Zberteoc's is more than sufficient for what you wanted =)
0
 
LVL 26

Expert Comment

by:Zberteoc
Comment Utility
I actually need to complete my post. The query will create a tempt table and then will select from it. Only indexes > 1000 pages will be checked, teh smaller ones are irrelevant.

As per Microsoft recommandation there are actions for different thresholds:

1. Frag < 10% - ignore
2. Frag <=10  and < 30 - reorganize
3. Frag >=30 - rebuild.

If you want to nicely automate these operations I recommend you Ola Hallegren's solution, from where my script was derived:

http://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html

For a complete solution including backup, index optimization, integrity check use the whole solution that will create all the objects for you including the jobs:

www.http://ola.hallengren.com/

Another nice way to see this is the free app from Idera:

http://www.idera.com/productssolutions/freetools/sqlfragmentationanalyzer


If you want a collection of useful scripts, including Ola's fragmentation you can get using Red Gate's Script Manager, also free:

http://www.red-gate.com/products/dba/sql-scripts-manager/
0
 

Author Comment

by:bibi92
Comment Utility
But how can I check data fragmentation?
0
 
LVL 26

Expert Comment

by:Zberteoc
Comment Utility
Data fragmentation of a table is given by its clustered index fragmentation. If you don't have a clustered index on some of your tables (called heaps in this case) you should create them.
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
SQL Server Set bit value based on sums 4 39
SQL Server DeDupe Table 3 29
How to enforce inte 8 31
Truncate vs Delete 63 87
Introduction This article will provide a solution for an error that might occur installing a new SQL 2005 64-bit cluster. This article will assume that you are fully prepared to complete the installation and describes the error as it occurred durin…
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now