<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
		>
<channel>
	<title>Comments on: SQL SERVER &#8211; 2005 &#8211; A Simple Way To Defragment All Indexes In A Database That Is Fragmented Above A Declared Threshold</title>
	<atom:link href="http://blog.sqlauthority.com/2008/03/04/sql-server-2005-a-simple-way-to-defragment-all-indexes-in-a-database-that-is-fragmented-above-a-declared-threshold/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.sqlauthority.com/2008/03/04/sql-server-2005-a-simple-way-to-defragment-all-indexes-in-a-database-that-is-fragmented-above-a-declared-threshold/</link>
	<description>Personal Notes of Pinal Dave</description>
	<lastBuildDate>Thu, 09 Feb 2012 19:36:10 +0000</lastBuildDate>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
	<item>
		<title>By: Paul Burkhardt</title>
		<link>http://blog.sqlauthority.com/2008/03/04/sql-server-2005-a-simple-way-to-defragment-all-indexes-in-a-database-that-is-fragmented-above-a-declared-threshold/#comment-222994</link>
		<dc:creator><![CDATA[Paul Burkhardt]]></dc:creator>
		<pubDate>Wed, 21 Dec 2011 16:34:29 +0000</pubDate>
		<guid isPermaLink="false">http://sqlauthority.wordpress.com/?p=526#comment-222994</guid>
		<description><![CDATA[Hi Paul,

   I found your script to be very thorough and complete.  However, when I run it, I receive the following error:

Msg 5236, Level 15, State 1, Line 1
Unable to process object &#039;dbo&#039; because it is a four-part name, which is not supported by any DBCC command.  

   Do you know how to fix this problem?  Please let me know.

Thanks,

Paul]]></description>
		<content:encoded><![CDATA[<p>Hi Paul,</p>
<p>   I found your script to be very thorough and complete.  However, when I run it, I receive the following error:</p>
<p>Msg 5236, Level 15, State 1, Line 1<br />
Unable to process object &#8216;dbo&#8217; because it is a four-part name, which is not supported by any DBCC command.  </p>
<p>   Do you know how to fix this problem?  Please let me know.</p>
<p>Thanks,</p>
<p>Paul</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Don</title>
		<link>http://blog.sqlauthority.com/2008/03/04/sql-server-2005-a-simple-way-to-defragment-all-indexes-in-a-database-that-is-fragmented-above-a-declared-threshold/#comment-105973</link>
		<dc:creator><![CDATA[Don]]></dc:creator>
		<pubDate>Wed, 15 Dec 2010 15:49:24 +0000</pubDate>
		<guid isPermaLink="false">http://sqlauthority.wordpress.com/?p=526#comment-105973</guid>
		<description><![CDATA[Is there a way to automate the above defrag task? Setting it up as a job fails but runing it in a query window it performs as expected.]]></description>
		<content:encoded><![CDATA[<p>Is there a way to automate the above defrag task? Setting it up as a job fails but runing it in a query window it performs as expected.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Derek Fordham</title>
		<link>http://blog.sqlauthority.com/2008/03/04/sql-server-2005-a-simple-way-to-defragment-all-indexes-in-a-database-that-is-fragmented-above-a-declared-threshold/#comment-87921</link>
		<dc:creator><![CDATA[Derek Fordham]]></dc:creator>
		<pubDate>Wed, 15 Sep 2010 12:04:33 +0000</pubDate>
		<guid isPermaLink="false">http://sqlauthority.wordpress.com/?p=526#comment-87921</guid>
		<description><![CDATA[Hello. Thanks for the fine information provided above. I ran one of the jobs which highlighted fragmentation and stated an intent to resolve it. However, on re-running the job, it showed the same level of fragmentation.... suspecting I had run the job inappropriately, I went to one of the offending indexes using the &quot;object explorer&quot; and have done a &quot;rebuild&quot; a &quot;reorganize&quot; and through &quot;properties&quot;-&gt;&quot;fragmentation&quot; have done a &quot;reorganize index&quot;.
All of these appear to run ok but leave the index with 80% fragmentation.....
I welcome any suggestions as to why this might be?

I am running ;
Microsoft SQL Server Management Studio Express						9.00.3033.00
Microsoft Data Access Components (MDAC)						2000.086.3959.00 (srv03_sp2_rtm.070216-1710)
Microsoft MSXML						2.6 3.0 4.0 6.0 
Microsoft Internet Explorer						6.0.3790.3959
Microsoft .NET Framework						2.0.50727.1433
Operating System						5.2.3790

Thanks in advance.
Regards, Derek]]></description>
		<content:encoded><![CDATA[<p>Hello. Thanks for the fine information provided above. I ran one of the jobs which highlighted fragmentation and stated an intent to resolve it. However, on re-running the job, it showed the same level of fragmentation&#8230;. suspecting I had run the job inappropriately, I went to one of the offending indexes using the &#8220;object explorer&#8221; and have done a &#8220;rebuild&#8221; a &#8220;reorganize&#8221; and through &#8220;properties&#8221;-&gt;&#8221;fragmentation&#8221; have done a &#8220;reorganize index&#8221;.<br />
All of these appear to run ok but leave the index with 80% fragmentation&#8230;..<br />
I welcome any suggestions as to why this might be?</p>
<p>I am running ;<br />
Microsoft SQL Server Management Studio Express						9.00.3033.00<br />
Microsoft Data Access Components (MDAC)						2000.086.3959.00 (srv03_sp2_rtm.070216-1710)<br />
Microsoft MSXML						2.6 3.0 4.0 6.0<br />
Microsoft Internet Explorer						6.0.3790.3959<br />
Microsoft .NET Framework						2.0.50727.1433<br />
Operating System						5.2.3790</p>
<p>Thanks in advance.<br />
Regards, Derek</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: satya</title>
		<link>http://blog.sqlauthority.com/2008/03/04/sql-server-2005-a-simple-way-to-defragment-all-indexes-in-a-database-that-is-fragmented-above-a-declared-threshold/#comment-61206</link>
		<dc:creator><![CDATA[satya]]></dc:creator>
		<pubDate>Mon, 15 Feb 2010 21:36:14 +0000</pubDate>
		<guid isPermaLink="false">http://sqlauthority.wordpress.com/?p=526#comment-61206</guid>
		<description><![CDATA[Hi Pinal,
I really appreciate you for your response

I am trying to execute the same code on database where i have many indexes fragmented upto 99%

this code only defragments few indexes

what about the other indexes whose fragmention is still 80% after running this code 
please help


SET NOCOUNT ON;
DECLARE @tablename VARCHAR(128);
DECLARE @execstr VARCHAR(255);
DECLARE @objectid INT;
DECLARE @indexid INT;
DECLARE @frag decimal;
DECLARE @maxfrag decimal;
-- Decide on the maximum fragmentation to allow for.
SELECT @maxfrag = 30.0;
-- Declare a cursor.
DECLARE tables CURSOR FOR
SELECT CAST(TABLE_SCHEMA AS VARCHAR(100))
+&#039;.&#039;+CAST(TABLE_NAME AS VARCHAR(100))
AS Table_Name
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = &#039;BASE TABLE&#039;;
-- Create the table.
CREATE TABLE #fraglist (
ObjectName CHAR(255),
ObjectId INT,
IndexName CHAR(255),
IndexId INT,
Lvl INT,
CountPages INT,
CountRows INT,
MinRecSize INT,
MaxRecSize INT,
AvgRecSize INT,
ForRecCount INT,
Extents INT,
ExtentSwitches INT,
AvgFreeBytes INT,
AvgPageDensity INT,
ScanDensity decimal,
BestCount INT,
ActualCount INT,
LogicalFrag decimal,
ExtentFrag decimal);
-- Open the cursor.
OPEN tables;
-- Loop through all the tables in the database.
FETCH NEXT
FROM tables
INTO @tablename;
WHILE @@FETCH_STATUS = 0
BEGIN;
-- Do the showcontig of all indexes of the table
INSERT INTO #fraglist
EXEC (&#039;DBCC SHOWCONTIG (&#039;&#039;&#039; + @tablename + &#039;&#039;&#039;)
WITH FAST, TABLERESULTS, ALL_INDEXES, NO_INFOMSGS&#039;);
FETCH NEXT
FROM tables
INTO @tablename;
END;
-- Close and deallocate the cursor.
CLOSE tables;
DEALLOCATE tables;
-- Declare the cursor for the list of indexes to be defragged.
DECLARE indexes CURSOR FOR
SELECT ObjectName, ObjectId, IndexId, LogicalFrag
FROM #fraglist
WHERE LogicalFrag &gt;= @maxfrag
AND INDEXPROPERTY (ObjectId, IndexName, &#039;IndexDepth&#039;) &gt; 0;
-- Open the cursor.
OPEN indexes;
-- Loop through the indexes.
FETCH NEXT
FROM indexes
INTO @tablename, @objectid, @indexid, @frag;
WHILE @@FETCH_STATUS = 0
BEGIN;
PRINT &#039;Executing DBCC INDEXDEFRAG (0, &#039; + RTRIM(@tablename) + &#039;,
&#039; + RTRIM(@indexid) + &#039;) - fragmentation currently &#039;
+ RTRIM(CONVERT(VARCHAR(15),@frag)) + &#039;%&#039;;
SELECT @execstr = &#039;DBCC INDEXDEFRAG (0, &#039; + RTRIM(@objectid) + &#039;,
&#039; + RTRIM(@indexid) + &#039;)&#039;;
EXEC (@execstr);
FETCH NEXT
FROM indexes
INTO @tablename, @objectid, @indexid, @frag;
END;
-- Close and deallocate the cursor.
CLOSE indexes;
DEALLOCATE indexes;
-- Delete the temporary table.
DROP TABLE #fraglist;
GO]]></description>
		<content:encoded><![CDATA[<p>Hi Pinal,<br />
I really appreciate you for your response</p>
<p>I am trying to execute the same code on database where i have many indexes fragmented upto 99%</p>
<p>this code only defragments few indexes</p>
<p>what about the other indexes whose fragmention is still 80% after running this code<br />
please help</p>
<p>SET NOCOUNT ON;<br />
DECLARE @tablename VARCHAR(128);<br />
DECLARE @execstr VARCHAR(255);<br />
DECLARE @objectid INT;<br />
DECLARE @indexid INT;<br />
DECLARE @frag decimal;<br />
DECLARE @maxfrag decimal;<br />
&#8211; Decide on the maximum fragmentation to allow for.<br />
SELECT @maxfrag = 30.0;<br />
&#8211; Declare a cursor.<br />
DECLARE tables CURSOR FOR<br />
SELECT CAST(TABLE_SCHEMA AS VARCHAR(100))<br />
+&#8217;.'+CAST(TABLE_NAME AS VARCHAR(100))<br />
AS Table_Name<br />
FROM INFORMATION_SCHEMA.TABLES<br />
WHERE TABLE_TYPE = &#8216;BASE TABLE&#8217;;<br />
&#8211; Create the table.<br />
CREATE TABLE #fraglist (<br />
ObjectName CHAR(255),<br />
ObjectId INT,<br />
IndexName CHAR(255),<br />
IndexId INT,<br />
Lvl INT,<br />
CountPages INT,<br />
CountRows INT,<br />
MinRecSize INT,<br />
MaxRecSize INT,<br />
AvgRecSize INT,<br />
ForRecCount INT,<br />
Extents INT,<br />
ExtentSwitches INT,<br />
AvgFreeBytes INT,<br />
AvgPageDensity INT,<br />
ScanDensity decimal,<br />
BestCount INT,<br />
ActualCount INT,<br />
LogicalFrag decimal,<br />
ExtentFrag decimal);<br />
&#8211; Open the cursor.<br />
OPEN tables;<br />
&#8211; Loop through all the tables in the database.<br />
FETCH NEXT<br />
FROM tables<br />
INTO @tablename;<br />
WHILE @@FETCH_STATUS = 0<br />
BEGIN;<br />
&#8211; Do the showcontig of all indexes of the table<br />
INSERT INTO #fraglist<br />
EXEC (&#8216;DBCC SHOWCONTIG (&#8221;&#8217; + @tablename + &#8221;&#8217;)<br />
WITH FAST, TABLERESULTS, ALL_INDEXES, NO_INFOMSGS&#8217;);<br />
FETCH NEXT<br />
FROM tables<br />
INTO @tablename;<br />
END;<br />
&#8211; Close and deallocate the cursor.<br />
CLOSE tables;<br />
DEALLOCATE tables;<br />
&#8211; Declare the cursor for the list of indexes to be defragged.<br />
DECLARE indexes CURSOR FOR<br />
SELECT ObjectName, ObjectId, IndexId, LogicalFrag<br />
FROM #fraglist<br />
WHERE LogicalFrag &gt;= @maxfrag<br />
AND INDEXPROPERTY (ObjectId, IndexName, &#8216;IndexDepth&#8217;) &gt; 0;<br />
&#8211; Open the cursor.<br />
OPEN indexes;<br />
&#8211; Loop through the indexes.<br />
FETCH NEXT<br />
FROM indexes<br />
INTO @tablename, @objectid, @indexid, @frag;<br />
WHILE @@FETCH_STATUS = 0<br />
BEGIN;<br />
PRINT &#8216;Executing DBCC INDEXDEFRAG (0, &#8216; + RTRIM(@tablename) + &#8216;,<br />
&#8216; + RTRIM(@indexid) + &#8216;) &#8211; fragmentation currently &#8216;<br />
+ RTRIM(CONVERT(VARCHAR(15),@frag)) + &#8216;%&#8217;;<br />
SELECT @execstr = &#8216;DBCC INDEXDEFRAG (0, &#8216; + RTRIM(@objectid) + &#8216;,<br />
&#8216; + RTRIM(@indexid) + &#8216;)&#8217;;<br />
EXEC (@execstr);<br />
FETCH NEXT<br />
FROM indexes<br />
INTO @tablename, @objectid, @indexid, @frag;<br />
END;<br />
&#8211; Close and deallocate the cursor.<br />
CLOSE indexes;<br />
DEALLOCATE indexes;<br />
&#8211; Delete the temporary table.<br />
DROP TABLE #fraglist;<br />
GO</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Pinal Dave</title>
		<link>http://blog.sqlauthority.com/2008/03/04/sql-server-2005-a-simple-way-to-defragment-all-indexes-in-a-database-that-is-fragmented-above-a-declared-threshold/#comment-59428</link>
		<dc:creator><![CDATA[Pinal Dave]]></dc:creator>
		<pubDate>Thu, 07 Jan 2010 09:25:11 +0000</pubDate>
		<guid isPermaLink="false">http://sqlauthority.wordpress.com/?p=526#comment-59428</guid>
		<description><![CDATA[Hello Alex,

The script is only to defrag index that are fragmented more than 30%. Defragmentation may not reflect in much small tables. So in the output of sys.dm_db_index_physical_stats make sure that:
1. the object that have high fragmentation percentage is not a heap.
2. Fragmentation percentage is more than 30
3. the page_count is not a very small number.

Regards,
Pinal Dave]]></description>
		<content:encoded><![CDATA[<p>Hello Alex,</p>
<p>The script is only to defrag index that are fragmented more than 30%. Defragmentation may not reflect in much small tables. So in the output of sys.dm_db_index_physical_stats make sure that:<br />
1. the object that have high fragmentation percentage is not a heap.<br />
2. Fragmentation percentage is more than 30<br />
3. the page_count is not a very small number.</p>
<p>Regards,<br />
Pinal Dave</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Alex</title>
		<link>http://blog.sqlauthority.com/2008/03/04/sql-server-2005-a-simple-way-to-defragment-all-indexes-in-a-database-that-is-fragmented-above-a-declared-threshold/#comment-59413</link>
		<dc:creator><![CDATA[Alex]]></dc:creator>
		<pubDate>Wed, 06 Jan 2010 21:41:46 +0000</pubDate>
		<guid isPermaLink="false">http://sqlauthority.wordpress.com/?p=526#comment-59413</guid>
		<description><![CDATA[Did it help you in any way?

I have a similar problem with you...how did you solve it?

Salutari!]]></description>
		<content:encoded><![CDATA[<p>Did it help you in any way?</p>
<p>I have a similar problem with you&#8230;how did you solve it?</p>
<p>Salutari!</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Alex</title>
		<link>http://blog.sqlauthority.com/2008/03/04/sql-server-2005-a-simple-way-to-defragment-all-indexes-in-a-database-that-is-fragmented-above-a-declared-threshold/#comment-59412</link>
		<dc:creator><![CDATA[Alex]]></dc:creator>
		<pubDate>Wed, 06 Jan 2010 21:23:27 +0000</pubDate>
		<guid isPermaLink="false">http://sqlauthority.wordpress.com/?p=526#comment-59412</guid>
		<description><![CDATA[Hi Dave,

After running your script in SQL 2005 I still don&#039;t see any index defrag changes not with a 3-rd party monitoring tool or by running this:
USE master 
SELECT * 
FROM sys.dm_db_index_physical_stats (NULL, NULL, NULL, NULL, NULL)
order by avg_fragmentation_in_percent

Pls. advise what can I do other than rebuilding all indexes.

Your site is SUPER!

Thank you,
Alex]]></description>
		<content:encoded><![CDATA[<p>Hi Dave,</p>
<p>After running your script in SQL 2005 I still don&#8217;t see any index defrag changes not with a 3-rd party monitoring tool or by running this:<br />
USE master<br />
SELECT *<br />
FROM sys.dm_db_index_physical_stats (NULL, NULL, NULL, NULL, NULL)<br />
order by avg_fragmentation_in_percent</p>
<p>Pls. advise what can I do other than rebuilding all indexes.</p>
<p>Your site is SUPER!</p>
<p>Thank you,<br />
Alex</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Mandar Kavishwar</title>
		<link>http://blog.sqlauthority.com/2008/03/04/sql-server-2005-a-simple-way-to-defragment-all-indexes-in-a-database-that-is-fragmented-above-a-declared-threshold/#comment-59269</link>
		<dc:creator><![CDATA[Mandar Kavishwar]]></dc:creator>
		<pubDate>Sat, 02 Jan 2010 16:08:05 +0000</pubDate>
		<guid isPermaLink="false">http://sqlauthority.wordpress.com/?p=526#comment-59269</guid>
		<description><![CDATA[Hi Sir,
I need to convert VARCHAR  to UNIQUEIDENTIFIER
so how can i do this conversion??]]></description>
		<content:encoded><![CDATA[<p>Hi Sir,<br />
I need to convert VARCHAR  to UNIQUEIDENTIFIER<br />
so how can i do this conversion??</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Matt</title>
		<link>http://blog.sqlauthority.com/2008/03/04/sql-server-2005-a-simple-way-to-defragment-all-indexes-in-a-database-that-is-fragmented-above-a-declared-threshold/#comment-57829</link>
		<dc:creator><![CDATA[Matt]]></dc:creator>
		<pubDate>Mon, 23 Nov 2009 14:46:29 +0000</pubDate>
		<guid isPermaLink="false">http://sqlauthority.wordpress.com/?p=526#comment-57829</guid>
		<description><![CDATA[Can I just say thank you to the author and all involved in providing / releasing this script! absolute magic! :)]]></description>
		<content:encoded><![CDATA[<p>Can I just say thank you to the author and all involved in providing / releasing this script! absolute magic! :)</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Liviu Cornea</title>
		<link>http://blog.sqlauthority.com/2008/03/04/sql-server-2005-a-simple-way-to-defragment-all-indexes-in-a-database-that-is-fragmented-above-a-declared-threshold/#comment-46371</link>
		<dc:creator><![CDATA[Liviu Cornea]]></dc:creator>
		<pubDate>Thu, 05 Feb 2009 16:00:27 +0000</pubDate>
		<guid isPermaLink="false">http://sqlauthority.wordpress.com/?p=526#comment-46371</guid>
		<description><![CDATA[Thank you 

Imran Mohammed]]></description>
		<content:encoded><![CDATA[<p>Thank you </p>
<p>Imran Mohammed</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Imran Mohammed</title>
		<link>http://blog.sqlauthority.com/2008/03/04/sql-server-2005-a-simple-way-to-defragment-all-indexes-in-a-database-that-is-fragmented-above-a-declared-threshold/#comment-46221</link>
		<dc:creator><![CDATA[Imran Mohammed]]></dc:creator>
		<pubDate>Mon, 02 Feb 2009 04:36:04 +0000</pubDate>
		<guid isPermaLink="false">http://sqlauthority.wordpress.com/?p=526#comment-46221</guid>
		<description><![CDATA[Liviu Cornea

Visit this link,
Link: http://www.sqlservercentral.com/Forums/Topic438525-145-1.aspx
 
Highlights from above link:
 
1. Check how many rows are present in the table. ( If very few rows, then you can ignore defraging your index)
2. Check how many pages are under Index. ( If low then ignore defraging index)
3. Check fragmentation level of Hard Disk.
4. Which index you are trying to rebuild/re-organize , Clustered or Non-Clustered ? ( If Non-Clustered, then ignore defraging index)
5. Instead of using Alter Index ALL ...... use , Alter Index Index_name on table rebuild with fillfactor ...... ( Personally, I don&#039;t think this will make a difference)
 
Quoted directly from forum 
Microsoft has as whitepaper on this.
 
&quot;Generally, you should not be concerned with fragmentation levels of indexes with less than 1,000 pages. In the tests, indexes containing more than 10,000 pages realized performance gains, with the biggest gains on indexes with significantly more pages (greater than 50,000 pages).&quot; 
 
Link: http://www.microsoft.com/technet/prodtechnol/sql/2000/maintain/ss2kidbp.mspx
 

Regards,
IM.]]></description>
		<content:encoded><![CDATA[<p>Liviu Cornea</p>
<p>Visit this link,<br />
Link: <a href="http://www.sqlservercentral.com/Forums/Topic438525-145-1.aspx" rel="nofollow">http://www.sqlservercentral.com/Forums/Topic438525-145-1.aspx</a></p>
<p>Highlights from above link:</p>
<p>1. Check how many rows are present in the table. ( If very few rows, then you can ignore defraging your index)<br />
2. Check how many pages are under Index. ( If low then ignore defraging index)<br />
3. Check fragmentation level of Hard Disk.<br />
4. Which index you are trying to rebuild/re-organize , Clustered or Non-Clustered ? ( If Non-Clustered, then ignore defraging index)<br />
5. Instead of using Alter Index ALL &#8230;&#8230; use , Alter Index Index_name on table rebuild with fillfactor &#8230;&#8230; ( Personally, I don&#8217;t think this will make a difference)</p>
<p>Quoted directly from forum<br />
Microsoft has as whitepaper on this.</p>
<p>&#8220;Generally, you should not be concerned with fragmentation levels of indexes with less than 1,000 pages. In the tests, indexes containing more than 10,000 pages realized performance gains, with the biggest gains on indexes with significantly more pages (greater than 50,000 pages).&#8221; </p>
<p>Link: <a href="http://www.microsoft.com/technet/prodtechnol/sql/2000/maintain/ss2kidbp.mspx" rel="nofollow">http://www.microsoft.com/technet/prodtechnol/sql/2000/maintain/ss2kidbp.mspx</a></p>
<p>Regards,<br />
IM.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Liviu Cornea</title>
		<link>http://blog.sqlauthority.com/2008/03/04/sql-server-2005-a-simple-way-to-defragment-all-indexes-in-a-database-that-is-fragmented-above-a-declared-threshold/#comment-46176</link>
		<dc:creator><![CDATA[Liviu Cornea]]></dc:creator>
		<pubDate>Sat, 31 Jan 2009 03:27:50 +0000</pubDate>
		<guid isPermaLink="false">http://sqlauthority.wordpress.com/?p=526#comment-46176</guid>
		<description><![CDATA[Hi Pinal
I have a SQL 2005 database and I try to do a smart reindex. It works OK fro most of indexes . Database has around 500 indexes and aprox 150 needs to be REBUILT OR REORGANIZED.
The problem is: no matter how I do rebuilt them ...they are still fragmented. Even if I drop index manualy and recreate it after....it comes fragmented. The indexes with problem are clustered and non clustered indexex create on one single column for each table (I mean no composite key) and column type is uniqueidentifier.
What is really strange..if I rebuild index with fill factor 10....it gets defragmented from 50 to 20 percent. If I use fillfactor 90...it doesn&#039; get better at all.
I want to mention that system operation files are ok, I mean no need to defrag HDD.
Thank you in advance for your help
Liviu]]></description>
		<content:encoded><![CDATA[<p>Hi Pinal<br />
I have a SQL 2005 database and I try to do a smart reindex. It works OK fro most of indexes . Database has around 500 indexes and aprox 150 needs to be REBUILT OR REORGANIZED.<br />
The problem is: no matter how I do rebuilt them &#8230;they are still fragmented. Even if I drop index manualy and recreate it after&#8230;.it comes fragmented. The indexes with problem are clustered and non clustered indexex create on one single column for each table (I mean no composite key) and column type is uniqueidentifier.<br />
What is really strange..if I rebuild index with fill factor 10&#8230;.it gets defragmented from 50 to 20 percent. If I use fillfactor 90&#8230;it doesn&#8217; get better at all.<br />
I want to mention that system operation files are ok, I mean no need to defrag HDD.<br />
Thank you in advance for your help<br />
Liviu</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Paul DeBrino</title>
		<link>http://blog.sqlauthority.com/2008/03/04/sql-server-2005-a-simple-way-to-defragment-all-indexes-in-a-database-that-is-fragmented-above-a-declared-threshold/#comment-44209</link>
		<dc:creator><![CDATA[Paul DeBrino]]></dc:creator>
		<pubDate>Thu, 13 Nov 2008 18:57:49 +0000</pubDate>
		<guid isPermaLink="false">http://sqlauthority.wordpress.com/?p=526#comment-44209</guid>
		<description><![CDATA[Hello,

Perhaps the following post will lend clarity:

http://blog.sqlauthority.com/2007/06/24/sql-server-comparison-index-fragmentation-index-de-fragmentation-index-rebuild-sql-server-2000-and-sql-server-2005/ 

Kind Regards,
Paul]]></description>
		<content:encoded><![CDATA[<p>Hello,</p>
<p>Perhaps the following post will lend clarity:</p>
<p><a href="http://blog.sqlauthority.com/2007/06/24/sql-server-comparison-index-fragmentation-index-de-fragmentation-index-rebuild-sql-server-2000-and-sql-server-2005/" rel="nofollow">http://blog.sqlauthority.com/2007/06/24/sql-server-comparison-index-fragmentation-index-de-fragmentation-index-rebuild-sql-server-2000-and-sql-server-2005/</a> </p>
<p>Kind Regards,<br />
Paul</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: WCM</title>
		<link>http://blog.sqlauthority.com/2008/03/04/sql-server-2005-a-simple-way-to-defragment-all-indexes-in-a-database-that-is-fragmented-above-a-declared-threshold/#comment-44185</link>
		<dc:creator><![CDATA[WCM]]></dc:creator>
		<pubDate>Wed, 12 Nov 2008 17:54:35 +0000</pubDate>
		<guid isPermaLink="false">http://sqlauthority.wordpress.com/?p=526#comment-44185</guid>
		<description><![CDATA[Hello Pinal Dave,

Thank for the great topic.

A few requests -
1. Please reformat the scripts in this post to show indentation and colorization, as in your original script, and correct the single- and double-quotes to be accepted by SQL when pasting the scripts into SMS or QA.

2. Please explain why, after running the script with SET @ViewOnly=0  the indexes did not appear to defragment (running the script afterward with SET @ViewOnly=1 showed the same exact frag level).

Thanks!
WCM]]></description>
		<content:encoded><![CDATA[<p>Hello Pinal Dave,</p>
<p>Thank for the great topic.</p>
<p>A few requests -<br />
1. Please reformat the scripts in this post to show indentation and colorization, as in your original script, and correct the single- and double-quotes to be accepted by SQL when pasting the scripts into SMS or QA.</p>
<p>2. Please explain why, after running the script with SET @ViewOnly=0  the indexes did not appear to defragment (running the script afterward with SET @ViewOnly=1 showed the same exact frag level).</p>
<p>Thanks!<br />
WCM</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Paul DeBrino</title>
		<link>http://blog.sqlauthority.com/2008/03/04/sql-server-2005-a-simple-way-to-defragment-all-indexes-in-a-database-that-is-fragmented-above-a-declared-threshold/#comment-44107</link>
		<dc:creator><![CDATA[Paul DeBrino]]></dc:creator>
		<pubDate>Fri, 07 Nov 2008 20:36:26 +0000</pubDate>
		<guid isPermaLink="false">http://sqlauthority.wordpress.com/?p=526#comment-44107</guid>
		<description><![CDATA[This is a different version than the prior post - it provides the ability to reorg or rebuild indexes, based on fragmentation value.

&lt;code&gt;

/* 
Added a @ViewOnly variable that will allow you to run this script as a test only and review proposed actions.
I also enhanced to perform either a reorg or rebuild, based on range of fragmentation value.
~Paul DeBrino : infinityrd.com

--INSPECT INDEXES&#039; FILL FACTOR VALUES:
use YourDBName
select * from sys.indexes order by name

--VIEW THE DEFAULT FILL FACTOR OF YOUR SERVER:
use YourDBname
exec sp_configure &#039;show advanced options&#039;, 1
go
reconfigure
go
exec sp_configure &#039;fill factor&#039;
go

*/
-- Specify your Database Name
USE YourDBname
GO

-- Declare variables
SET NOCOUNT ON
DECLARE @tablename VARCHAR(128)
DECLARE @execstr   VARCHAR(255)
DECLARE @objectid  INT
DECLARE @indexid   INT
DECLARE @frag      decimal
DECLARE @maxreorg   decimal
DECLARE @maxrebuild decimal
DECLARE @IdxName   varchar(128)
DECLARE @ViewOnly  bit
DECLARE @ReorgOptions varchar(255)
DECLARE @RebuildOptions varchar(255)

-- Set to 1 to view proposed actions, set to 0 to Execute proposed actions:
SET @ViewOnly=1

-- Decide on the maximum fragmentation to allow for a reorganize.
-- AVAILABLE OPTIONS: http://technet.microsoft.com/en-us/library/ms188388(SQL.90).aspx
SET @maxreorg = 20.0
SET @ReorgOptions = &#039;LOB_COMPACTION=ON&#039;
-- Decide on the maximum fragmentation to allow for a rebuild.
SET @maxrebuild = 30.0
-- NOTE: only specifiy FILLFACTOR=x if x is something other than zero:
SET @RebuildOptions = &#039;PAD_INDEX=OFF, SORT_IN_TEMPDB=ON, STATISTICS_NORECOMPUTE=OFF, ALLOW_ROW_LOCKS=ON, ALLOW_PAGE_LOCKS=ON&#039;

-- Declare a cursor.
DECLARE tables CURSOR FOR
   SELECT CAST(TABLE_SCHEMA AS VARCHAR(100))
	+&#039;.&#039;+CAST(TABLE_NAME AS VARCHAR(100))
           AS Table_Name
   FROM INFORMATION_SCHEMA.TABLES
   WHERE TABLE_TYPE = &#039;BASE TABLE&#039;

-- Create the temporary table.
if exists (select name from tempdb.dbo.sysobjects where name like &#039;#fraglist%&#039;)
	drop table #fraglist

CREATE TABLE #fraglist (
   ObjectName CHAR(255),
   ObjectId INT,
   IndexName CHAR(255),
   IndexId INT,
   Lvl INT,
   CountPages INT,
   CountRows INT,
   MinRecSize INT,
   MaxRecSize INT,
   AvgRecSize INT,
   ForRecCount INT,
   Extents INT,
   ExtentSwitches INT,
   AvgFreeBytes INT,
   AvgPageDensity INT,
   ScanDensity decimal,
   BestCount INT,
   ActualCount INT,
   LogicalFrag decimal,
   ExtentFrag decimal)

-- Open the cursor.
OPEN tables

-- Loop through all the tables in the database.
FETCH NEXT
   FROM tables
   INTO @tablename

WHILE @@FETCH_STATUS = 0
BEGIN
-- Do the showcontig of all indexes of the table
   INSERT INTO #fraglist
   EXEC (&#039;DBCC SHOWCONTIG (&#039;&#039;&#039; + @tablename + &#039;&#039;&#039;)
      WITH FAST, TABLERESULTS, ALL_INDEXES, NO_INFOMSGS&#039;)
   FETCH NEXT
      FROM tables
      INTO @tablename
END

-- Close and deallocate the cursor.
CLOSE tables
DEALLOCATE tables

-- Declare the cursor for the list of indexes to be defragged.
DECLARE indexes CURSOR FOR
   SELECT ObjectName, ObjectId, IndexId, LogicalFrag, IndexName
   FROM #fraglist
   WHERE ((LogicalFrag &gt;= @maxreorg) OR (LogicalFrag &gt;= @maxrebuild))
      AND INDEXPROPERTY (ObjectId, IndexName, &#039;IndexDepth&#039;) &gt; 0

-- Open the cursor.
OPEN indexes

-- Loop through the indexes.
FETCH NEXT
   FROM indexes
   INTO @tablename, @objectid, @indexid, @frag, @IdxName

WHILE @@FETCH_STATUS = 0
BEGIN
	IF (@frag &gt;= @maxrebuild)
	BEGIN
		IF (@ViewOnly=1)
		BEGIN
			PRINT &#039;WOULD be executing ALTER INDEX &#039; + RTRIM(@IdxName) + &#039; ON &#039; + RTRIM(@tablename) + &#039; REBUILD WITH ( &#039; + @RebuildOptions + &#039; ) -- Fragmentation currently &#039; + RTRIM(CONVERT(VARCHAR(15),@frag)) + &#039;%&#039;
		END
		ELSE
		BEGIN
			PRINT &#039;Now executing ALTER INDEX &#039; + RTRIM(@IdxName) + &#039; ON &#039; + RTRIM(@tablename) + &#039; REBUILD WITH ( &#039; + @RebuildOptions + &#039; ) -- Fragmentation currently &#039; + RTRIM(CONVERT(VARCHAR(15),@frag)) + &#039;%&#039;
			SELECT @execstr = &#039;ALTER INDEX &#039; + RTRIM(@IdxName) + &#039; ON &#039; + RTRIM(@tablename) + &#039; REBUILD WITH ( &#039; + @RebuildOptions + &#039; )&#039;
			EXEC (@execstr)
		END
	END
	ELSE IF (@frag &gt;= @maxreorg)
	BEGIN
		IF (@ViewOnly=1)
		BEGIN
			PRINT &#039;WOULD be executing ALTER INDEX &#039; + RTRIM(@IdxName) + &#039; ON &#039; + RTRIM(@tablename) + &#039; REORGANIZE WITH ( &#039; + @ReorgOptions + &#039; ) -- Fragmentation currently &#039; + RTRIM(CONVERT(VARCHAR(15),@frag)) + &#039;%&#039;
		END
		ELSE
		BEGIN
			PRINT &#039;Now executing ALTER INDEX &#039; + RTRIM(@IdxName) + &#039; ON &#039; + RTRIM(@tablename) + &#039; REORGANIZE WITH ( &#039; + @ReorgOptions + &#039; ) -- Fragmentation currently &#039; + RTRIM(CONVERT(VARCHAR(15),@frag)) + &#039;%&#039;
			SELECT @execstr = &#039;ALTER INDEX &#039; + RTRIM(@IdxName) + &#039; ON &#039; + RTRIM(@tablename) + &#039; REORGANIZE WITH ( &#039; + @ReorgOptions + &#039; )&#039;
			EXEC (@execstr)
		END
	END

   FETCH NEXT
      FROM indexes
      INTO @tablename, @objectid, @indexid, @frag, @IdxName
END

-- Close and deallocate the cursor.
CLOSE indexes
DEALLOCATE indexes

-- Delete the temporary table.
DROP TABLE #fraglist
GO

&lt;/code&gt;]]></description>
		<content:encoded><![CDATA[<p>This is a different version than the prior post &#8211; it provides the ability to reorg or rebuild indexes, based on fragmentation value.</p>
<p><code></p>
<p>/*<br />
Added a @ViewOnly variable that will allow you to run this script as a test only and review proposed actions.<br />
I also enhanced to perform either a reorg or rebuild, based on range of fragmentation value.<br />
~Paul DeBrino : infinityrd.com</p>
<p>--INSPECT INDEXES' FILL FACTOR VALUES:<br />
use YourDBName<br />
select * from sys.indexes order by name</p>
<p>--VIEW THE DEFAULT FILL FACTOR OF YOUR SERVER:<br />
use YourDBname<br />
exec sp_configure 'show advanced options', 1<br />
go<br />
reconfigure<br />
go<br />
exec sp_configure 'fill factor'<br />
go</p>
<p>*/<br />
-- Specify your Database Name<br />
USE YourDBname<br />
GO</p>
<p>-- Declare variables<br />
SET NOCOUNT ON<br />
DECLARE @tablename VARCHAR(128)<br />
DECLARE @execstr   VARCHAR(255)<br />
DECLARE @objectid  INT<br />
DECLARE @indexid   INT<br />
DECLARE @frag      decimal<br />
DECLARE @maxreorg   decimal<br />
DECLARE @maxrebuild decimal<br />
DECLARE @IdxName   varchar(128)<br />
DECLARE @ViewOnly  bit<br />
DECLARE @ReorgOptions varchar(255)<br />
DECLARE @RebuildOptions varchar(255)</p>
<p>-- Set to 1 to view proposed actions, set to 0 to Execute proposed actions:<br />
SET @ViewOnly=1</p>
<p>-- Decide on the maximum fragmentation to allow for a reorganize.<br />
-- AVAILABLE OPTIONS: <a href="http://technet.microsoft.com/en-us/library/ms188388(SQL.90).aspx" rel="nofollow">http://technet.microsoft.com/en-us/library/ms188388(SQL.90).aspx</a><br />
SET @maxreorg = 20.0<br />
SET @ReorgOptions = 'LOB_COMPACTION=ON'<br />
-- Decide on the maximum fragmentation to allow for a rebuild.<br />
SET @maxrebuild = 30.0<br />
-- NOTE: only specifiy FILLFACTOR=x if x is something other than zero:<br />
SET @RebuildOptions = 'PAD_INDEX=OFF, SORT_IN_TEMPDB=ON, STATISTICS_NORECOMPUTE=OFF, ALLOW_ROW_LOCKS=ON, ALLOW_PAGE_LOCKS=ON'</p>
<p>-- Declare a cursor.<br />
DECLARE tables CURSOR FOR<br />
   SELECT CAST(TABLE_SCHEMA AS VARCHAR(100))<br />
	+'.'+CAST(TABLE_NAME AS VARCHAR(100))<br />
           AS Table_Name<br />
   FROM INFORMATION_SCHEMA.TABLES<br />
   WHERE TABLE_TYPE = 'BASE TABLE'</p>
<p>-- Create the temporary table.<br />
if exists (select name from tempdb.dbo.sysobjects where name like '#fraglist%')<br />
	drop table #fraglist</p>
<p>CREATE TABLE #fraglist (<br />
   ObjectName CHAR(255),<br />
   ObjectId INT,<br />
   IndexName CHAR(255),<br />
   IndexId INT,<br />
   Lvl INT,<br />
   CountPages INT,<br />
   CountRows INT,<br />
   MinRecSize INT,<br />
   MaxRecSize INT,<br />
   AvgRecSize INT,<br />
   ForRecCount INT,<br />
   Extents INT,<br />
   ExtentSwitches INT,<br />
   AvgFreeBytes INT,<br />
   AvgPageDensity INT,<br />
   ScanDensity decimal,<br />
   BestCount INT,<br />
   ActualCount INT,<br />
   LogicalFrag decimal,<br />
   ExtentFrag decimal)</p>
<p>-- Open the cursor.<br />
OPEN tables</p>
<p>-- Loop through all the tables in the database.<br />
FETCH NEXT<br />
   FROM tables<br />
   INTO @tablename</p>
<p>WHILE @@FETCH_STATUS = 0<br />
BEGIN<br />
-- Do the showcontig of all indexes of the table<br />
   INSERT INTO #fraglist<br />
   EXEC ('DBCC SHOWCONTIG (''' + @tablename + ''')<br />
      WITH FAST, TABLERESULTS, ALL_INDEXES, NO_INFOMSGS')<br />
   FETCH NEXT<br />
      FROM tables<br />
      INTO @tablename<br />
END</p>
<p>-- Close and deallocate the cursor.<br />
CLOSE tables<br />
DEALLOCATE tables</p>
<p>-- Declare the cursor for the list of indexes to be defragged.<br />
DECLARE indexes CURSOR FOR<br />
   SELECT ObjectName, ObjectId, IndexId, LogicalFrag, IndexName<br />
   FROM #fraglist<br />
   WHERE ((LogicalFrag &gt;= @maxreorg) OR (LogicalFrag &gt;= @maxrebuild))<br />
      AND INDEXPROPERTY (ObjectId, IndexName, 'IndexDepth') &gt; 0</p>
<p>-- Open the cursor.<br />
OPEN indexes</p>
<p>-- Loop through the indexes.<br />
FETCH NEXT<br />
   FROM indexes<br />
   INTO @tablename, @objectid, @indexid, @frag, @IdxName</p>
<p>WHILE @@FETCH_STATUS = 0<br />
BEGIN<br />
	IF (@frag &gt;= @maxrebuild)<br />
	BEGIN<br />
		IF (@ViewOnly=1)<br />
		BEGIN<br />
			PRINT 'WOULD be executing ALTER INDEX ' + RTRIM(@IdxName) + ' ON ' + RTRIM(@tablename) + ' REBUILD WITH ( ' + @RebuildOptions + ' ) -- Fragmentation currently ' + RTRIM(CONVERT(VARCHAR(15),@frag)) + '%'<br />
		END<br />
		ELSE<br />
		BEGIN<br />
			PRINT 'Now executing ALTER INDEX ' + RTRIM(@IdxName) + ' ON ' + RTRIM(@tablename) + ' REBUILD WITH ( ' + @RebuildOptions + ' ) -- Fragmentation currently ' + RTRIM(CONVERT(VARCHAR(15),@frag)) + '%'<br />
			SELECT @execstr = 'ALTER INDEX ' + RTRIM(@IdxName) + ' ON ' + RTRIM(@tablename) + ' REBUILD WITH ( ' + @RebuildOptions + ' )'<br />
			EXEC (@execstr)<br />
		END<br />
	END<br />
	ELSE IF (@frag &gt;= @maxreorg)<br />
	BEGIN<br />
		IF (@ViewOnly=1)<br />
		BEGIN<br />
			PRINT 'WOULD be executing ALTER INDEX ' + RTRIM(@IdxName) + ' ON ' + RTRIM(@tablename) + ' REORGANIZE WITH ( ' + @ReorgOptions + ' ) -- Fragmentation currently ' + RTRIM(CONVERT(VARCHAR(15),@frag)) + '%'<br />
		END<br />
		ELSE<br />
		BEGIN<br />
			PRINT 'Now executing ALTER INDEX ' + RTRIM(@IdxName) + ' ON ' + RTRIM(@tablename) + ' REORGANIZE WITH ( ' + @ReorgOptions + ' ) -- Fragmentation currently ' + RTRIM(CONVERT(VARCHAR(15),@frag)) + '%'<br />
			SELECT @execstr = 'ALTER INDEX ' + RTRIM(@IdxName) + ' ON ' + RTRIM(@tablename) + ' REORGANIZE WITH ( ' + @ReorgOptions + ' )'<br />
			EXEC (@execstr)<br />
		END<br />
	END</p>
<p>   FETCH NEXT<br />
      FROM indexes<br />
      INTO @tablename, @objectid, @indexid, @frag, @IdxName<br />
END</p>
<p>-- Close and deallocate the cursor.<br />
CLOSE indexes<br />
DEALLOCATE indexes</p>
<p>-- Delete the temporary table.<br />
DROP TABLE #fraglist<br />
GO</p>
<p></code></p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Paul DeBrino</title>
		<link>http://blog.sqlauthority.com/2008/03/04/sql-server-2005-a-simple-way-to-defragment-all-indexes-in-a-database-that-is-fragmented-above-a-declared-threshold/#comment-44103</link>
		<dc:creator><![CDATA[Paul DeBrino]]></dc:creator>
		<pubDate>Fri, 07 Nov 2008 19:00:24 +0000</pubDate>
		<guid isPermaLink="false">http://sqlauthority.wordpress.com/?p=526#comment-44103</guid>
		<description><![CDATA[HalfHuman’s two-part suggestion results in the following complete script. I also added a @ViewOnly variable that will allow you to run this script as a test only. I am also wrapping this post with &lt;CODE&gt; &lt;/CODE&gt;to keep the webserver from mangling the script.

&lt;code&gt;
-- Specify your Database Name
USE DatabaseName
GO

-- Declare variables
SET NOCOUNT ON
DECLARE @tablename VARCHAR(128)
DECLARE @execstr   VARCHAR(255)
DECLARE @objectid  INT
DECLARE @indexid   INT
DECLARE @frag      decimal
DECLARE @maxfrag   decimal
DECLARE @IdxName   varchar(128)
DECLARE @ViewOnly  bit

-- Set to 1 to view proposed actions, set to 0 to Execute proposed actions:
SET @ViewOnly=1

-- Decide on the maximum fragmentation to allow for.
SET @maxfrag = 30.0

-- Declare a cursor.
DECLARE tables CURSOR FOR
   SELECT CAST(TABLE_SCHEMA AS VARCHAR(100))
	+&#039;.&#039;+CAST(TABLE_NAME AS VARCHAR(100))
           AS Table_Name
   FROM INFORMATION_SCHEMA.TABLES
   WHERE TABLE_TYPE = &#039;BASE TABLE&#039;

-- Create the temporary table.
if exists (select name from tempdb.dbo.sysobjects where name like &#039;#fraglist%&#039;)
	drop table #fraglist

CREATE TABLE #fraglist (
   ObjectName CHAR(255),
   ObjectId INT,
   IndexName CHAR(255),
   IndexId INT,
   Lvl INT,
   CountPages INT,
   CountRows INT,
   MinRecSize INT,
   MaxRecSize INT,
   AvgRecSize INT,
   ForRecCount INT,
   Extents INT,
   ExtentSwitches INT,
   AvgFreeBytes INT,
   AvgPageDensity INT,
   ScanDensity decimal,
   BestCount INT,
   ActualCount INT,
   LogicalFrag decimal,
   ExtentFrag decimal)

-- Open the cursor.
OPEN tables

-- Loop through all the tables in the database.
FETCH NEXT
   FROM tables
   INTO @tablename

WHILE @@FETCH_STATUS = 0
BEGIN
-- Do the showcontig of all indexes of the table
   INSERT INTO #fraglist
   EXEC (&#039;DBCC SHOWCONTIG (&#039;&#039;&#039; + @tablename + &#039;&#039;&#039;)
      WITH FAST, TABLERESULTS, ALL_INDEXES, NO_INFOMSGS&#039;)
   FETCH NEXT
      FROM tables
      INTO @tablename
END

-- Close and deallocate the cursor.
CLOSE tables
DEALLOCATE tables

-- Declare the cursor for the list of indexes to be defragged.
DECLARE indexes CURSOR FOR
   SELECT ObjectName, ObjectId, IndexId, LogicalFrag, IndexName
   FROM #fraglist
   WHERE LogicalFrag &gt;= @maxfrag
      AND INDEXPROPERTY (ObjectId, IndexName, &#039;IndexDepth&#039;) &gt; 0

-- Open the cursor.
OPEN indexes

-- Loop through the indexes.
FETCH NEXT
   FROM indexes
   INTO @tablename, @objectid, @indexid, @frag, @IdxName

WHILE @@FETCH_STATUS = 0
BEGIN
	IF (@ViewOnly=1)
	BEGIN
		PRINT &#039;WOULD be executing ALTER INDEX &#039; + RTRIM(@IdxName) + &#039; ON &#039; + RTRIM(@tablename) + &#039; REORGANIZE WITH ( LOB_COMPACTION = ON ) - Fragmentation currently &#039; + RTRIM(CONVERT(VARCHAR(15),@frag)) + &#039;%&#039;
	END
	ELSE
	BEGIN
		PRINT &#039;Now executing ALTER INDEX &#039; + RTRIM(@IdxName) + &#039; ON &#039; + RTRIM(@tablename) + &#039; REORGANIZE WITH ( LOB_COMPACTION = ON ) - Fragmentation currently &#039; + RTRIM(CONVERT(VARCHAR(15),@frag)) + &#039;%&#039;
		SELECT @execstr = &#039;ALTER INDEX &#039; + RTRIM(@IdxName) + &#039; ON &#039; + RTRIM(@tablename) + &#039; REORGANIZE WITH ( LOB_COMPACTION = ON )&#039;
		EXEC (@execstr)
	END

   FETCH NEXT
      FROM indexes
      INTO @tablename, @objectid, @indexid, @frag, @IdxName
END

-- Close and deallocate the cursor.
CLOSE indexes
DEALLOCATE indexes

-- Delete the temporary table.
DROP TABLE #fraglist
GO
&lt;/code&gt;]]></description>
		<content:encoded><![CDATA[<p>HalfHuman’s two-part suggestion results in the following complete script. I also added a @ViewOnly variable that will allow you to run this script as a test only. I am also wrapping this post with &lt;CODE&gt; &lt;/CODE&gt;to keep the webserver from mangling the script.</p>
<p><code><br />
-- Specify your Database Name<br />
USE DatabaseName<br />
GO</p>
<p>-- Declare variables<br />
SET NOCOUNT ON<br />
DECLARE @tablename VARCHAR(128)<br />
DECLARE @execstr   VARCHAR(255)<br />
DECLARE @objectid  INT<br />
DECLARE @indexid   INT<br />
DECLARE @frag      decimal<br />
DECLARE @maxfrag   decimal<br />
DECLARE @IdxName   varchar(128)<br />
DECLARE @ViewOnly  bit</p>
<p>-- Set to 1 to view proposed actions, set to 0 to Execute proposed actions:<br />
SET @ViewOnly=1</p>
<p>-- Decide on the maximum fragmentation to allow for.<br />
SET @maxfrag = 30.0</p>
<p>-- Declare a cursor.<br />
DECLARE tables CURSOR FOR<br />
   SELECT CAST(TABLE_SCHEMA AS VARCHAR(100))<br />
	+'.'+CAST(TABLE_NAME AS VARCHAR(100))<br />
           AS Table_Name<br />
   FROM INFORMATION_SCHEMA.TABLES<br />
   WHERE TABLE_TYPE = 'BASE TABLE'</p>
<p>-- Create the temporary table.<br />
if exists (select name from tempdb.dbo.sysobjects where name like '#fraglist%')<br />
	drop table #fraglist</p>
<p>CREATE TABLE #fraglist (<br />
   ObjectName CHAR(255),<br />
   ObjectId INT,<br />
   IndexName CHAR(255),<br />
   IndexId INT,<br />
   Lvl INT,<br />
   CountPages INT,<br />
   CountRows INT,<br />
   MinRecSize INT,<br />
   MaxRecSize INT,<br />
   AvgRecSize INT,<br />
   ForRecCount INT,<br />
   Extents INT,<br />
   ExtentSwitches INT,<br />
   AvgFreeBytes INT,<br />
   AvgPageDensity INT,<br />
   ScanDensity decimal,<br />
   BestCount INT,<br />
   ActualCount INT,<br />
   LogicalFrag decimal,<br />
   ExtentFrag decimal)</p>
<p>-- Open the cursor.<br />
OPEN tables</p>
<p>-- Loop through all the tables in the database.<br />
FETCH NEXT<br />
   FROM tables<br />
   INTO @tablename</p>
<p>WHILE @@FETCH_STATUS = 0<br />
BEGIN<br />
-- Do the showcontig of all indexes of the table<br />
   INSERT INTO #fraglist<br />
   EXEC ('DBCC SHOWCONTIG (''' + @tablename + ''')<br />
      WITH FAST, TABLERESULTS, ALL_INDEXES, NO_INFOMSGS')<br />
   FETCH NEXT<br />
      FROM tables<br />
      INTO @tablename<br />
END</p>
<p>-- Close and deallocate the cursor.<br />
CLOSE tables<br />
DEALLOCATE tables</p>
<p>-- Declare the cursor for the list of indexes to be defragged.<br />
DECLARE indexes CURSOR FOR<br />
   SELECT ObjectName, ObjectId, IndexId, LogicalFrag, IndexName<br />
   FROM #fraglist<br />
   WHERE LogicalFrag &gt;= @maxfrag<br />
      AND INDEXPROPERTY (ObjectId, IndexName, 'IndexDepth') &gt; 0</p>
<p>-- Open the cursor.<br />
OPEN indexes</p>
<p>-- Loop through the indexes.<br />
FETCH NEXT<br />
   FROM indexes<br />
   INTO @tablename, @objectid, @indexid, @frag, @IdxName</p>
<p>WHILE @@FETCH_STATUS = 0<br />
BEGIN<br />
	IF (@ViewOnly=1)<br />
	BEGIN<br />
		PRINT 'WOULD be executing ALTER INDEX ' + RTRIM(@IdxName) + ' ON ' + RTRIM(@tablename) + ' REORGANIZE WITH ( LOB_COMPACTION = ON ) - Fragmentation currently ' + RTRIM(CONVERT(VARCHAR(15),@frag)) + '%'<br />
	END<br />
	ELSE<br />
	BEGIN<br />
		PRINT 'Now executing ALTER INDEX ' + RTRIM(@IdxName) + ' ON ' + RTRIM(@tablename) + ' REORGANIZE WITH ( LOB_COMPACTION = ON ) - Fragmentation currently ' + RTRIM(CONVERT(VARCHAR(15),@frag)) + '%'<br />
		SELECT @execstr = 'ALTER INDEX ' + RTRIM(@IdxName) + ' ON ' + RTRIM(@tablename) + ' REORGANIZE WITH ( LOB_COMPACTION = ON )'<br />
		EXEC (@execstr)<br />
	END</p>
<p>   FETCH NEXT<br />
      FROM indexes<br />
      INTO @tablename, @objectid, @indexid, @frag, @IdxName<br />
END</p>
<p>-- Close and deallocate the cursor.<br />
CLOSE indexes<br />
DEALLOCATE indexes</p>
<p>-- Delete the temporary table.<br />
DROP TABLE #fraglist<br />
GO<br />
</code></p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Anvie Knox</title>
		<link>http://blog.sqlauthority.com/2008/03/04/sql-server-2005-a-simple-way-to-defragment-all-indexes-in-a-database-that-is-fragmented-above-a-declared-threshold/#comment-43962</link>
		<dc:creator><![CDATA[Anvie Knox]]></dc:creator>
		<pubDate>Wed, 29 Oct 2008 18:41:33 +0000</pubDate>
		<guid isPermaLink="false">http://sqlauthority.wordpress.com/?p=526#comment-43962</guid>
		<description><![CDATA[I Just like to share this... It defrag index with 50% fragment or more then print a report.



-- Index Fragmentation: Delete unused pages
-- ICDB

Declare @SQL nvarchar(4000),
 @acursor_TableName cursor,
 @TableName varchar(150),
 @acursor_Indexes cursor,
 @Indexes varchar(150)

Create Table #Report
(
[Table Name] varchar(150),
Fragment decimal(18,2),
Defragment decimal(18,2),
Percentage decimal(18,2)
)

Create Table #TableIndex
(
Indexes varchar(150),
Fragment decimal(18,2)
)


--Start Looping (Get table)
set @acursor_TableName = cursor for SELECT TABLE_NAME AS Table_Name FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = &#039;BASE TABLE&#039; And TABLE_SCHEMA = &#039;dbo&#039;
open @acursor_TableName
fetch next from @acursor_TableName into @TableName
while (@@fetch_status = 0)
begin

---------------------------------------------------------------------------------------------------
INSERT INTO #Report
Values(@TableName,&#039;0&#039;,&#039;0&#039;,&#039;0&#039;)

Truncate Table #TableIndex

Set @SQL = &#039;Select Name, Avg_fragmentation_in_Percent
FROM sys.dm_db_index_physical_stats (db_id(N&#039;&#039;ICDB&#039;&#039;),
	Object_id(&#039;&#039;&#039; + @TableName + &#039;&#039;&#039;),null,null,null) as A
JOIN 
	sys.indexes as B on a.Object_ID = b.Object_id
AND a.index_id = b.index_id
AND name is not null 
AND name  &#039;&#039;&#039;&#039;&#039;

Insert INTO #TableIndex(Indexes,Fragment)
Execute sp_Executesql @sql

UPDATE A SET Fragment = (SELECT Sum(Fragment) / (Select Count(*) FROM #TableIndex) FROM #TableIndex)
FROM #Report A
Where [Table Name] = @TableName


	--Start Looping (Get Indexes)
	set @acursor_Indexes = cursor for SELECT Indexes FROM #TableIndex Where Fragment &gt;= 50
	open @acursor_Indexes
	fetch next from @acursor_Indexes into @Indexes
	while (@@fetch_status = 0)
	begin

---------------------------------------------------------------------------------------------------
	Set @SQL = &#039;Alter INDEX &#039; + @Indexes + &#039; on &#039; + @TableName + &#039; Rebuild&#039;
	Execute sp_Executesql @sql
---------------------------------------------------------------------------------------------------

	 fetch next from @acursor_Indexes into @Indexes
	end

	close @acursor_Indexes
	deallocate @acursor_Indexes
	--End Looping


Truncate Table #TableIndex

Set @SQL = &#039;Select Name, Avg_fragmentation_in_Percent
FROM sys.dm_db_index_physical_stats (db_id(N&#039;&#039;ICDB&#039;&#039;),
	Object_id(&#039;&#039;&#039; + @TableName + &#039;&#039;&#039;),null,null,null) as A
JOIN 
	sys.indexes as B on a.Object_ID = b.Object_id
AND a.index_id = b.index_id
AND name is not null 
AND name  &#039;&#039;&#039;&#039;&#039;

Insert INTO #TableIndex(Indexes,Fragment)
Execute sp_Executesql @sql

UPDATE A SET Defragment = (SELECT Sum(Fragment) / (Select Count(*) FROM #TableIndex) FROM #TableIndex)
FROM #Report A
Where [Table Name] = @TableName

---------------------------------------------------------------------------------------------------

 fetch next from @acursor_TableName into @TableName
end

close @acursor_TableName
deallocate @acursor_TableName
--End Looping


Update A Set Percentage = (Defragment/Fragment) * 100
FROM #Report A
Where Defragment  0 
	and Defragment is not null
	and Fragment  0 
	and Fragment is not null

Select *
FROM #Report
Where Defragment is not null 
and Defragment  &#039;0.00&#039;
and Defragment = Fragment

Drop table #TableIndex
Drop Table #Report]]></description>
		<content:encoded><![CDATA[<p>I Just like to share this&#8230; It defrag index with 50% fragment or more then print a report.</p>
<p>&#8211; Index Fragmentation: Delete unused pages<br />
&#8211; ICDB</p>
<p>Declare @SQL nvarchar(4000),<br />
 @acursor_TableName cursor,<br />
 @TableName varchar(150),<br />
 @acursor_Indexes cursor,<br />
 @Indexes varchar(150)</p>
<p>Create Table #Report<br />
(<br />
[Table Name] varchar(150),<br />
Fragment decimal(18,2),<br />
Defragment decimal(18,2),<br />
Percentage decimal(18,2)<br />
)</p>
<p>Create Table #TableIndex<br />
(<br />
Indexes varchar(150),<br />
Fragment decimal(18,2)<br />
)</p>
<p>&#8211;Start Looping (Get table)<br />
set @acursor_TableName = cursor for SELECT TABLE_NAME AS Table_Name FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = &#8216;BASE TABLE&#8217; And TABLE_SCHEMA = &#8216;dbo&#8217;<br />
open @acursor_TableName<br />
fetch next from @acursor_TableName into @TableName<br />
while (@@fetch_status = 0)<br />
begin</p>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;<br />
INSERT INTO #Report<br />
Values(@TableName,&#8217;0&#8242;,&#8217;0&#8242;,&#8217;0&#8242;)</p>
<p>Truncate Table #TableIndex</p>
<p>Set @SQL = &#8216;Select Name, Avg_fragmentation_in_Percent<br />
FROM sys.dm_db_index_physical_stats (db_id(N&#8221;ICDB&#8221;),<br />
	Object_id(&#8221;&#8217; + @TableName + &#8221;&#8217;),null,null,null) as A<br />
JOIN<br />
	sys.indexes as B on a.Object_ID = b.Object_id<br />
AND a.index_id = b.index_id<br />
AND name is not null<br />
AND name  &#8221;&#8221;&#8217;</p>
<p>Insert INTO #TableIndex(Indexes,Fragment)<br />
Execute sp_Executesql @sql</p>
<p>UPDATE A SET Fragment = (SELECT Sum(Fragment) / (Select Count(*) FROM #TableIndex) FROM #TableIndex)<br />
FROM #Report A<br />
Where [Table Name] = @TableName</p>
<p>	&#8211;Start Looping (Get Indexes)<br />
	set @acursor_Indexes = cursor for SELECT Indexes FROM #TableIndex Where Fragment &gt;= 50<br />
	open @acursor_Indexes<br />
	fetch next from @acursor_Indexes into @Indexes<br />
	while (@@fetch_status = 0)<br />
	begin</p>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;<br />
	Set @SQL = &#8216;Alter INDEX &#8216; + @Indexes + &#8216; on &#8216; + @TableName + &#8216; Rebuild&#8217;<br />
	Execute sp_Executesql @sql<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</p>
<p>	 fetch next from @acursor_Indexes into @Indexes<br />
	end</p>
<p>	close @acursor_Indexes<br />
	deallocate @acursor_Indexes<br />
	&#8211;End Looping</p>
<p>Truncate Table #TableIndex</p>
<p>Set @SQL = &#8216;Select Name, Avg_fragmentation_in_Percent<br />
FROM sys.dm_db_index_physical_stats (db_id(N&#8221;ICDB&#8221;),<br />
	Object_id(&#8221;&#8217; + @TableName + &#8221;&#8217;),null,null,null) as A<br />
JOIN<br />
	sys.indexes as B on a.Object_ID = b.Object_id<br />
AND a.index_id = b.index_id<br />
AND name is not null<br />
AND name  &#8221;&#8221;&#8217;</p>
<p>Insert INTO #TableIndex(Indexes,Fragment)<br />
Execute sp_Executesql @sql</p>
<p>UPDATE A SET Defragment = (SELECT Sum(Fragment) / (Select Count(*) FROM #TableIndex) FROM #TableIndex)<br />
FROM #Report A<br />
Where [Table Name] = @TableName</p>
<p>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</p>
<p> fetch next from @acursor_TableName into @TableName<br />
end</p>
<p>close @acursor_TableName<br />
deallocate @acursor_TableName<br />
&#8211;End Looping</p>
<p>Update A Set Percentage = (Defragment/Fragment) * 100<br />
FROM #Report A<br />
Where Defragment  0<br />
	and Defragment is not null<br />
	and Fragment  0<br />
	and Fragment is not null</p>
<p>Select *<br />
FROM #Report<br />
Where Defragment is not null<br />
and Defragment  &#8217;0.00&#8242;<br />
and Defragment = Fragment</p>
<p>Drop table #TableIndex<br />
Drop Table #Report</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: HalfHuman</title>
		<link>http://blog.sqlauthority.com/2008/03/04/sql-server-2005-a-simple-way-to-defragment-all-indexes-in-a-database-that-is-fragmented-above-a-declared-threshold/#comment-42643</link>
		<dc:creator><![CDATA[HalfHuman]]></dc:creator>
		<pubDate>Wed, 10 Sep 2008 10:39:10 +0000</pubDate>
		<guid isPermaLink="false">http://sqlauthority.wordpress.com/?p=526#comment-42643</guid>
		<description><![CDATA[oops! forgot to tell.
should first declare @IdxName and then use it with the selector]]></description>
		<content:encoded><![CDATA[<p>oops! forgot to tell.<br />
should first declare @IdxName and then use it with the selector</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: HalfHuman</title>
		<link>http://blog.sqlauthority.com/2008/03/04/sql-server-2005-a-simple-way-to-defragment-all-indexes-in-a-database-that-is-fragmented-above-a-declared-threshold/#comment-42642</link>
		<dc:creator><![CDATA[HalfHuman]]></dc:creator>
		<pubDate>Wed, 10 Sep 2008 10:37:42 +0000</pubDate>
		<guid isPermaLink="false">http://sqlauthority.wordpress.com/?p=526#comment-42642</guid>
		<description><![CDATA[hello

found you solution helpfull. don&#039;t want to seem ungratefull but i have a few additions:

1st - i&#039;d check for the existence of the temp table:
if exists (select name from tempdb.dbo.sysobjects where name like &#039;#fraglist%&#039;)
	drop table #fraglist

2nd - id use the alter index aproach as dbcc indexdefrag is deprecated in 2005 and unsupported in 2008. here si the cod snippet for those lazy as me :) :
   PRINT &#039;Executing ALTER INDEX &#039; + RTRIM(@IdxName) + &#039; ON &#039; + RTRIM(@tablename) + &#039;REORGANIZE WITH ( LOB_COMPACTION = ON ) - fragmentation currently &#039; + RTRIM(CONVERT(VARCHAR(15),@frag)) + &#039;%&#039;;
   SELECT @execstr = &#039;ALTER INDEX &#039; + RTRIM(@IdxName) + &#039; ON &#039; + RTRIM(@tablename) + &#039; REORGANIZE WITH ( LOB_COMPACTION = ON )&#039;
   EXEC (@execstr);

instead of 
   PRINT &#039;Executing DBCC INDEXDEFRAG (0, &#039; + RTRIM(@tablename) + &#039;,
      &#039; + RTRIM(@indexid) + &#039;) - fragmentation currently &#039;
       + RTRIM(CONVERT(VARCHAR(15),@frag)) + &#039;%&#039;;
   SELECT @execstr = &#039;DBCC INDEXDEFRAG (0, &#039; + RTRIM(@objectid) + &#039;,
       &#039; + RTRIM(@indexid) + &#039;)&#039;;
   EXEC (@execstr);]]></description>
		<content:encoded><![CDATA[<p>hello</p>
<p>found you solution helpfull. don&#8217;t want to seem ungratefull but i have a few additions:</p>
<p>1st &#8211; i&#8217;d check for the existence of the temp table:<br />
if exists (select name from tempdb.dbo.sysobjects where name like &#8216;#fraglist%&#8217;)<br />
	drop table #fraglist</p>
<p>2nd &#8211; id use the alter index aproach as dbcc indexdefrag is deprecated in 2005 and unsupported in 2008. here si the cod snippet for those lazy as me :) :<br />
   PRINT &#8216;Executing ALTER INDEX &#8216; + RTRIM(@IdxName) + &#8216; ON &#8216; + RTRIM(@tablename) + &#8216;REORGANIZE WITH ( LOB_COMPACTION = ON ) &#8211; fragmentation currently &#8216; + RTRIM(CONVERT(VARCHAR(15),@frag)) + &#8216;%&#8217;;<br />
   SELECT @execstr = &#8216;ALTER INDEX &#8216; + RTRIM(@IdxName) + &#8216; ON &#8216; + RTRIM(@tablename) + &#8216; REORGANIZE WITH ( LOB_COMPACTION = ON )&#8217;<br />
   EXEC (@execstr);</p>
<p>instead of<br />
   PRINT &#8216;Executing DBCC INDEXDEFRAG (0, &#8216; + RTRIM(@tablename) + &#8216;,<br />
      &#8216; + RTRIM(@indexid) + &#8216;) &#8211; fragmentation currently &#8216;<br />
       + RTRIM(CONVERT(VARCHAR(15),@frag)) + &#8216;%&#8217;;<br />
   SELECT @execstr = &#8216;DBCC INDEXDEFRAG (0, &#8216; + RTRIM(@objectid) + &#8216;,<br />
       &#8216; + RTRIM(@indexid) + &#8216;)&#8217;;<br />
   EXEC (@execstr);</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: SD</title>
		<link>http://blog.sqlauthority.com/2008/03/04/sql-server-2005-a-simple-way-to-defragment-all-indexes-in-a-database-that-is-fragmented-above-a-declared-threshold/#comment-34166</link>
		<dc:creator><![CDATA[SD]]></dc:creator>
		<pubDate>Thu, 06 Mar 2008 23:24:45 +0000</pubDate>
		<guid isPermaLink="false">http://sqlauthority.wordpress.com/?p=526#comment-34166</guid>
		<description><![CDATA[Since INDEXDEFRAG will be not supported in SS2008, how about a version of this scrip t with ALTER INDEX rather.]]></description>
		<content:encoded><![CDATA[<p>Since INDEXDEFRAG will be not supported in SS2008, how about a version of this scrip t with ALTER INDEX rather.</p>
]]></content:encoded>
	</item>
</channel>
</rss>

