?
Solved

script to check tables and indexes fragmentation

Posted on 2013-12-05
5
Medium Priority
?
321 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
5 Comments
 
LVL 27

Accepted Solution

by:
Zberteoc earned 2000 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 27

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 27

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: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

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

This article will describe one method to parse a delimited string into a table of data.   Why would I do that you ask?  Let's say that you need to pass multiple parameters into a stored procedure to search for.  For our sake, we'll say that we wa…
When writing XML code a very difficult part is when we like to remove all the elements or attributes from the XML that have no data. I would like to share a set of recursive MSSQL stored procedures that I have made to remove those elements from …
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…

762 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