Solved

script to check tables and indexes fragmentation

Posted on 2013-12-05
5
311 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
ID: 39699559
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
ID: 39699562
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
ID: 39699592
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
ID: 39701314
But how can I check data fragmentation?
0
 
LVL 26

Expert Comment

by:Zberteoc
ID: 39701397
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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Sql Query join multiple table and distinct records 7 32
Bubble user-defined Sql RAISERROR(...) to c# exception 14 202
Grid querry results 41 82
SQL- GROUP BY 4 23
by Mark Wills Attending one of Rob Farley's seminars the other day, I heard the phrase "The Accidental DBA" and fell in love with it. It got me thinking about the plight of the newcomer to SQL Server...  So if you are the accidental DBA, or, simp…
In SQL Server, when rows are selected from a table, does it retrieve data in the order in which it is inserted?  Many believe this is the case. Let us try to examine for ourselves with an example. To get started, use the following script, wh…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

749 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