<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	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:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>SQL Fool &#187; Michelle Ufford</title>
	<atom:link href="http://sqlfool.com/author/michelle/feed/" rel="self" type="application/rss+xml" />
	<link>http://sqlfool.com</link>
	<description>Adventures in SQL Tuning - a blog for the rest of us</description>
	<lastBuildDate>Fri, 16 Jul 2010 14:34:11 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>See you in Seattle!</title>
		<link>http://sqlfool.com/2010/07/see-you-in-seattle/</link>
		<comments>http://sqlfool.com/2010/07/see-you-in-seattle/#comments</comments>
		<pubDate>Fri, 16 Jul 2010 14:34:11 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Miscellaneous]]></category>
		<category><![CDATA[PASS]]></category>
		<category><![CDATA[Presentations]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[380PASS]]></category>
		<category><![CDATA[presentation]]></category>
		<category><![CDATA[SQL Saturday]]></category>
		<category><![CDATA[Summit]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1370</guid>
		<description><![CDATA[My Summit abstract was accepted! I'm still a little surprised, but I'm also excited (okay, and a little nervous) to once more be presenting at the PASS Summit. If you'll be at Summit this year -- and I really hope you are, as it's well worth the time and cost -- then please make sure [...]]]></description>
			<content:encoded><![CDATA[<p>My <a href="http://sqlfool.com/2010/05/summit-2010-abstract-submission/" target="_blank">Summit abstract</a> was accepted!  I'm still a little surprised, but I'm also excited (okay, and a little nervous) to once more be presenting at the <a href="http://www.sqlpass.org/summit/na2010/" target="_blank">PASS Summit</a>.  If you'll be at Summit this year -- and I really hope you are, as it's well worth the time and cost -- then please make sure to say "hi" if you see me wandering around.  Aside from the *excellent* content, my favorite thing about Summit is getting to meet so many great people.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>In other news, I've once more switched roles within GoDaddy.  For the half dozen folks who've been following my blog from the beginning, you may remember that I originally started out on the traffic team working with tuning and VLDB's, then took an opportunity to switch to the BI team to learn more about OLAP.  Recently, a new team has been formed under the BI branch that's tasked with developing a massive hybrid data warehouse (by hybrid, I mean half OLTP and half OLAP).  <em>"How massive is it?"</em>  Well, it's SO massive, we're expecting to be store <a href="http://en.wikipedia.org/wiki/Petabyte" target="_blank">petabytes</a> of data when everything is said and done.  I'm happy to say I'll be on this new team.  So yes, that means <a href="http://godaddy.com/jobs">we have an opening</a> for an OLAP developer.  We're also hiring SQL Server DBA's.  We have offices in Cedar Rapids, Denver, and the Phoenix area.  Send me an e-mail at michelle <em>at</em> sqlfool <em>dot</em> com if you're interested in learning more about this great job opportunity and company.</p>
<p>Lastly, I want to announce that <a href="http://sqlsaturday.com/50/eventhome.aspx" target="_blank">SQL Saturday 50</a> is now open for registration!  SQL Saturday 50 will be held in Iowa City, IA on Saturday, September 18th.  We're almost at 50% of our attendance capacity, so if you're interested in attending, <a href="http://sqlsaturday.com/50/register.aspx" target="_blank">please register soon</a>.  </p>
<p>That's it for now.  I promise that my next blog post will be uber technical.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2010/07/see-you-in-seattle/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>SQL Saturday #50 &#8211; Call for Speakers</title>
		<link>http://sqlfool.com/2010/06/sql-saturday-50-call-for-speakers/</link>
		<comments>http://sqlfool.com/2010/06/sql-saturday-50-call-for-speakers/#comments</comments>
		<pubDate>Mon, 21 Jun 2010 21:04:35 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Miscellaneous]]></category>
		<category><![CDATA[PASS]]></category>
		<category><![CDATA[Presentations]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[380PASS]]></category>
		<category><![CDATA[presentation]]></category>
		<category><![CDATA[SQL Saturday]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1355</guid>
		<description><![CDATA[The Call for Speakers is now open for SQL Saturday #50, the East Iowa SQL Saturday event! This is our second time hosting a SQL Saturday, and we're hoping to build upon the success of last year's event. We're looking for a wide variety of topics on SQL Server and related technologies (i.e. PowerShell, R2, [...]]]></description>
			<content:encoded><![CDATA[<p>The Call for Speakers is now open for SQL Saturday #50, the East Iowa SQL Saturday event!  This is our second time hosting a SQL Saturday, and we're hoping to build upon the success of last year's event.  We're looking for a wide variety of topics on SQL Server and related technologies (i.e. PowerShell, R2, LINQ, etc.).  We also have had several requests for intro-level topics, such as beginning disaster recovery and basic performance tuning.  If you're even remotely thinking about speaking, <a href="http://sqlsaturday.com/50/callforspeakers.aspx" target="_blank">please submit an abstract</a>! </p>
<p>Last year we had about 100 folks attend from surrounding areas.  This year, we're shooting for 125 attendees, which would max out our facility's capacity.  Not sure how far away Iowa City is?  It may be closer than you think.  Allow me to rehash my travel times from <a href="http://sqlfool.com/2009/06/east-iowa-sql-saturday-call-for-speakers/" target="_blank">last year's plea for speakers</a>:</p>
<ul>
<li>Chicago – 3.5 hours</li>
<li>Omaha – 3.5 hours</li>
<li>Milwaukee – 4 hours</li>
<li>Kansas City – 4.5 hours</li>
<li>Minneapolis – 5 hours</li>
<li>St. Louis – 5 hours</li>
<li>Indianapolis – 6 hours</li>
</ul>
<p>The event will be held on September 18th at the University of Iowa in Iowa City. You can find more information, including an abstract submission form, on our event website at <a href="http://sqlsaturday.com/50/eventhome.aspx" target="_blank">http://sqlsaturday.com/50/eventhome.aspx</a>. </p>
<p>Oh, and if you do make it to our SQL Saturday event, please make sure to stop me and say "hi!"  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2010/06/sql-saturday-50-call-for-speakers/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Check VLF Counts</title>
		<link>http://sqlfool.com/2010/06/check-vlf-counts/</link>
		<comments>http://sqlfool.com/2010/06/check-vlf-counts/#comments</comments>
		<pubDate>Tue, 08 Jun 2010 16:03:40 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[SQL Tips]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[T-SQL Scripts]]></category>
		<category><![CDATA[maintenance]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[TSQL]]></category>
		<category><![CDATA[tuning]]></category>
		<category><![CDATA[undocumented commands]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1350</guid>
		<description><![CDATA[Today I stumbled across a database with 87,302 VLF's. Yes, that's right... 87 THOUSAND. Most of our databases have a few dozen VLF's, but this was an old database that had grown to 1.5 TB and had the default autogrowth settings left in tact. How did we discover this? During a routine reboot of the [...]]]></description>
			<content:encoded><![CDATA[<p>Today I stumbled across a database with 87,302 VLF's.  Yes, that's right... 87 THOUSAND.  Most of our databases have a few dozen VLF's, but this was an old database that had grown to 1.5 TB and had the default autogrowth settings left in tact.  How did we discover this?  During a routine reboot of the server, this database took 30 minutes to recover, but there were no error messages or status messages in the log.  </p>
<p>Now, this blog post is not about VLF's or why you should keep the number of VLF's to a small, manageable number -- although I hear under 50 is a good rule of thumb.  No, the purpose of this blog post is to share a little script I wrote to check the number of VLF's each database uses:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> #stage<span style="color: #808080;">&#40;</span>
    FileID      <span style="color: #0000FF;">INT</span>
  , FileSize    <span style="color: #0000FF;">BIGINT</span>
  , StartOffset <span style="color: #0000FF;">BIGINT</span>
  , FSeqNo      <span style="color: #0000FF;">BIGINT</span>
  , <span style="color: #808080;">&#91;</span>Status<span style="color: #808080;">&#93;</span>    <span style="color: #0000FF;">BIGINT</span>
  , Parity      <span style="color: #0000FF;">BIGINT</span>
  , CreateLSN   <span style="color: #0000FF;">NUMERIC</span><span style="color: #808080;">&#40;</span><span style="color: #000;">38</span><span style="color: #808080;">&#41;</span>
<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> #results<span style="color: #808080;">&#40;</span>
    Database_Name   sysname
  , VLF_count       <span style="color: #0000FF;">INT</span> 
<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">EXEC</span> sp_msforeachdb N<span style="color: #FF0000;">'Use ?; 
            Insert Into #stage 
            Exec sp_executeSQL N'</span><span style="color: #FF0000;">'DBCC LogInfo(?)'</span><span style="color: #FF0000;">'; 
&nbsp;
            Insert Into #results 
            Select DB_Name(), Count(*) 
            From #stage; 
&nbsp;
            Truncate Table #stage;'</span>
&nbsp;
<span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">*</span> 
<span style="color: #0000FF;">FROM</span> #results
<span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> VLF_count <span style="color: #0000FF;">DESC</span>;
&nbsp;
<span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">TABLE</span> #stage;
<span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">TABLE</span> #results;</pre></div></div>

<p>This script is low-impact and is safe to run on large, production databases during business hours.  However, just be aware that it's using some undocumented commands.  </p>
<p>For more information on VLF's, check out these excellent articles:</p>
<ul>
<li><a href="http://www.sqlskills.com/BLOGS/KIMBERLY/post/Transaction-Log-VLFs-too-many-or-too-few.aspx" target="_blank">Transaction Log VLF's - Too Many or Too Few?</a></li>
<li><a href="http://technet.microsoft.com/en-us/magazine/2009.02.logging.aspx#id0060025" target="_blank">Understanding Logging &#038; Recovery</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2010/06/check-vlf-counts/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Index Interrogation for SQL Server 2008</title>
		<link>http://sqlfool.com/2010/06/index-interrogation-for-sql-server-2008/</link>
		<comments>http://sqlfool.com/2010/06/index-interrogation-for-sql-server-2008/#comments</comments>
		<pubDate>Fri, 04 Jun 2010 19:55:17 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Internals]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[T-SQL Scripts]]></category>
		<category><![CDATA[indexes]]></category>
		<category><![CDATA[partitioning]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[TSQL]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1344</guid>
		<description><![CDATA[I had previously posted an index interrogation script for SQL Server 2005. I've updated that script for 2008; namely, it includes filtered index definitions. For anyone interested: DECLARE @objectID INT = OBJECT_ID&#40;'Sales.SalesOrderHeader'&#41;; &#160; WITH indexCTE&#40;partition_scheme_name , partition_function_name , data_space_id&#41; AS &#40; SELECT sps.name , spf.name , sps.data_space_id FROM sys.partition_schemes AS sps Join sys.partition_functions AS spf [...]]]></description>
			<content:encoded><![CDATA[<p>I had previously posted an index interrogation script for SQL Server 2005.  I've updated that script for 2008; namely, it includes filtered index definitions.  For anyone interested:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">DECLARE</span> @objectID <span style="color: #0000FF;">INT</span> <span style="color: #808080;">=</span> <span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Sales.SalesOrderHeader'</span><span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">WITH</span> indexCTE<span style="color: #808080;">&#40;</span>partition_scheme_name
            , partition_function_name
            , data_space_id<span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">AS</span> <span style="color: #808080;">&#40;</span>
    <span style="color: #0000FF;">SELECT</span> sps.<span style="color: #202020;">name</span>
        , spf.<span style="color: #202020;">name</span>
        , sps.<span style="color: #202020;">data_space_id</span>
    <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">partition_schemes</span> <span style="color: #0000FF;">AS</span> sps
    Join sys.<span style="color: #202020;">partition_functions</span> <span style="color: #0000FF;">AS</span> spf
        <span style="color: #0000FF;">ON</span> sps.<span style="color: #202020;">function_id</span> <span style="color: #808080;">=</span> spf.<span style="color: #202020;">function_id</span>
<span style="color: #808080;">&#41;</span>
&nbsp;
<span style="color: #0000FF;">SELECT</span> st.<span style="color: #202020;">name</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'table_name'</span>
    , IsNull<span style="color: #808080;">&#40;</span>ix.<span style="color: #202020;">name</span>, <span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'index_name'</span>
    , ix.<span style="color: #FF00FF;">OBJECT_ID</span>
    , ix.<span style="color: #202020;">index_id</span>
	, <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>
        <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> ix.<span style="color: #202020;">index_id</span> <span style="color: #808080;">=</span> <span style="color: #000;">1</span> 
                <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">'clustered'</span> 
            <span style="color: #0000FF;">WHEN</span> ix.<span style="color: #202020;">index_id</span> <span style="color: #808080;">=</span><span style="color: #000;">0</span>
                <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">'heap'</span>
            <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">'nonclustered'</span> <span style="color: #0000FF;">END</span>
		<span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> ix.<span style="color: #202020;">ignore_dup_key</span> <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">0</span> 
            <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">', ignore duplicate keys'</span> 
                <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">''</span> <span style="color: #0000FF;">END</span>
		<span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> ix.<span style="color: #202020;">is_unique</span> <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">0</span> 
            <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">', unique'</span> 
                <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">''</span> <span style="color: #0000FF;">END</span>
		<span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> ix.<span style="color: #202020;">is_primary_key</span> <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">0</span> 
            <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">', primary key'</span> <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">''</span> <span style="color: #0000FF;">END</span> <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">210</span><span style="color: #808080;">&#41;</span>
        <span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'index_description'</span>
    , IsNull<span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">REPLACE</span><span style="color: #808080;">&#40;</span> <span style="color: #FF00FF;">REPLACE</span><span style="color: #808080;">&#40;</span> <span style="color: #FF00FF;">REPLACE</span><span style="color: #808080;">&#40;</span>
        <span style="color: #808080;">&#40;</span>   
            <span style="color: #0000FF;">SELECT</span> c.<span style="color: #202020;">name</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'columnName'</span>
            <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">index_columns</span> <span style="color: #0000FF;">AS</span> sic
            Join sys.<span style="color: #202020;">columns</span> <span style="color: #0000FF;">AS</span> c 
                <span style="color: #0000FF;">ON</span> c.<span style="color: #202020;">column_id</span> <span style="color: #808080;">=</span> sic.<span style="color: #202020;">column_id</span> 
                And c.<span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> sic.<span style="color: #FF00FF;">OBJECT_ID</span>
            <span style="color: #0000FF;">WHERE</span> sic.<span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> ix.<span style="color: #FF00FF;">OBJECT_ID</span>
                And sic.<span style="color: #202020;">index_id</span> <span style="color: #808080;">=</span> ix.<span style="color: #202020;">index_id</span>
                And is_included_column <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
            <span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> sic.<span style="color: #202020;">index_column_id</span>
            <span style="color: #0000FF;">FOR</span> XML Raw<span style="color: #808080;">&#41;</span>
            , <span style="color: #FF0000;">'&quot;/&gt;&lt;row columnName=&quot;'</span>, <span style="color: #FF0000;">', '</span><span style="color: #808080;">&#41;</span>
            , <span style="color: #FF0000;">'&lt;row columnName=&quot;'</span>, <span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>
            , <span style="color: #FF0000;">'&quot;/&gt;'</span>, <span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>, <span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'indexed_columns'</span>
    , IsNull<span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">REPLACE</span><span style="color: #808080;">&#40;</span> <span style="color: #FF00FF;">REPLACE</span><span style="color: #808080;">&#40;</span> <span style="color: #FF00FF;">REPLACE</span><span style="color: #808080;">&#40;</span>
        <span style="color: #808080;">&#40;</span>   
            <span style="color: #0000FF;">SELECT</span> c.<span style="color: #202020;">name</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'columnName'</span>
            <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">index_columns</span> <span style="color: #0000FF;">AS</span> sic
            Join sys.<span style="color: #202020;">columns</span> <span style="color: #0000FF;">AS</span> c 
                <span style="color: #0000FF;">ON</span> c.<span style="color: #202020;">column_id</span> <span style="color: #808080;">=</span> sic.<span style="color: #202020;">column_id</span> 
                And c.<span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> sic.<span style="color: #FF00FF;">OBJECT_ID</span>
            <span style="color: #0000FF;">WHERE</span> sic.<span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> ix.<span style="color: #FF00FF;">OBJECT_ID</span>
                And sic.<span style="color: #202020;">index_id</span> <span style="color: #808080;">=</span> ix.<span style="color: #202020;">index_id</span>
                And is_included_column <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
            <span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> sic.<span style="color: #202020;">index_column_id</span>
            <span style="color: #0000FF;">FOR</span> XML Raw<span style="color: #808080;">&#41;</span>
            , <span style="color: #FF0000;">'&quot;/&gt;&lt;row columnName=&quot;'</span>, <span style="color: #FF0000;">', '</span><span style="color: #808080;">&#41;</span>
            , <span style="color: #FF0000;">'&lt;row columnName=&quot;'</span>, <span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>
            , <span style="color: #FF0000;">'&quot;/&gt;'</span>, <span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>, <span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'included_columns'</span>
    , ix.<span style="color: #202020;">filter_definition</span>
    , IsNull<span style="color: #808080;">&#40;</span>cte.<span style="color: #202020;">partition_scheme_name</span>, <span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'partition_scheme_name'</span>
    , <span style="color: #FF00FF;">COUNT</span><span style="color: #808080;">&#40;</span>partition_number<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'partition_count'</span>
    , <span style="color: #FF00FF;">SUM</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">ROWS</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'row_count'</span>
<span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">indexes</span> <span style="color: #0000FF;">AS</span> ix
Join sys.<span style="color: #202020;">partitions</span> <span style="color: #0000FF;">AS</span> sp
    <span style="color: #0000FF;">ON</span> ix.<span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> sp.<span style="color: #FF00FF;">OBJECT_ID</span>
    And ix.<span style="color: #202020;">index_id</span> <span style="color: #808080;">=</span> sp.<span style="color: #202020;">index_id</span>
Join sys.<span style="color: #202020;">tables</span> <span style="color: #0000FF;">AS</span> st
    <span style="color: #0000FF;">ON</span> ix.<span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> st.<span style="color: #FF00FF;">OBJECT_ID</span>
<span style="color: #0000FF;">LEFT</span> Join indexCTE <span style="color: #0000FF;">AS</span> cte
    <span style="color: #0000FF;">ON</span> ix.<span style="color: #202020;">data_space_id</span> <span style="color: #808080;">=</span> cte.<span style="color: #202020;">data_space_id</span>
<span style="color: #0000FF;">WHERE</span> ix.<span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> IsNull<span style="color: #808080;">&#40;</span>@objectID, ix.<span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">GROUP</span> <span style="color: #0000FF;">BY</span> st.<span style="color: #202020;">name</span>
    , IsNull<span style="color: #808080;">&#40;</span>ix.<span style="color: #202020;">name</span>, <span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>
    , ix.<span style="color: #FF00FF;">OBJECT_ID</span>
    , ix.<span style="color: #202020;">index_id</span>
	, <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>
        <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> ix.<span style="color: #202020;">index_id</span> <span style="color: #808080;">=</span> <span style="color: #000;">1</span> 
                <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">'clustered'</span> 
            <span style="color: #0000FF;">WHEN</span> ix.<span style="color: #202020;">index_id</span> <span style="color: #808080;">=</span><span style="color: #000;">0</span>
                <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">'heap'</span>
            <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">'nonclustered'</span> <span style="color: #0000FF;">END</span>
		<span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> ix.<span style="color: #202020;">ignore_dup_key</span> <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">0</span> 
            <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">', ignore duplicate keys'</span> 
                <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">''</span> <span style="color: #0000FF;">END</span>
		<span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> ix.<span style="color: #202020;">is_unique</span> <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">0</span> 
            <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">', unique'</span> 
                <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">''</span> <span style="color: #0000FF;">END</span>
		<span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> ix.<span style="color: #202020;">is_primary_key</span> <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">0</span> 
            <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">', primary key'</span> <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">''</span> <span style="color: #0000FF;">END</span> <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">210</span><span style="color: #808080;">&#41;</span>
        <span style="color: #808080;">&#41;</span>
    , ix.<span style="color: #202020;">filter_definition</span>
    , IsNull<span style="color: #808080;">&#40;</span>cte.<span style="color: #202020;">partition_scheme_name</span>, <span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>
    , IsNull<span style="color: #808080;">&#40;</span>cte.<span style="color: #202020;">partition_function_name</span>, <span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> table_name
    , index_id;</pre></div></div>

<p>You may need to create some indexes to see this in AdventureWorks:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">NONCLUSTERED</span> <span style="color: #0000FF;">INDEX</span> IX_Sales_SalesOrderHeader_filtered_2005
    <span style="color: #0000FF;">ON</span> Sales.<span style="color: #202020;">SalesOrderHeader</span><span style="color: #808080;">&#40;</span>AccountNumber<span style="color: #808080;">&#41;</span>
    Include <span style="color: #808080;">&#40;</span>CustomerID, SalesPersonID<span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">WHERE</span> OrderDate <span style="color: #808080;">&gt;=</span> <span style="color: #FF0000;">'2005-01-01'</span>
        And OrderDate <span style="color: #808080;">&lt;</span> <span style="color: #FF0000;">'2006-01-01'</span>;</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">table_name           index_name                               object_id   index_id    index_description                   indexed_columns      included_columns               filter_definition                                            partition_scheme_name partition_count row_count
-------------------- ---------------------------------------- ----------- ----------- ----------------------------------- -------------------- ------------------------------ ------------------------------------------------------------ --------------------- --------------- --------------------
SalesOrderHeader     PK_SalesOrderHeader_SalesOrderID         1010102639  1           clustered, unique, primary key      SalesOrderID                                        NULL                                                                               1               31465
SalesOrderHeader     AK_SalesOrderHeader_rowguid              1010102639  2           nonclustered, unique                rowguid                                             NULL                                                                               1               31465
SalesOrderHeader     AK_SalesOrderHeader_SalesOrderNumber     1010102639  3           nonclustered, unique                SalesOrderNumber                                    NULL                                                                               1               31465
SalesOrderHeader     IX_SalesOrderHeader_CustomerID           1010102639  5           nonclustered                        CustomerID                                          NULL                                                                               1               31465
SalesOrderHeader     IX_SalesOrderHeader_SalesPersonID        1010102639  6           nonclustered                        SalesPersonID                                       NULL                                                                               1               31465
SalesOrderHeader     IX_Sales_SalesOrderHeader_filtered_2005  1010102639  13          nonclustered                        AccountNumber        CustomerID, SalesPersonID      ([OrderDate]&gt;='2005-01-01' AND [OrderDate]&lt;'2006-01-01')                           1               1379</pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2010/06/index-interrogation-for-sql-server-2008/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Summit 2010 Abstract Submission</title>
		<link>http://sqlfool.com/2010/05/summit-2010-abstract-submission/</link>
		<comments>http://sqlfool.com/2010/05/summit-2010-abstract-submission/#comments</comments>
		<pubDate>Fri, 28 May 2010 19:02:33 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[PASS]]></category>
		<category><![CDATA[Presentations]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[defrag]]></category>
		<category><![CDATA[defragment]]></category>
		<category><![CDATA[fragmentation]]></category>
		<category><![CDATA[indexes]]></category>
		<category><![CDATA[Internals]]></category>
		<category><![CDATA[partitioning]]></category>
		<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[presentation]]></category>
		<category><![CDATA[Summit]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1341</guid>
		<description><![CDATA[Jeremiah Peschka just tweeted about the looming deadline to submit an abstract for Summit 2010. I've been trying to think of a good topic to present on, and this finally got my butt in gear to submit one! For those interested, here's what I submitted: Heaps of Trouble, Clusters of Glory - A Look At [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://facility9.com" target="_blank">Jeremiah Peschka</a> <a href="http://twitter.com/peschkaj/statuses/14924746005" target="_blank">just tweeted</a> about the looming deadline to submit an abstract for <a href="http://www.sqlpass.org/summit/na2010/default.aspx" target="_blank">Summit 2010</a>.  I've been trying to think of a good topic to present on, and this finally got my butt in gear to submit one!  For those interested, here's what I submitted:</p>
<p><strong>Heaps of Trouble, Clusters of Glory - A Look At Index Internals</strong></p>
<blockquote><p>Indexes are a crucial component of SQL Server, especially in performance tuning, yet many DBA's don't fully understand how indexes work.  In this in-depth session, Michelle will examine the anatomy of indexes, from how they're stored to how they get fragmented.  And to make our inner geeks happy, she'll look at page data to show you what's happening behind the scenes.  Topics covered will include index structure, fragmentation and defragmentation, index partitioning, and index filtering.  If you've ever wondered just *what* goes on in an index, don't miss this session!</p></blockquote>
<p>Special thanks to <a href="http://twitter.com/databaseguy" target="_blank">Chris</a> for help with the session title.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2010/05/summit-2010-abstract-submission/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>DELETE 5_Useless_Things FROM [SQL Server]</title>
		<link>http://sqlfool.com/2010/05/delet-5_useless_things-from-sql-server/</link>
		<comments>http://sqlfool.com/2010/05/delet-5_useless_things-from-sql-server/#comments</comments>
		<pubDate>Fri, 14 May 2010 14:34:35 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Miscellaneous]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[chainblogging]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1328</guid>
		<description><![CDATA[It's been a while since I've been caught up in a round of chainblogging, the blogosphere's version of a Facebook meme. This time, Denis Gobo tagged me in a post started by Paul Randal. Paul asked us to list the "top-5 things in SQL Server we all wish would just be removed from the product [...]]]></description>
			<content:encoded><![CDATA[<p>It's <a href="http://sqlfool.com/2009/06/chainblogging-deserted-islands-have-wifi/" target="_blank">been a while</a> since I've been caught up in a round of chainblogging, the blogosphere's version of a Facebook meme.  This time, <a href="http://twitter.com/denisgobo" target="_blank">Denis Gobo</a> <a href="http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/sql-meme-tagged-5-things-sql-server-shou" target="_blank">tagged me in a post</a> started by <a href="http://www.twitter.com/paulrandal" target="_blank">Paul Randal</a>.  Paul asked us to list the "<a href="http://www.sqlskills.com/BLOGS/PAUL/post/What-5-things-should-SQL-Server-get-rid-of.aspx" target="_blank">top-5 things in SQL Server we all wish would just be removed from the product once and for all</a>."  I reviewed <a href="http://sqlblog.com/blogs/aaron_bertrand/archive/2010/05/11/tagged-5-things-sql-server-should-drop.aspx" target="_blank">other posts</a>, and the good and bad news is that they already listed several of the same things I would have.  The good news is I'm apparently not alone; the bad news is that means I need to come up with something original!  So while these wouldn't necessarily be the *first* 5 on my list, they'd still be on the list nevertheless:</p>
<p><strong>Default Autogrowth Options</strong><br />
Okay, so I lied.  I'm not completely original.  Yes, I know Paul Randal also commented on this one.  While I said I would try to come up with only original ones, this one just has to be repeated.  I've actually this option overlooked in production environments, resulting in thousands of VLF's.  It's just a terrible default, and it needs to be changed.</p>
<p><strong>Edit Top 200 Rows</strong><br />
This "feature" is just asking for trouble.  Any DBA who is managing a SQL Server database should understand how to actually write insert/update/delete statements.  Maybe leave the option available in SQL Express, but please remove it from SQL Server Standard &#038; Enterprise.</p>
<p><strong>Debug</strong><br />
There's nothing wrong with the Debug option, but I think it should be removed as a default option for the toolbar.  It's easily mistaken for "Execute," which I've seen more than one DBA do on occasion.  </p>
<p><del datetime="2010-06-04T19:55:56+00:00"><strong>PIVOT</strong><br />
I understand the need to pivot your data, but let's face it.  PIVOT is a clunky, expensive SQL operation.  Let's move the presentation tasks to the presentation layer (.NET), and reserve the database layer for what it does best. </del><br />
<em>Update: By popular demand, I have removed PIVOT from this list.  Who am I to argue with such fine folks?  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </em></p>
<p><strong>Cursors</strong><br />
Okay, okay, I know I can't actually get rid of this, BUT I think it gets abused way too much.  Set-based operations, anyone?</p>
<p>Alrighty, now it's my turn to tag!  I'm not sure if they've already been hit, but I'm tagging:</p>
<ul>
<li>Jorge Segarra (<a href="http://twitter.com/sqlchicken" target="_blank">Twitter</a> | <a href="http://sqlchicken.com/" target="_blank">Blog</a>)</li>
<li>Jack Corbett (<a href="http://twitter.com/unclebiguns" target="_blank">Twitter</a> | <a href="http://www.wiseman-wiseguy.blogspot.com/" target="_blank">Blog</a>)</li>
<li>David Levy (<a href="http://twitter.com/Dave_Levy" target="_blank">Twitter</a> | <a href="http://adventuresinsql.com/" target="_blank">Blog</a>)</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2010/05/delet-5_useless_things-from-sql-server/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Index Defrag Script, v4.0</title>
		<link>http://sqlfool.com/2010/04/index-defrag-script-v4-0/</link>
		<comments>http://sqlfool.com/2010/04/index-defrag-script-v4-0/#comments</comments>
		<pubDate>Thu, 22 Apr 2010 18:07:00 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[T-SQL Scripts]]></category>
		<category><![CDATA[defrag]]></category>
		<category><![CDATA[defragment]]></category>
		<category><![CDATA[fragmentation]]></category>
		<category><![CDATA[indexes]]></category>
		<category><![CDATA[maintenace]]></category>
		<category><![CDATA[partitioning]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[TSQL]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1316</guid>
		<description><![CDATA[In my blog post, "Index Defrag Script Updates - Beta Testers Needed", I stated "I'll hopefully have the new version online in just a few days." That was dated January 26th. I had every intention of following through with it, too, but something came up: My daughter, Chloe Lynn, was born on February 10th. She's [...]]]></description>
			<content:encoded><![CDATA[<p>In my blog post, "<a href="http://sqlfool.com/2010/01/index-defrag-script-updates-beta-testers-needed/" target="_blank">Index Defrag Script Updates - Beta Testers Needed</a>", I stated "I'll hopefully have the new version online in just a few days."  That was dated January 26th.  I had every intention of following through with it, too, but something came up:</p>
<p><img src="http://sqlfool.com/images/Chloe.jpg"></p>
<p>My daughter, Chloe Lynn, was born on February 10th.  She's a happy, healthy baby girl who consumes all of my free time and already has both her parents wrapped around her adorable little finger.  So while I apologize for the delay in posting the latest version, I hope you can understand and forgive me.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Alrighty, back to SQL stuff!  This version of the script has been significantly overhauled from previous versions.  Here's a full synopsis of the changes and enhancements:</p>
<p>- There's now a time limit option so you have more control over how long your defrags run. This time limit is checked *before* a defrag is begun, so it's still possible to have a defrag occur after the time limit is exceeded (i.e. a large index).</p>
<p>- I've added a static table for managing the index defrag scans. This way, you can start and stop the defrag process without the need to rescan. This is especially useful for VLDB's or any environment where you're unable to complete the defrags in one operation.</p>
<p>- Just in case you want to perform a rescan, even if there's still indexes left to defrag from your last rescan, there's a parameter to force it.</p>
<p>- There's now an option to sort by page count, range scan count, or fragmentation level. Range scan count is defaulted, as the indexes that have high amounts of range scans will benefit the most from having a defragged index. You can also specify whether you want to sort by ASC or DESC.</p>
<p>- There's now min and max parameters for page counts. This is useful for a) ignoring indexes with less than 1 extent (as recommended by Microsoft) and b) for scheduling index operations by size. For instance, you may want to defrag your small indexes during business hours but leave your big indexes for evening or weekend hours.</p>
<p>- There's now a parameterized option for sorting in TEMPDB. This may reduce execution time and will prevent unnecessary database file size inflation during defrags. NOTE: Make sure you have enough free space in TEMPDB prior to enabling this option.</p>
<p>- I moved the SQL statement output to display before execution so you can see what's currently executing.</p>
<p>- I've added a debug output of the parameters selected. I've added additional validation to the start of the script, so this will help show you if an invalid value was submitted and overwritten.</p>
<p>- I've added new columns to the log table to show what command is being executed and what error, if any, occurred when trying to execute.</p>
<p>- I've added try/catch logic to handle errors during execution; this way, a single error will not prevent the whole script from terminating.</p>
<p>- The script will now force a rebuild for indexes with allow_page_locks = off.</p>
<p>- For those who use partitioning, you can now exclude the right-most populated partition from the defrag operation. This won't be applicable for all partitioning schemes, but for sliding-window scenarios (one of the most common schemes), it'll reduce contention on the partition that's being actively written to.</p>
<p>- I've fixed a bug where tables with LOB indexes may have more than one record returned from sys.dm_db_index_physical_stats.</p>
<p>- For various reasons, I've removed the option to rebuild stats.  </p>
<p>Also, if you have a previous version of the script installed, this version will rename those tables, since there have been some changes made to them. </p>
<p><strong>FAQ:</strong></p>
<p>I often receive the same questions about this script, so allow me to answer them here:</p>
<p><em>"I keep running the script, but my index is still fragmented.  Why?"</em><br />
This is most likely a very small index.  Here's what <a href="http://msdn.microsoft.com/en-us/library/ms189858.aspx" target="_blank">Microsoft has to say</a>: </p>
<blockquote><p>"In general, fragmentation on small indexes is often not controllable. The pages of small indexes are stored on mixed extents. Mixed extents are shared by up to eight objects, so the fragmentation in a small index might not be reduced after reorganizing or rebuilding the index. For more information about mixed extents, see <a href="http://msdn.microsoft.com/en-us/library/ms190969.aspx" target="_blank">Understanding Pages and Extents</a>."  </p></blockquote>
<p><em>"What database should I create it in?" or "Can I create this in the MASTER database?"</em><br />
It's up to you where you create it.  You could technically create it in the MASTER database, but I recommend creating a utility database for your DBA administrative tasks.</p>
<p><em>"Can I run this againt a SharePoint database?"</em><br />
I've never tried personally, but I've been told it runs just fine.</p>
<p><em>"What are the minimum requirements to run this script?" or "Will this run on SQL Server 2000 instances?"</em><br />
You need to be on SQL Server 2005 SP2 or higher.</p>
<p>Without further ado, here's the script:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/* Scroll down to the see notes, disclaimers, and licensing information */</span>
&nbsp;
<span style="color: #0000FF;">DECLARE</span> @indexDefragLog_rename      <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>
    , @indexDefragExclusion_rename  <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>
    , @indexDefragStatus_rename     <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">SELECT</span> @indexDefragLog_rename       <span style="color: #808080;">=</span> <span style="color: #FF0000;">'dba_indexDefragLog_obsolete_'</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CONVERT</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span>, <span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>, <span style="color: #000;">112</span><span style="color: #808080;">&#41;</span>
    , @indexDefragExclusion_rename  <span style="color: #808080;">=</span> <span style="color: #FF0000;">'dba_indexDefragExclusion_obsolete_'</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CONVERT</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span>, <span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>, <span style="color: #000;">112</span><span style="color: #808080;">&#41;</span>
    , @indexDefragStatus_rename     <span style="color: #808080;">=</span> <span style="color: #FF0000;">'dba_indexDefragStatus_obsolete_'</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CONVERT</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span>, <span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>, <span style="color: #000;">112</span><span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">IF</span> Exists<span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">&#91;</span><span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#93;</span> <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">tables</span> <span style="color: #0000FF;">WHERE</span> <span style="color: #808080;">&#91;</span>name<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'dba_indexDefragLog'</span><span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">SP_RENAME</span> dba_indexDefragLog, @indexDefragLog_rename;
&nbsp;
<span style="color: #0000FF;">IF</span> Exists<span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">&#91;</span><span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#93;</span> <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">tables</span> <span style="color: #0000FF;">WHERE</span> <span style="color: #808080;">&#91;</span>name<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'dba_indexDefragExclusion'</span><span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">SP_RENAME</span> dba_indexDefragExclusion, @indexDefragExclusion_rename;
&nbsp;
<span style="color: #0000FF;">IF</span> Exists<span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">&#91;</span><span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#93;</span> <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">tables</span> <span style="color: #0000FF;">WHERE</span> <span style="color: #808080;">&#91;</span>name<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'dba_indexDefragStatus'</span><span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">SP_RENAME</span> dba_indexDefragStatus, @indexDefragStatus_rename;
Go
&nbsp;
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">dba_indexDefragLog</span>
<span style="color: #808080;">&#40;</span>
      indexDefrag_id    <span style="color: #0000FF;">INT</span> <span style="color: #0000FF;">IDENTITY</span><span style="color: #808080;">&#40;</span><span style="color: #000;">1</span>,<span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>   Not Null
    , databaseID        <span style="color: #0000FF;">INT</span>                 Not Null
    , databaseName      <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>       Not Null
    , objectID          <span style="color: #0000FF;">INT</span>                 Not Null
    , objectName        <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>       Not Null
    , indexID           <span style="color: #0000FF;">INT</span>                 Not Null
    , indexName         <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>       Not Null
    , partitionNumber   <span style="color: #0000FF;">SMALLINT</span>            Not Null
    , fragmentation     <span style="color: #0000FF;">FLOAT</span>               Not Null
    , page_count        <span style="color: #0000FF;">INT</span>                 Not Null
    , dateTimeStart     <span style="color: #0000FF;">DATETIME</span>            Not Null
    , dateTimeEnd       <span style="color: #0000FF;">DATETIME</span>            Null
    , durationSeconds   <span style="color: #0000FF;">INT</span>                 Null
    , sqlStatement      <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>       Null
    , errorMessage      <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">1000</span><span style="color: #808080;">&#41;</span>       Null
&nbsp;
    <span style="color: #0000FF;">CONSTRAINT</span> PK_indexDefragLog_v40
        <span style="color: #0000FF;">PRIMARY</span> <span style="color: #0000FF;">KEY</span> <span style="color: #0000FF;">CLUSTERED</span> <span style="color: #808080;">&#40;</span>indexDefrag_id<span style="color: #808080;">&#41;</span>
<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">PRINT</span> <span style="color: #FF0000;">'dba_indexDefragLog Table Created'</span>;
&nbsp;
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">dba_indexDefragExclusion</span>
<span style="color: #808080;">&#40;</span>
      databaseID        <span style="color: #0000FF;">INT</span>                 Not Null
    , databaseName      <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>       Not Null
    , objectID          <span style="color: #0000FF;">INT</span>                 Not Null
    , objectName        <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>       Not Null
    , indexID           <span style="color: #0000FF;">INT</span>                 Not Null
    , indexName         <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>       Not Null
    , exclusionMask     <span style="color: #0000FF;">INT</span>                 Not Null
        <span style="color: #008080;">/* 1=Sunday, 2=Monday, 4=Tuesday, 8=Wednesday, 16=Thursday, 32=Friday, 64=Saturday */</span>
&nbsp;
    <span style="color: #0000FF;">CONSTRAINT</span> PK_indexDefragExclusion_v40
        <span style="color: #0000FF;">PRIMARY</span> <span style="color: #0000FF;">KEY</span> <span style="color: #0000FF;">CLUSTERED</span> <span style="color: #808080;">&#40;</span>databaseID, objectID, indexID<span style="color: #808080;">&#41;</span>
<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">PRINT</span> <span style="color: #FF0000;">'dba_indexDefragExclusion Table Created'</span>;
&nbsp;
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">dba_indexDefragStatus</span>
<span style="color: #808080;">&#40;</span>
      databaseID        <span style="color: #0000FF;">INT</span>
    , databaseName      <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>
    , objectID          <span style="color: #0000FF;">INT</span>
    , indexID           <span style="color: #0000FF;">INT</span>
    , partitionNumber   <span style="color: #0000FF;">SMALLINT</span>
    , fragmentation     <span style="color: #0000FF;">FLOAT</span>
    , page_count        <span style="color: #0000FF;">INT</span>
    , range_scan_count  <span style="color: #0000FF;">BIGINT</span>
    , schemaName        <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>   Null
    , objectName        <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>   Null
    , indexName         <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>   Null
    , scanDate          <span style="color: #0000FF;">DATETIME</span>        
    , defragDate        <span style="color: #0000FF;">DATETIME</span>        Null
    , printStatus       <span style="color: #0000FF;">BIT</span>             <span style="color: #0000FF;">DEFAULT</span><span style="color: #808080;">&#40;</span><span style="color: #000;">0</span><span style="color: #808080;">&#41;</span>
    , exclusionMask     <span style="color: #0000FF;">INT</span>             <span style="color: #0000FF;">DEFAULT</span><span style="color: #808080;">&#40;</span><span style="color: #000;">0</span><span style="color: #808080;">&#41;</span>
&nbsp;
    <span style="color: #0000FF;">CONSTRAINT</span> PK_indexDefragStatus_v40
        <span style="color: #0000FF;">PRIMARY</span> <span style="color: #0000FF;">KEY</span> <span style="color: #0000FF;">CLUSTERED</span><span style="color: #808080;">&#40;</span>databaseID, objectID, indexID, partitionNumber<span style="color: #808080;">&#41;</span>
<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">PRINT</span> <span style="color: #FF0000;">'dba_indexDefragStatus Table Created'</span>;
&nbsp;
<span style="color: #0000FF;">IF</span> <span style="color: #FF00FF;">OBJECTPROPERTY</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'dbo.dba_indexDefrag_sp'</span><span style="color: #808080;">&#41;</span>, N<span style="color: #FF0000;">'IsProcedure'</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
<span style="color: #0000FF;">BEGIN</span>
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">PROCEDURE</span> dbo.<span style="color: #202020;">dba_indexDefrag_sp</span>;
    <span style="color: #0000FF;">PRINT</span> <span style="color: #FF0000;">'Procedure dba_indexDefrag_sp dropped'</span>;
<span style="color: #0000FF;">END</span>;
Go
&nbsp;
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">PROCEDURE</span> dbo.<span style="color: #202020;">dba_indexDefrag_sp</span>
&nbsp;
    <span style="color: #008080;">/* Declare Parameters */</span>
      @minFragmentation     <span style="color: #0000FF;">FLOAT</span>           <span style="color: #808080;">=</span> <span style="color: #000;">10.0</span>  
        <span style="color: #008080;">/* in percent, will not defrag if fragmentation less than specified */</span>
    , @rebuildThreshold     <span style="color: #0000FF;">FLOAT</span>           <span style="color: #808080;">=</span> <span style="color: #000;">30.0</span>  
        <span style="color: #008080;">/* in percent, greater than @rebuildThreshold will result in rebuild instead of reorg */</span>
    , @executeSQL           <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">1</span>     
        <span style="color: #008080;">/* 1 = execute; 0 = print command only */</span>
    , @defragOrderColumn    <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">20</span><span style="color: #808080;">&#41;</span>    <span style="color: #808080;">=</span> <span style="color: #FF0000;">'range_scan_count'</span>
        <span style="color: #008080;">/* Valid options are: range_scan_count, fragmentation, page_count */</span>
    , @defragSortOrder      <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4</span><span style="color: #808080;">&#41;</span>     <span style="color: #808080;">=</span> <span style="color: #FF0000;">'DESC'</span>
        <span style="color: #008080;">/* Valid options are: ASC, DESC */</span>
    , @timeLimit            <span style="color: #0000FF;">INT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">720</span> <span style="color: #008080;">/* defaulted to 12 hours */</span>
        <span style="color: #008080;">/* Optional time limitation; expressed in minutes */</span>
    , @<span style="color: #0000FF;">DATABASE</span>             <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>    <span style="color: #808080;">=</span> Null
        <span style="color: #008080;">/* Option to specify a database name; null will return all */</span>
    , @tableName            <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>   <span style="color: #808080;">=</span> Null  <span style="color: #008080;">-- databaseName.schema.tableName</span>
        <span style="color: #008080;">/* Option to specify a table name; null will return all */</span>
    , @forceRescan          <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
        <span style="color: #008080;">/* Whether or not to force a rescan of indexes; 1 = force, 0 = use existing scan, if available */</span>
    , @scanMode             <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span>     <span style="color: #808080;">=</span> N<span style="color: #FF0000;">'LIMITED'</span>
        <span style="color: #008080;">/* Options are LIMITED, SAMPLED, and DETAILED */</span>
    , @minPageCount         <span style="color: #0000FF;">INT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">8</span> 
        <span style="color: #008080;">/*  MS recommends &gt; 1 extent (8 pages) */</span>
    , @maxPageCount         <span style="color: #0000FF;">INT</span>             <span style="color: #808080;">=</span> Null
        <span style="color: #008080;">/* NULL = no limit */</span>
    , @excludeMaxPartition  <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
        <span style="color: #008080;">/* 1 = exclude right-most populated partition; 0 = do not exclude; see notes for caveats */</span>
    , @onlineRebuild        <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">1</span>     
        <span style="color: #008080;">/* 1 = online rebuild; 0 = offline rebuild; only in Enterprise */</span>
    , @sortInTempDB         <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
        <span style="color: #008080;">/* 1 = perform sort operation in TempDB; 0 = perform sort operation in the index's database */</span>
    , @maxDopRestriction    <span style="color: #0000FF;">TINYINT</span>         <span style="color: #808080;">=</span> Null
        <span style="color: #008080;">/* Option to restrict the number of processors for the operation; only in Enterprise */</span>
    , @printCommands        <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">0</span>     
        <span style="color: #008080;">/* 1 = print commands; 0 = do not print commands */</span>
    , @printFragmentation   <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
        <span style="color: #008080;">/* 1 = print fragmentation prior to defrag; 
           0 = do not print */</span>
    , @defragDelay          <span style="color: #0000FF;">CHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">8</span><span style="color: #808080;">&#41;</span>         <span style="color: #808080;">=</span> <span style="color: #FF0000;">'00:00:05'</span>
        <span style="color: #008080;">/* time to wait between defrag commands */</span>
    , @debugMode            <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
        <span style="color: #008080;">/* display some useful comments to help determine if/where issues occur */</span>
&nbsp;
<span style="color: #0000FF;">AS</span>
<span style="color: #008080;">/*********************************************************************************
    Name:       dba_indexDefrag_sp
&nbsp;
    Author:     Michelle Ufford, http://sqlfool.com
&nbsp;
    Purpose:    Defrags one or more indexes for one or more databases
&nbsp;
    Notes:
&nbsp;
    CAUTION: TRANSACTION LOG SIZE SHOULD BE MONITORED CLOSELY WHEN DEFRAGMENTING.
             DO NOT RUN UNATTENDED ON LARGE DATABASES DURING BUSINESS HOURS.
&nbsp;
      @minFragmentation     defaulted to 10%, will not defrag if fragmentation 
                            is less than that
&nbsp;
      @rebuildThreshold     defaulted to 30% as recommended by Microsoft in BOL;
                            greater than 30% will result in rebuild instead
&nbsp;
      @executeSQL           1 = execute the SQL generated by this proc; 
                            0 = print command only
&nbsp;
      @defragOrderColumn    Defines how to prioritize the order of defrags.  Only
                            used if @executeSQL = 1.  
                            Valid options are: 
                            range_scan_count = count of range and table scans on the
                                               index; in general, this is what benefits 
                                               the most from defragmentation
                            fragmentation    = amount of fragmentation in the index;
                                               the higher the number, the worse it is
                            page_count       = number of pages in the index; affects
                                               how long it takes to defrag an index
&nbsp;
      @defragSortOrder      The sort order of the ORDER BY clause.
                            Valid options are ASC (ascending) or DESC (descending).
&nbsp;
      @timeLimit            Optional, limits how much time can be spent performing 
                            index defrags; expressed in minutes.
&nbsp;
                            NOTE: The time limit is checked BEFORE an index defrag
                                  is begun, thus a long index defrag can exceed the
                                  time limitation.
&nbsp;
      @database             Optional, specify specific database name to defrag;
                            If not specified, all non-system databases will
                            be defragged.
&nbsp;
      @tableName            Specify if you only want to defrag indexes for a 
                            specific table, format = databaseName.schema.tableName;
                            if not specified, all tables will be defragged.
&nbsp;
      @forceRescan          Whether or not to force a rescan of indexes.  If set
                            to 0, a rescan will not occur until all indexes have
                            been defragged.  This can span multiple executions.
                            1 = force a rescan
                            0 = use previous scan, if there are indexes left to defrag
&nbsp;
      @scanMode             Specifies which scan mode to use to determine
                            fragmentation levels.  Options are:
                            LIMITED - scans the parent level; quickest mode,
                                      recommended for most cases.
                            SAMPLED - samples 1% of all data pages; if less than
                                      10k pages, performs a DETAILED scan.
                            DETAILED - scans all data pages.  Use great care with
                                       this mode, as it can cause performance issues.
&nbsp;
      @minPageCount         Specifies how many pages must exist in an index in order 
                            to be considered for a defrag.  Defaulted to 8 pages, as 
                            Microsoft recommends only defragging indexes with more 
                            than 1 extent (8 pages).  
&nbsp;
                            NOTE: The @minPageCount will restrict the indexes that
                            are stored in dba_indexDefragStatus table.
&nbsp;
      @maxPageCount         Specifies the maximum number of pages that can exist in 
                            an index and still be considered for a defrag.  Useful
                            for scheduling small indexes during business hours and
                            large indexes for non-business hours.
&nbsp;
                            NOTE: The @maxPageCount will restrict the indexes that
                            are defragged during the current operation; it will not
                            prevent indexes from being stored in the 
                            dba_indexDefragStatus table.  This way, a single scan
                            can support multiple page count thresholds.
&nbsp;
      @excludeMaxPartition  If an index is partitioned, this option specifies whether
                            to exclude the right-most populated partition.  Typically,
                            this is the partition that is currently being written to in
                            a sliding-window scenario.  Enabling this feature may reduce
                            contention.  This may not be applicable in other types of 
                            partitioning scenarios.  Non-partitioned indexes are 
                            unaffected by this option.
                            1 = exclude right-most populated partition
                            0 = do not exclude
&nbsp;
      @onlineRebuild        1 = online rebuild; 
                            0 = offline rebuild
&nbsp;
      @sortInTempDB         Specifies whether to defrag the index in TEMPDB or in the
                            database the index belongs to.  Enabling this option may
                            result in faster defrags and prevent database file size 
                            inflation.
                            1 = perform sort operation in TempDB
                            0 = perform sort operation in the index's database 
&nbsp;
      @maxDopRestriction    Option to specify a processor limit for index rebuilds
&nbsp;
      @printCommands        1 = print commands to screen; 
                            0 = do not print commands
&nbsp;
      @printFragmentation   1 = print fragmentation to screen;
                            0 = do not print fragmentation
&nbsp;
      @defragDelay          Time to wait between defrag commands; gives the
                            server a little time to catch up 
&nbsp;
      @debugMode            1 = display debug comments; helps with troubleshooting
                            0 = do not display debug comments
&nbsp;
    Called by:  SQL Agent Job or DBA
&nbsp;
    ----------------------------------------------------------------------------
    DISCLAIMER: 
    This code and information are provided &quot;AS IS&quot; without warranty of any kind,
    either expressed or implied, including but not limited to the implied 
    warranties or merchantability and/or fitness for a particular purpose.
    ----------------------------------------------------------------------------
    LICENSE: 
    This index defrag script is free to download and use for personal, educational, 
    and internal corporate purposes, provided that this header is preserved. 
    Redistribution or sale of this index defrag script, in whole or in part, is 
    prohibited without the author's express written consent.
    ----------------------------------------------------------------------------
    Date        Initials	Version Description
    ----------------------------------------------------------------------------
    2007-12-18  MFU         1.0     Initial Release
    2008-10-17  MFU         1.1     Added @defragDelay, CIX_temp_indexDefragList
    2008-11-17  MFU         1.2     Added page_count to log table
                                    , added @printFragmentation option
    2009-03-17  MFU         2.0     Provided support for centralized execution
                                    , consolidated Enterprise &amp; Standard versions
                                    , added @debugMode, @maxDopRestriction
                                    , modified LOB and partition logic  
    2009-06-18  MFU         3.0     Fixed bug in LOB logic, added @scanMode option
                                    , added support for stat rebuilds (@rebuildStats)
                                    , support model and msdb defrag
                                    , added columns to the dba_indexDefragLog table
                                    , modified logging to show &quot;in progress&quot; defrags
                                    , added defrag exclusion list (scheduling)
    2009-08-28  MFU         3.1     Fixed read_only bug for database lists
    2010-04-20  MFU         4.0     Added time limit option
                                    , added static table with rescan logic
                                    , added parameters for page count &amp; SORT_IN_TEMPDB
                                    , added try/catch logic and additional debug options
                                    , added options for defrag prioritization
                                    , fixed bug for indexes with allow_page_lock = off
                                    , added option to exclude right-most partition
                                    , removed @rebuildStats option
                                    , refer to http://sqlfool.com for full release notes
*********************************************************************************
    Example of how to call this script:
&nbsp;
        Exec dbo.dba_indexDefrag_sp
              @executeSQL           = 1
            , @printCommands        = 1
            , @debugMode            = 1
            , @printFragmentation   = 1
            , @forceRescan          = 1
            , @maxDopRestriction    = 1
            , @minPageCount         = 8
            , @maxPageCount         = Null
            , @minFragmentation     = 1
            , @rebuildThreshold     = 30
            , @defragDelay          = '00:00:05'
            , @defragOrderColumn    = 'page_count'
            , @defragSortOrder      = 'DESC'
            , @excludeMaxPartition  = 1
            , @timeLimit            = Null;
*********************************************************************************/</span>																
<span style="color: #0000FF;">SET</span> <span style="color: #0000FF;">NOCOUNT</span> <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">SET</span> XACT_Abort <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">SET</span> Quoted_Identifier <span style="color: #0000FF;">ON</span>;
&nbsp;
<span style="color: #0000FF;">BEGIN</span>
&nbsp;
    <span style="color: #0000FF;">BEGIN</span> Try
&nbsp;
        <span style="color: #008080;">/* Just a little validation... */</span>
        <span style="color: #0000FF;">IF</span> @minFragmentation <span style="color: #0000FF;">IS</span> Null 
            Or @minFragmentation Not Between <span style="color: #000;">0.00</span> And <span style="color: #000;">100.0</span>
                <span style="color: #0000FF;">SET</span> @minFragmentation <span style="color: #808080;">=</span> <span style="color: #000;">10.0</span>;
&nbsp;
        <span style="color: #0000FF;">IF</span> @rebuildThreshold <span style="color: #0000FF;">IS</span> Null
            Or @rebuildThreshold Not Between <span style="color: #000;">0.00</span> And <span style="color: #000;">100.0</span>
                <span style="color: #0000FF;">SET</span> @rebuildThreshold <span style="color: #808080;">=</span> <span style="color: #000;">30.0</span>;
&nbsp;
        <span style="color: #0000FF;">IF</span> @defragDelay Not Like <span style="color: #FF0000;">'00:[0-5][0-9]:[0-5][0-9]'</span>
            <span style="color: #0000FF;">SET</span> @defragDelay <span style="color: #808080;">=</span> <span style="color: #FF0000;">'00:00:05'</span>;
&nbsp;
        <span style="color: #0000FF;">IF</span> @defragOrderColumn <span style="color: #0000FF;">IS</span> Null
            Or @defragOrderColumn Not In <span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'range_scan_count'</span>, <span style="color: #FF0000;">'fragmentation'</span>, <span style="color: #FF0000;">'page_count'</span><span style="color: #808080;">&#41;</span>
                <span style="color: #0000FF;">SET</span> @defragOrderColumn <span style="color: #808080;">=</span> <span style="color: #FF0000;">'range_scan_count'</span>;
&nbsp;
        <span style="color: #0000FF;">IF</span> @defragSortOrder <span style="color: #0000FF;">IS</span> Null
            Or @defragSortOrder Not In <span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'ASC'</span>, <span style="color: #FF0000;">'DESC'</span><span style="color: #808080;">&#41;</span>
                <span style="color: #0000FF;">SET</span> @defragSortOrder <span style="color: #808080;">=</span> <span style="color: #FF0000;">'DESC'</span>;
&nbsp;
        <span style="color: #0000FF;">IF</span> @scanMode Not In <span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'LIMITED'</span>, <span style="color: #FF0000;">'SAMPLED'</span>, <span style="color: #FF0000;">'DETAILED'</span><span style="color: #808080;">&#41;</span>
            <span style="color: #0000FF;">SET</span> @scanMode <span style="color: #808080;">=</span> <span style="color: #FF0000;">'LIMITED'</span>;
&nbsp;
        <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #0000FF;">IS</span> Null
            <span style="color: #0000FF;">SET</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">0</span>;
&nbsp;
        <span style="color: #0000FF;">IF</span> @forceRescan <span style="color: #0000FF;">IS</span> Null
            <span style="color: #0000FF;">SET</span> @forceRescan <span style="color: #808080;">=</span> <span style="color: #000;">0</span>;
&nbsp;
        <span style="color: #0000FF;">IF</span> @sortInTempDB <span style="color: #0000FF;">IS</span> Null
            <span style="color: #0000FF;">SET</span> @sortInTempDB <span style="color: #808080;">=</span> <span style="color: #000;">1</span>;
&nbsp;
&nbsp;
        <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Undusting the cogs and starting up...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
        <span style="color: #008080;">/* Declare our variables */</span>
        <span style="color: #0000FF;">DECLARE</span>   @objectID                 <span style="color: #0000FF;">INT</span>
                , @databaseID               <span style="color: #0000FF;">INT</span>
                , @databaseName             <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>
                , @indexID                  <span style="color: #0000FF;">INT</span>
                , @partitionCount           <span style="color: #0000FF;">BIGINT</span>
                , @schemaName               <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>
                , @objectName               <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>
                , @indexName                <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>
                , @partitionNumber          <span style="color: #0000FF;">SMALLINT</span>
                , @fragmentation            <span style="color: #0000FF;">FLOAT</span>
                , @pageCount                <span style="color: #0000FF;">INT</span>
                , @sqlCommand               <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>
                , @rebuildCommand           <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">200</span><span style="color: #808080;">&#41;</span>
                , @dateTimeStart            <span style="color: #0000FF;">DATETIME</span>
                , @dateTimeEnd              <span style="color: #0000FF;">DATETIME</span>
                , @containsLOB              <span style="color: #0000FF;">BIT</span>
                , @editionCheck             <span style="color: #0000FF;">BIT</span>
                , @debugMessage             <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>
                , @updateSQL                <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>
                , @partitionSQL             <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>
                , @partitionSQL_Param       <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">1000</span><span style="color: #808080;">&#41;</span>
                , @LOB_SQL                  <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>
                , @LOB_SQL_Param            <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">1000</span><span style="color: #808080;">&#41;</span>
                , @indexDefrag_id           <span style="color: #0000FF;">INT</span>
                , @startDateTime            <span style="color: #0000FF;">DATETIME</span>
                , @endDateTime              <span style="color: #0000FF;">DATETIME</span>
                , @getIndexSQL              <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>
                , @getIndexSQL_Param        <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>
                , @allowPageLockSQL         <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>
                , @allowPageLockSQL_Param   <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>
                , @allowPageLocks           <span style="color: #0000FF;">INT</span>
                , @excludeMaxPartitionSQL   <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>;
&nbsp;
        <span style="color: #008080;">/* Initialize our variables */</span>
        <span style="color: #0000FF;">SELECT</span> @startDateTime <span style="color: #808080;">=</span> <span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>
            , @endDateTime <span style="color: #808080;">=</span> <span style="color: #FF00FF;">DATEADD</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">MINUTE</span>, @timeLimit, <span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>;
&nbsp;
        <span style="color: #008080;">/* Create our temporary tables */</span>
        <span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> #databaseList
        <span style="color: #808080;">&#40;</span>
              databaseID        <span style="color: #0000FF;">INT</span>
            , databaseName      <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>
            , scanStatus        <span style="color: #0000FF;">BIT</span>
        <span style="color: #808080;">&#41;</span>;
&nbsp;
        <span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> #processor 
        <span style="color: #808080;">&#40;</span>
              <span style="color: #808080;">&#91;</span><span style="color: #0000FF;">INDEX</span><span style="color: #808080;">&#93;</span>           <span style="color: #0000FF;">INT</span>
            , Name              <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>
            , Internal_Value    <span style="color: #0000FF;">INT</span>
            , Character_Value   <span style="color: #0000FF;">INT</span>
        <span style="color: #808080;">&#41;</span>;
&nbsp;
        <span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> #maxPartitionList
        <span style="color: #808080;">&#40;</span>
              databaseID        <span style="color: #0000FF;">INT</span>
            , objectID          <span style="color: #0000FF;">INT</span>
            , indexID           <span style="color: #0000FF;">INT</span>
            , maxPartition      <span style="color: #0000FF;">INT</span>
        <span style="color: #808080;">&#41;</span>;
&nbsp;
        <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Beginning validation...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
        <span style="color: #008080;">/* Make sure we're not exceeding the number of processors we have available */</span>
        <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> #processor
        <span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">XP_MSVER</span> <span style="color: #FF0000;">'ProcessorCount'</span>;
&nbsp;
        <span style="color: #0000FF;">IF</span> @maxDopRestriction <span style="color: #0000FF;">IS</span> Not Null And @maxDopRestriction <span style="color: #808080;">&gt;</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> Internal_Value <span style="color: #0000FF;">FROM</span> #processor<span style="color: #808080;">&#41;</span>
            <span style="color: #0000FF;">SELECT</span> @maxDopRestriction <span style="color: #808080;">=</span> Internal_Value
            <span style="color: #0000FF;">FROM</span> #processor;
&nbsp;
        <span style="color: #008080;">/* Check our server version; 1804890536 = Enterprise, 610778273 = Enterprise Evaluation, -2117995310 = Developer */</span>
        <span style="color: #0000FF;">IF</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #FF00FF;">SERVERPROPERTY</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'EditionID'</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> In <span style="color: #808080;">&#40;</span><span style="color: #000;">1804890536</span>, <span style="color: #000;">610778273</span>, <span style="color: #808080;">-</span><span style="color: #000;">2117995310</span><span style="color: #808080;">&#41;</span> 
            <span style="color: #0000FF;">SET</span> @editionCheck <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #008080;">-- supports online rebuilds</span>
        <span style="color: #0000FF;">ELSE</span>
            <span style="color: #0000FF;">SET</span> @editionCheck <span style="color: #808080;">=</span> <span style="color: #000;">0</span>; <span style="color: #008080;">-- does not support online rebuilds</span>
&nbsp;
        <span style="color: #008080;">/* Output the parameters we're working with */</span>
        <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> 
        <span style="color: #0000FF;">BEGIN</span>
&nbsp;
            <span style="color: #0000FF;">SELECT</span> @debugMessage <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Your selected parameters are... 
            Defrag indexes with fragmentation greater than '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@minFragmentation <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">';
            Rebuild indexes with fragmentation greater than '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@rebuildThreshold <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">';
            You'</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> @executeSQL <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">' DO'</span> <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">' DO NOT'</span> <span style="color: #0000FF;">END</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">' want the commands to be executed automatically; 
            You want to defrag indexes in '</span> <span style="color: #808080;">+</span> @defragSortOrder <span style="color: #808080;">+</span> <span style="color: #FF0000;">' order of the '</span> <span style="color: #808080;">+</span> <span style="color: #FF00FF;">UPPER</span><span style="color: #808080;">&#40;</span>@defragOrderColumn<span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">' value;
            You have'</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> @timeLimit <span style="color: #0000FF;">IS</span> Null <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">' not specified a time limit;'</span> <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">' specified a time limit of '</span> 
                <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@timeLimit <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">END</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">' minutes;
            '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> @<span style="color: #0000FF;">DATABASE</span> <span style="color: #0000FF;">IS</span> Null <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">'ALL databases'</span> <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">'The '</span> <span style="color: #808080;">+</span> @<span style="color: #0000FF;">DATABASE</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">' database'</span> <span style="color: #0000FF;">END</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">' will be defragged;
            '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> @tableName <span style="color: #0000FF;">IS</span> Null <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">'ALL tables'</span> <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">'The '</span> <span style="color: #808080;">+</span> @tableName <span style="color: #808080;">+</span> <span style="color: #FF0000;">' table'</span> <span style="color: #0000FF;">END</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">' will be defragged;
            We'</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> Exists<span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">TOP</span> <span style="color: #000;">1</span> <span style="color: #808080;">*</span> <span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">dba_indexDefragStatus</span> <span style="color: #0000FF;">WHERE</span> defragDate <span style="color: #0000FF;">IS</span> Null<span style="color: #808080;">&#41;</span>
                And @forceRescan <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">' WILL NOT'</span> <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">' WILL'</span> <span style="color: #0000FF;">END</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">' be rescanning indexes;
            The scan will be performed in '</span> <span style="color: #808080;">+</span> @scanMode <span style="color: #808080;">+</span> <span style="color: #FF0000;">' mode;
            You want to limit defrags to indexes with'</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> @maxPageCount <span style="color: #0000FF;">IS</span> Null <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">' more than '</span> 
                <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@minPageCount <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">ELSE</span>
                <span style="color: #FF0000;">' between '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@minPageCount <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>
                <span style="color: #808080;">+</span> <span style="color: #FF0000;">' and '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@maxPageCount <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">END</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">' pages;
            Indexes will be defragged'</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> @editionCheck <span style="color: #808080;">=</span> <span style="color: #000;">0</span> Or @onlineRebuild <span style="color: #808080;">=</span> <span style="color: #000;">0</span> <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">' OFFLINE;'</span> <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">' ONLINE;'</span> <span style="color: #0000FF;">END</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">'
            Indexes will be sorted in'</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> @sortInTempDB <span style="color: #808080;">=</span> <span style="color: #000;">0</span> <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">' the DATABASE'</span> <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">' TEMPDB;'</span> <span style="color: #0000FF;">END</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">'
            Defrag operations will utilize '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> @editionCheck <span style="color: #808080;">=</span> <span style="color: #000;">0</span> Or @maxDopRestriction <span style="color: #0000FF;">IS</span> Null 
                <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">'system defaults for processors;'</span> 
                <span style="color: #0000FF;">ELSE</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@maxDopRestriction <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">2</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">' processors;'</span> <span style="color: #0000FF;">END</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">'
            You'</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> @printCommands <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">' DO'</span> <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">' DO NOT'</span> <span style="color: #0000FF;">END</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">' want to print the ALTER INDEX commands; 
            You'</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> @printFragmentation <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">' DO'</span> <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">' DO NOT'</span> <span style="color: #0000FF;">END</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">' want to output fragmentation levels; 
            You want to wait '</span> <span style="color: #808080;">+</span> @defragDelay <span style="color: #808080;">+</span> <span style="color: #FF0000;">' (hh:mm:ss) between defragging indexes;
            You want to run in'</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">' DEBUG'</span> <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">' SILENT'</span> <span style="color: #0000FF;">END</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">' mode.'</span>;
&nbsp;
            <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span>@debugMessage, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
        <span style="color: #0000FF;">END</span>;
&nbsp;
        <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Grabbing a list of our databases...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
        <span style="color: #008080;">/* Retrieve the list of databases to investigate */</span>
        <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> #databaseList
        <span style="color: #0000FF;">SELECT</span> database_id
            , name
            , <span style="color: #000;">0</span> <span style="color: #008080;">-- not scanned yet for fragmentation</span>
        <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">databases</span>
        <span style="color: #0000FF;">WHERE</span> name <span style="color: #808080;">=</span> IsNull<span style="color: #808080;">&#40;</span>@<span style="color: #0000FF;">DATABASE</span>, name<span style="color: #808080;">&#41;</span>
            And <span style="color: #808080;">&#91;</span>name<span style="color: #808080;">&#93;</span> Not In <span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'master'</span>, <span style="color: #FF0000;">'tempdb'</span><span style="color: #808080;">&#41;</span><span style="color: #008080;">-- exclude system databases</span>
            And <span style="color: #808080;">&#91;</span><span style="color: #0000FF;">STATE</span><span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> <span style="color: #000;">0</span> <span style="color: #008080;">-- state must be ONLINE</span>
            And is_read_only <span style="color: #808080;">=</span> <span style="color: #000;">0</span>;  <span style="color: #008080;">-- cannot be read_only</span>
&nbsp;
        <span style="color: #008080;">/* Check to see if we have indexes in need of defrag; otherwise, re-scan the database(s) */</span>
        <span style="color: #0000FF;">IF</span> Not Exists<span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">TOP</span> <span style="color: #000;">1</span> <span style="color: #808080;">*</span> <span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">dba_indexDefragStatus</span> <span style="color: #0000FF;">WHERE</span> defragDate <span style="color: #0000FF;">IS</span> Null<span style="color: #808080;">&#41;</span>
            Or @forceRescan <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
        <span style="color: #0000FF;">BEGIN</span>
&nbsp;
            <span style="color: #008080;">/* Truncate our list of indexes to prepare for a new scan */</span>
            <span style="color: #0000FF;">TRUNCATE</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">dba_indexDefragStatus</span>;
&nbsp;
            <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Looping through our list of databases and checking for fragmentation...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
            <span style="color: #008080;">/* Loop through our list of databases */</span>
            <span style="color: #0000FF;">WHILE</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #FF00FF;">COUNT</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">*</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">FROM</span> #databaseList <span style="color: #0000FF;">WHERE</span> scanStatus <span style="color: #808080;">=</span> <span style="color: #000;">0</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span>
            <span style="color: #0000FF;">BEGIN</span>
&nbsp;
                <span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">TOP</span> <span style="color: #000;">1</span> @databaseID <span style="color: #808080;">=</span> databaseID
                <span style="color: #0000FF;">FROM</span> #databaseList
                <span style="color: #0000FF;">WHERE</span> scanStatus <span style="color: #808080;">=</span> <span style="color: #000;">0</span>;
&nbsp;
                <span style="color: #0000FF;">SELECT</span> @debugMessage <span style="color: #808080;">=</span> <span style="color: #FF0000;">'  working on '</span> <span style="color: #808080;">+</span> <span style="color: #FF00FF;">DB_NAME</span><span style="color: #808080;">&#40;</span>@databaseID<span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">'...'</span>;
&nbsp;
                <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
                    <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span>@debugMessage, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
               <span style="color: #008080;">/* Determine which indexes to defrag using our user-defined parameters */</span>
                <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> dbo.<span style="color: #202020;">dba_indexDefragStatus</span>
                <span style="color: #808080;">&#40;</span>
                      databaseID
                    , databaseName
                    , objectID
                    , indexID
                    , partitionNumber
                    , fragmentation
                    , page_count
                    , range_scan_count
                    , scanDate
                <span style="color: #808080;">&#41;</span>
                <span style="color: #0000FF;">SELECT</span>
                      ps.<span style="color: #202020;">database_id</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'databaseID'</span>
                    , <span style="color: #FF00FF;">QUOTENAME</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">DB_NAME</span><span style="color: #808080;">&#40;</span>ps.<span style="color: #202020;">database_id</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'databaseName'</span>
                    , ps.<span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'objectID'</span>
                    , ps.<span style="color: #202020;">index_id</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'indexID'</span>
                    , ps.<span style="color: #202020;">partition_number</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'partitionNumber'</span>
                    , <span style="color: #FF00FF;">SUM</span><span style="color: #808080;">&#40;</span>ps.<span style="color: #202020;">avg_fragmentation_in_percent</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'fragmentation'</span>
                    , <span style="color: #FF00FF;">SUM</span><span style="color: #808080;">&#40;</span>ps.<span style="color: #202020;">page_count</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'page_count'</span>
                    , os.<span style="color: #202020;">range_scan_count</span>
                    , <span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'scanDate'</span>
                <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">dm_db_index_physical_stats</span><span style="color: #808080;">&#40;</span>@databaseID, <span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#40;</span>@tableName<span style="color: #808080;">&#41;</span>, Null , Null, @scanMode<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> ps
                Join sys.<span style="color: #202020;">dm_db_index_operational_stats</span><span style="color: #808080;">&#40;</span>@databaseID, <span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#40;</span>@tableName<span style="color: #808080;">&#41;</span>, Null , Null<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> os
                    <span style="color: #0000FF;">ON</span> ps.<span style="color: #202020;">database_id</span> <span style="color: #808080;">=</span> os.<span style="color: #202020;">database_id</span>
                    And ps.<span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> os.<span style="color: #FF00FF;">OBJECT_ID</span>
                    and ps.<span style="color: #202020;">index_id</span> <span style="color: #808080;">=</span> os.<span style="color: #202020;">index_id</span>
                    And ps.<span style="color: #202020;">partition_number</span> <span style="color: #808080;">=</span> os.<span style="color: #202020;">partition_number</span>
                <span style="color: #0000FF;">WHERE</span> avg_fragmentation_in_percent <span style="color: #808080;">&gt;=</span> @minFragmentation 
                    And ps.<span style="color: #202020;">index_id</span> <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span> <span style="color: #008080;">-- ignore heaps</span>
                    And ps.<span style="color: #202020;">page_count</span> <span style="color: #808080;">&gt;</span> @minPageCount 
                    And ps.<span style="color: #202020;">index_level</span> <span style="color: #808080;">=</span> <span style="color: #000;">0</span> <span style="color: #008080;">-- leaf-level nodes only, supports @scanMode</span>
                <span style="color: #0000FF;">GROUP</span> <span style="color: #0000FF;">BY</span> ps.<span style="color: #202020;">database_id</span> 
                    , <span style="color: #FF00FF;">QUOTENAME</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">DB_NAME</span><span style="color: #808080;">&#40;</span>ps.<span style="color: #202020;">database_id</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> 
                    , ps.<span style="color: #FF00FF;">OBJECT_ID</span> 
                    , ps.<span style="color: #202020;">index_id</span> 
                    , ps.<span style="color: #202020;">partition_number</span> 
                    , os.<span style="color: #202020;">range_scan_count</span>
                <span style="color: #0000FF;">OPTION</span> <span style="color: #808080;">&#40;</span>MaxDop <span style="color: #000;">2</span><span style="color: #808080;">&#41;</span>;
&nbsp;
                <span style="color: #008080;">/* Do we want to exclude right-most populated partition of our partitioned indexes? */</span>
                <span style="color: #0000FF;">IF</span> @excludeMaxPartition <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
                <span style="color: #0000FF;">BEGIN</span>
&nbsp;
                    <span style="color: #0000FF;">SET</span> @excludeMaxPartitionSQL <span style="color: #808080;">=</span> <span style="color: #FF0000;">'
                        Select '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@databaseID <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">' As [databaseID]
                            , [object_id]
                            , index_id
                            , Max(partition_number) As [maxPartition]
                        From '</span> <span style="color: #808080;">+</span> <span style="color: #FF00FF;">DB_NAME</span><span style="color: #808080;">&#40;</span>@databaseID<span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">'.sys.partitions
                        Where partition_number &gt; 1
                            And [rows] &gt; 0
                        Group By object_id
                            , index_id;'</span>;
&nbsp;
                    <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> #maxPartitionList
                    <span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">SP_EXECUTESQL</span> @excludeMaxPartitionSQL;
&nbsp;
                <span style="color: #0000FF;">END</span>;
&nbsp;
                <span style="color: #008080;">/* Keep track of which databases have already been scanned */</span>
                <span style="color: #0000FF;">UPDATE</span> #databaseList
                <span style="color: #0000FF;">SET</span> scanStatus <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
                <span style="color: #0000FF;">WHERE</span> databaseID <span style="color: #808080;">=</span> @databaseID;
&nbsp;
            <span style="color: #0000FF;">END</span>
&nbsp;
            <span style="color: #008080;">/* We don't want to defrag the right-most populated partition, so
               delete any records for partitioned indexes where partition = Max(partition) */</span>
            <span style="color: #0000FF;">IF</span> @excludeMaxPartition <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
            <span style="color: #0000FF;">BEGIN</span>
&nbsp;
                <span style="color: #0000FF;">DELETE</span> ids
                <span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">dba_indexDefragStatus</span> <span style="color: #0000FF;">AS</span> ids
                Join #maxPartitionList <span style="color: #0000FF;">AS</span> mpl
                    <span style="color: #0000FF;">ON</span> ids.<span style="color: #202020;">databaseID</span> <span style="color: #808080;">=</span> mpl.<span style="color: #202020;">databaseID</span>
                    And ids.<span style="color: #202020;">objectID</span> <span style="color: #808080;">=</span> mpl.<span style="color: #202020;">objectID</span>
                    And ids.<span style="color: #202020;">indexID</span> <span style="color: #808080;">=</span> mpl.<span style="color: #202020;">indexID</span>
                    And ids.<span style="color: #202020;">partitionNumber</span> <span style="color: #808080;">=</span> mpl.<span style="color: #202020;">maxPartition</span>;
&nbsp;
            <span style="color: #0000FF;">END</span>;
&nbsp;
            <span style="color: #008080;">/* Update our exclusion mask for any index that has a restriction on the days it can be defragged */</span>
            <span style="color: #0000FF;">UPDATE</span> ids
            <span style="color: #0000FF;">SET</span> ids.<span style="color: #202020;">exclusionMask</span> <span style="color: #808080;">=</span> ide.<span style="color: #202020;">exclusionMask</span>
            <span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">dba_indexDefragStatus</span> <span style="color: #0000FF;">AS</span> ids
            Join dbo.<span style="color: #202020;">dba_indexDefragExclusion</span> <span style="color: #0000FF;">AS</span> ide
                <span style="color: #0000FF;">ON</span> ids.<span style="color: #202020;">databaseID</span> <span style="color: #808080;">=</span> ide.<span style="color: #202020;">databaseID</span>
                And ids.<span style="color: #202020;">objectID</span> <span style="color: #808080;">=</span> ide.<span style="color: #202020;">objectID</span>
                And ids.<span style="color: #202020;">indexID</span> <span style="color: #808080;">=</span> ide.<span style="color: #202020;">indexID</span>;
&nbsp;
        <span style="color: #0000FF;">END</span>
&nbsp;
        <span style="color: #0000FF;">SELECT</span> @debugMessage <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Looping through our list... there are '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">COUNT</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">*</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">' indexes to defrag!'</span>
        <span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">dba_indexDefragStatus</span>
        <span style="color: #0000FF;">WHERE</span> defragDate <span style="color: #0000FF;">IS</span> Null
            And page_count Between @minPageCount And IsNull<span style="color: #808080;">&#40;</span>@maxPageCount, page_count<span style="color: #808080;">&#41;</span>;
&nbsp;
        <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span>@debugMessage, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
        <span style="color: #008080;">/* Begin our loop for defragging */</span>
        <span style="color: #0000FF;">WHILE</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #FF00FF;">COUNT</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">*</span><span style="color: #808080;">&#41;</span> 
               <span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">dba_indexDefragStatus</span> 
               <span style="color: #0000FF;">WHERE</span> <span style="color: #808080;">&#40;</span>
                           <span style="color: #808080;">&#40;</span>@executeSQL <span style="color: #808080;">=</span> <span style="color: #000;">1</span> And defragDate <span style="color: #0000FF;">IS</span> Null<span style="color: #808080;">&#41;</span> 
                        Or <span style="color: #808080;">&#40;</span>@executeSQL <span style="color: #808080;">=</span> <span style="color: #000;">0</span> And defragDate <span style="color: #0000FF;">IS</span> Null And printStatus <span style="color: #808080;">=</span> <span style="color: #000;">0</span><span style="color: #808080;">&#41;</span>
                     <span style="color: #808080;">&#41;</span>
                And exclusionMask <span style="color: #808080;">&amp;</span> <span style="color: #FF00FF;">POWER</span><span style="color: #808080;">&#40;</span><span style="color: #000;">2</span>, <span style="color: #FF00FF;">DATEPART</span><span style="color: #808080;">&#40;</span>weekday, <span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">-</span><span style="color: #000;">1</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
                And page_count Between @minPageCount And IsNull<span style="color: #808080;">&#40;</span>@maxPageCount, page_count<span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span>
        <span style="color: #0000FF;">BEGIN</span>
&nbsp;
            <span style="color: #008080;">/* Check to see if we need to exit our loop because of our time limit */</span>        
            <span style="color: #0000FF;">IF</span> IsNull<span style="color: #808080;">&#40;</span>@endDateTime, <span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">&lt;</span> <span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>
            <span style="color: #0000FF;">BEGIN</span>
                <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Our time limit has been exceeded!'</span>, <span style="color: #000;">11</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
            <span style="color: #0000FF;">END</span>;
&nbsp;
            <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  Picking an index to beat into shape...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
            <span style="color: #008080;">/* Grab the index with the highest priority, based on the values submitted; 
               Look at the exclusion mask to ensure it can be defragged today */</span>
            <span style="color: #0000FF;">SET</span> @getIndexSQL <span style="color: #808080;">=</span> N<span style="color: #FF0000;">'
            Select Top 1 
                  @objectID_Out         = objectID
                , @indexID_Out          = indexID
                , @databaseID_Out       = databaseID
                , @databaseName_Out     = databaseName
                , @fragmentation_Out    = fragmentation
                , @partitionNumber_Out  = partitionNumber
                , @pageCount_Out        = page_count
            From dbo.dba_indexDefragStatus
            Where defragDate Is Null '</span> 
                <span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> @executeSQL <span style="color: #808080;">=</span> <span style="color: #000;">0</span> <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">'And printStatus = 0'</span> <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">''</span> <span style="color: #0000FF;">END</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">'
                And exclusionMask &amp; Power(2, DatePart(weekday, GetDate())-1) = 0
                And page_count Between @p_minPageCount and IsNull(@p_maxPageCount, page_count)
            Order By + '</span> <span style="color: #808080;">+</span> @defragOrderColumn <span style="color: #808080;">+</span> <span style="color: #FF0000;">' '</span> <span style="color: #808080;">+</span> @defragSortOrder;
&nbsp;
            <span style="color: #0000FF;">SET</span> @getIndexSQL_Param <span style="color: #808080;">=</span> N<span style="color: #FF0000;">'@objectID_Out        int OutPut
                                     , @indexID_Out         int OutPut
                                     , @databaseID_Out      int OutPut
                                     , @databaseName_Out    nvarchar(128) OutPut
                                     , @fragmentation_Out   int OutPut
                                     , @partitionNumber_Out int OutPut
                                     , @pageCount_Out       int OutPut
                                     , @p_minPageCount      int
                                     , @p_maxPageCount      int'</span>;
&nbsp;
            <span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">SP_EXECUTESQL</span> @getIndexSQL
                , @getIndexSQL_Param
                , @p_minPageCount       <span style="color: #808080;">=</span> @minPageCount
                , @p_maxPageCount       <span style="color: #808080;">=</span> @maxPageCount
                , @objectID_Out         <span style="color: #808080;">=</span> @objectID <span style="color: #0000FF;">OUTPUT</span>
                , @indexID_Out          <span style="color: #808080;">=</span> @indexID <span style="color: #0000FF;">OUTPUT</span>
                , @databaseID_Out       <span style="color: #808080;">=</span> @databaseID <span style="color: #0000FF;">OUTPUT</span>
                , @databaseName_Out     <span style="color: #808080;">=</span> @databaseName <span style="color: #0000FF;">OUTPUT</span>
                , @fragmentation_Out    <span style="color: #808080;">=</span> @fragmentation <span style="color: #0000FF;">OUTPUT</span>
                , @partitionNumber_Out  <span style="color: #808080;">=</span> @partitionNumber <span style="color: #0000FF;">OUTPUT</span>
                , @pageCount_Out        <span style="color: #808080;">=</span> @pageCount <span style="color: #0000FF;">OUTPUT</span>;
&nbsp;
            <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  Looking up the specifics for our index...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
            <span style="color: #008080;">/* Look up index information */</span>
            <span style="color: #0000FF;">SELECT</span> @updateSQL <span style="color: #808080;">=</span> N<span style="color: #FF0000;">'Update ids
                Set schemaName = QuoteName(s.name)
                    , objectName = QuoteName(o.name)
                    , indexName = QuoteName(i.name)
                From dbo.dba_indexDefragStatus As ids
                Inner Join '</span> <span style="color: #808080;">+</span> @databaseName <span style="color: #808080;">+</span> <span style="color: #FF0000;">'.sys.objects As o
                    On ids.objectID = o.object_id
                Inner Join '</span> <span style="color: #808080;">+</span> @databaseName <span style="color: #808080;">+</span> <span style="color: #FF0000;">'.sys.indexes As i
                    On o.object_id = i.object_id
                    And ids.indexID = i.index_id
                Inner Join '</span> <span style="color: #808080;">+</span> @databaseName <span style="color: #808080;">+</span> <span style="color: #FF0000;">'.sys.schemas As s
                    On o.schema_id = s.schema_id
                Where o.object_id = '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@objectID <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">'
                    And i.index_id = '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@indexID <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">'
                    And i.type &gt; 0
                    And ids.databaseID = '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@databaseID <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>;
&nbsp;
            <span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">SP_EXECUTESQL</span> @updateSQL;
&nbsp;
            <span style="color: #008080;">/* Grab our object names */</span>
            <span style="color: #0000FF;">SELECT</span> @objectName  <span style="color: #808080;">=</span> objectName
                , @schemaName   <span style="color: #808080;">=</span> schemaName
                , @indexName    <span style="color: #808080;">=</span> indexName
            <span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">dba_indexDefragStatus</span>
            <span style="color: #0000FF;">WHERE</span> objectID <span style="color: #808080;">=</span> @objectID
                And indexID <span style="color: #808080;">=</span> @indexID
                And databaseID <span style="color: #808080;">=</span> @databaseID;
&nbsp;
            <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  Grabbing the partition count...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
            <span style="color: #008080;">/* Determine if the index is partitioned */</span>
            <span style="color: #0000FF;">SELECT</span> @partitionSQL <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Select @partitionCount_OUT = Count(*)
                                        From '</span> <span style="color: #808080;">+</span> @databaseName <span style="color: #808080;">+</span> <span style="color: #FF0000;">'.sys.partitions
                                        Where object_id = '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@objectID <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">'
                                            And index_id = '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@indexID <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">';'</span>
                , @partitionSQL_Param <span style="color: #808080;">=</span> <span style="color: #FF0000;">'@partitionCount_OUT int OutPut'</span>;
&nbsp;
            <span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">SP_EXECUTESQL</span> @partitionSQL, @partitionSQL_Param, @partitionCount_OUT <span style="color: #808080;">=</span> @partitionCount <span style="color: #0000FF;">OUTPUT</span>;
&nbsp;
            <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  Seeing if there are any LOBs to be handled...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
            <span style="color: #008080;">/* Determine if the table contains LOBs */</span>
            <span style="color: #0000FF;">SELECT</span> @LOB_SQL <span style="color: #808080;">=</span> <span style="color: #FF0000;">' Select @containsLOB_OUT = Count(*)
                                From '</span> <span style="color: #808080;">+</span> @databaseName <span style="color: #808080;">+</span> <span style="color: #FF0000;">'.sys.columns With (NoLock) 
                                Where [object_id] = '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@objectID <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">'
                                   And (system_type_id In (34, 35, 99)
                                            Or max_length = -1);'</span>
                                <span style="color: #008080;">/*  system_type_id --&gt; 34 = image, 35 = text, 99 = ntext
                                    max_length = -1 --&gt; varbinary(max), varchar(max), nvarchar(max), xml */</span>
                    , @LOB_SQL_Param <span style="color: #808080;">=</span> <span style="color: #FF0000;">'@containsLOB_OUT int OutPut'</span>;
&nbsp;
            <span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">SP_EXECUTESQL</span> @LOB_SQL, @LOB_SQL_Param, @containsLOB_OUT <span style="color: #808080;">=</span> @containsLOB <span style="color: #0000FF;">OUTPUT</span>;
&nbsp;
            <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  Checking for indexes that do not allow page locks...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
            <span style="color: #008080;">/* Determine if page locks are allowed; for those indexes, we need to always rebuild */</span>
            <span style="color: #0000FF;">SELECT</span> @allowPageLockSQL <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Select @allowPageLocks_OUT = Count(*)
                                        From '</span> <span style="color: #808080;">+</span> @databaseName <span style="color: #808080;">+</span> <span style="color: #FF0000;">'.sys.indexes
                                        Where object_id = '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@objectID <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">'
                                            And index_id = '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@indexID <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">'
                                            And Allow_Page_Locks = 0;'</span>
                , @allowPageLockSQL_Param <span style="color: #808080;">=</span> <span style="color: #FF0000;">'@allowPageLocks_OUT int OutPut'</span>;
&nbsp;
            <span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">SP_EXECUTESQL</span> @allowPageLockSQL, @allowPageLockSQL_Param, @allowPageLocks_OUT <span style="color: #808080;">=</span> @allowPageLocks <span style="color: #0000FF;">OUTPUT</span>;
&nbsp;
            <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  Building our SQL statements...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
            <span style="color: #008080;">/* If there's not a lot of fragmentation, or if we have a LOB, we should reorganize */</span>
            <span style="color: #0000FF;">IF</span> <span style="color: #808080;">&#40;</span>@fragmentation <span style="color: #808080;">&lt;</span> @rebuildThreshold Or @containsLOB <span style="color: #808080;">&gt;=</span> <span style="color: #000;">1</span> Or @partitionCount <span style="color: #808080;">&gt;</span> <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>
                And @allowPageLocks <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
            <span style="color: #0000FF;">BEGIN</span>
&nbsp;
                <span style="color: #0000FF;">SET</span> @sqlCommand <span style="color: #808080;">=</span> N<span style="color: #FF0000;">'Alter Index '</span> <span style="color: #808080;">+</span> @indexName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">' On '</span> <span style="color: #808080;">+</span> @databaseName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">'.'</span> 
                                    <span style="color: #808080;">+</span> @schemaName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">'.'</span> <span style="color: #808080;">+</span> @objectName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">' ReOrganize'</span>;
&nbsp;
                <span style="color: #008080;">/* If our index is partitioned, we should always reorganize */</span>
                <span style="color: #0000FF;">IF</span> @partitionCount <span style="color: #808080;">&gt;</span> <span style="color: #000;">1</span>
                    <span style="color: #0000FF;">SET</span> @sqlCommand <span style="color: #808080;">=</span> @sqlCommand <span style="color: #808080;">+</span> N<span style="color: #FF0000;">' Partition = '</span> 
                                    <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@partitionNumber <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>;
&nbsp;
            <span style="color: #0000FF;">END</span>
            <span style="color: #008080;">/* If the index is heavily fragmented and doesn't contain any partitions or LOB's, 
               or if the index does not allow page locks, rebuild it */</span>
            <span style="color: #0000FF;">ELSE</span> <span style="color: #0000FF;">IF</span> <span style="color: #808080;">&#40;</span>@fragmentation <span style="color: #808080;">&gt;=</span> @rebuildThreshold Or @allowPageLocks <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">0</span><span style="color: #808080;">&#41;</span>
                And IsNull<span style="color: #808080;">&#40;</span>@containsLOB, <span style="color: #000;">0</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">!=</span> <span style="color: #000;">1</span> And @partitionCount <span style="color: #808080;">&lt;=</span> <span style="color: #000;">1</span>
            <span style="color: #0000FF;">BEGIN</span>
&nbsp;
                <span style="color: #008080;">/* Set online rebuild options; requires Enterprise Edition */</span>
                <span style="color: #0000FF;">IF</span> @onlineRebuild <span style="color: #808080;">=</span> <span style="color: #000;">1</span> And @editionCheck <span style="color: #808080;">=</span> <span style="color: #000;">1</span> 
                    <span style="color: #0000FF;">SET</span> @rebuildCommand <span style="color: #808080;">=</span> N<span style="color: #FF0000;">' Rebuild With (Online = On'</span>;
                <span style="color: #0000FF;">ELSE</span>
                    <span style="color: #0000FF;">SET</span> @rebuildCommand <span style="color: #808080;">=</span> N<span style="color: #FF0000;">' Rebuild With (Online = Off'</span>;
&nbsp;
                <span style="color: #008080;">/* Set sort operation preferences */</span>
                <span style="color: #0000FF;">IF</span> @sortInTempDB <span style="color: #808080;">=</span> <span style="color: #000;">1</span> 
                    <span style="color: #0000FF;">SET</span> @rebuildCommand <span style="color: #808080;">=</span> @rebuildCommand <span style="color: #808080;">+</span> N<span style="color: #FF0000;">', Sort_In_TempDB = On'</span>;
                <span style="color: #0000FF;">ELSE</span>
                    <span style="color: #0000FF;">SET</span> @rebuildCommand <span style="color: #808080;">=</span> @rebuildCommand <span style="color: #808080;">+</span> N<span style="color: #FF0000;">', Sort_In_TempDB = Off'</span>;
&nbsp;
                <span style="color: #008080;">/* Set processor restriction options; requires Enterprise Edition */</span>
                <span style="color: #0000FF;">IF</span> @maxDopRestriction <span style="color: #0000FF;">IS</span> Not Null And @editionCheck <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
                    <span style="color: #0000FF;">SET</span> @rebuildCommand <span style="color: #808080;">=</span> @rebuildCommand <span style="color: #808080;">+</span> N<span style="color: #FF0000;">', MaxDop = '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@maxDopRestriction <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">2</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> N<span style="color: #FF0000;">')'</span>;
                <span style="color: #0000FF;">ELSE</span>
                    <span style="color: #0000FF;">SET</span> @rebuildCommand <span style="color: #808080;">=</span> @rebuildCommand <span style="color: #808080;">+</span> N<span style="color: #FF0000;">')'</span>;
&nbsp;
                <span style="color: #0000FF;">SET</span> @sqlCommand <span style="color: #808080;">=</span> N<span style="color: #FF0000;">'Alter Index '</span> <span style="color: #808080;">+</span> @indexName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">' On '</span> <span style="color: #808080;">+</span> @databaseName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">'.'</span>
                                <span style="color: #808080;">+</span> @schemaName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">'.'</span> <span style="color: #808080;">+</span> @objectName <span style="color: #808080;">+</span> @rebuildCommand;
&nbsp;
            <span style="color: #0000FF;">END</span>
            <span style="color: #0000FF;">ELSE</span>
                <span style="color: #008080;">/* Print an error message if any indexes happen to not meet the criteria above */</span>
                <span style="color: #0000FF;">IF</span> @printCommands <span style="color: #808080;">=</span> <span style="color: #000;">1</span> Or @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
                    <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'We are unable to defrag this index.'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
            <span style="color: #008080;">/* Are we executing the SQL?  If so, do it */</span>
            <span style="color: #0000FF;">IF</span> @executeSQL <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
            <span style="color: #0000FF;">BEGIN</span>
&nbsp;
                <span style="color: #0000FF;">SET</span> @debugMessage <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Executing: '</span> <span style="color: #808080;">+</span> @sqlCommand;
&nbsp;
                <span style="color: #008080;">/* Print the commands we're executing if specified to do so */</span>
                <span style="color: #0000FF;">IF</span> @printCommands <span style="color: #808080;">=</span> <span style="color: #000;">1</span> Or @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
                    <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span>@debugMessage, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
                <span style="color: #008080;">/* Grab the time for logging purposes */</span>
                <span style="color: #0000FF;">SET</span> @dateTimeStart  <span style="color: #808080;">=</span> <span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>;
&nbsp;
                <span style="color: #008080;">/* Log our actions */</span>
                <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> dbo.<span style="color: #202020;">dba_indexDefragLog</span>
                <span style="color: #808080;">&#40;</span>
                      databaseID
                    , databaseName
                    , objectID
                    , objectName
                    , indexID
                    , indexName
                    , partitionNumber
                    , fragmentation
                    , page_count
                    , dateTimeStart
                    , sqlStatement
                <span style="color: #808080;">&#41;</span>
                <span style="color: #0000FF;">SELECT</span>
                      @databaseID
                    , @databaseName
                    , @objectID
                    , @objectName
                    , @indexID
                    , @indexName
                    , @partitionNumber
                    , @fragmentation
                    , @pageCount
                    , @dateTimeStart
                    , @sqlCommand;
&nbsp;
                <span style="color: #0000FF;">SET</span> @indexDefrag_id <span style="color: #808080;">=</span> <span style="color: #FF00FF;">SCOPE_IDENTITY</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>;
&nbsp;
                <span style="color: #008080;">/* Wrap our execution attempt in a try/catch and log any errors that occur */</span>
                <span style="color: #0000FF;">BEGIN</span> Try
&nbsp;
                    <span style="color: #008080;">/* Execute our defrag! */</span>
                    <span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">SP_EXECUTESQL</span> @sqlCommand;
                    <span style="color: #0000FF;">SET</span> @dateTimeEnd <span style="color: #808080;">=</span> <span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>;
&nbsp;
                    <span style="color: #008080;">/* Update our log with our completion time */</span>
                    <span style="color: #0000FF;">UPDATE</span> dbo.<span style="color: #202020;">dba_indexDefragLog</span>
                    <span style="color: #0000FF;">SET</span> dateTimeEnd <span style="color: #808080;">=</span> @dateTimeEnd
                        , durationSeconds <span style="color: #808080;">=</span> <span style="color: #FF00FF;">DATEDIFF</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SECOND</span>, @dateTimeStart, @dateTimeEnd<span style="color: #808080;">&#41;</span>
                    <span style="color: #0000FF;">WHERE</span> indexDefrag_id <span style="color: #808080;">=</span> @indexDefrag_id;
&nbsp;
                <span style="color: #0000FF;">END</span> Try
                <span style="color: #0000FF;">BEGIN</span> Catch
&nbsp;
                    <span style="color: #008080;">/* Update our log with our error message */</span>
                    <span style="color: #0000FF;">UPDATE</span> dbo.<span style="color: #202020;">dba_indexDefragLog</span>
                    <span style="color: #0000FF;">SET</span> dateTimeEnd <span style="color: #808080;">=</span> <span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>
                        , durationSeconds <span style="color: #808080;">=</span> <span style="color: #808080;">-</span><span style="color: #000;">1</span>
                        , errorMessage <span style="color: #808080;">=</span> Error_Message<span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>
                    <span style="color: #0000FF;">WHERE</span> indexDefrag_id <span style="color: #808080;">=</span> @indexDefrag_id;
&nbsp;
                    <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> 
                        <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  An error has occurred executing this command! Please review the dba_indexDefragLog table for details.'</span>
                            , <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
                <span style="color: #0000FF;">END</span> Catch
&nbsp;
                <span style="color: #008080;">/* Just a little breather for the server */</span>
                <span style="color: #0000FF;">WAITFOR</span> Delay @defragDelay;
&nbsp;
                <span style="color: #0000FF;">UPDATE</span> dbo.<span style="color: #202020;">dba_indexDefragStatus</span>
                <span style="color: #0000FF;">SET</span> defragDate <span style="color: #808080;">=</span> <span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>
                    , printStatus <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
                <span style="color: #0000FF;">WHERE</span> databaseID       <span style="color: #808080;">=</span> @databaseID
                  And objectID         <span style="color: #808080;">=</span> @objectID
                  And indexID          <span style="color: #808080;">=</span> @indexID
                  And partitionNumber  <span style="color: #808080;">=</span> @partitionNumber;
&nbsp;
            <span style="color: #0000FF;">END</span>
            <span style="color: #0000FF;">ELSE</span>
            <span style="color: #008080;">/* Looks like we're not executing, just printing the commands */</span>
            <span style="color: #0000FF;">BEGIN</span>
                <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  Printing SQL statements...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
                <span style="color: #0000FF;">IF</span> @printCommands <span style="color: #808080;">=</span> <span style="color: #000;">1</span> Or @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> 
                    <span style="color: #0000FF;">PRINT</span> IsNull<span style="color: #808080;">&#40;</span>@sqlCommand, <span style="color: #FF0000;">'error!'</span><span style="color: #808080;">&#41;</span>;
&nbsp;
                <span style="color: #0000FF;">UPDATE</span> dbo.<span style="color: #202020;">dba_indexDefragStatus</span>
                <span style="color: #0000FF;">SET</span> printStatus <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
                <span style="color: #0000FF;">WHERE</span> databaseID       <span style="color: #808080;">=</span> @databaseID
                  And objectID         <span style="color: #808080;">=</span> @objectID
                  And indexID          <span style="color: #808080;">=</span> @indexID
                  And partitionNumber  <span style="color: #808080;">=</span> @partitionNumber;
            <span style="color: #0000FF;">END</span>
&nbsp;
        <span style="color: #0000FF;">END</span>
&nbsp;
        <span style="color: #008080;">/* Do we want to output our fragmentation results? */</span>
        <span style="color: #0000FF;">IF</span> @printFragmentation <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
        <span style="color: #0000FF;">BEGIN</span>
&nbsp;
            <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  Displaying a summary of our action...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
            <span style="color: #0000FF;">SELECT</span> databaseID
                , databaseName
                , objectID
                , objectName
                , indexID
                , indexName
                , partitionNumber
                , fragmentation
                , page_count
                , range_scan_count
            <span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">dba_indexDefragStatus</span>
            <span style="color: #0000FF;">WHERE</span> defragDate <span style="color: #808080;">&gt;=</span> @startDateTime
            <span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> defragDate;
&nbsp;
        <span style="color: #0000FF;">END</span>;
&nbsp;
    <span style="color: #0000FF;">END</span> Try
    <span style="color: #0000FF;">BEGIN</span> Catch
&nbsp;
        <span style="color: #0000FF;">SET</span> @debugMessage <span style="color: #808080;">=</span> Error_Message<span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">' (Line Number: '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>Error_Line<span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">')'</span>;
        <span style="color: #0000FF;">PRINT</span> @debugMessage;
&nbsp;
    <span style="color: #0000FF;">END</span> Catch;
&nbsp;
    <span style="color: #008080;">/* When everything is said and done, make sure to get rid of our temp table */</span>
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">TABLE</span> #databaseList;
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">TABLE</span> #processor;
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">TABLE</span> #maxPartitionList;
&nbsp;
    <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'DONE!  Thank you for taking care of your indexes!  :)'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
    <span style="color: #0000FF;">SET</span> <span style="color: #0000FF;">NOCOUNT</span> <span style="color: #0000FF;">OFF</span>;
    <span style="color: #0000FF;">RETURN</span> <span style="color: #000;">0</span>
<span style="color: #0000FF;">END</span></pre></div></div>

<p>You can also download it here: <a href="http://sqlfool.com/scripts/dba_indexDefrag_sp_v40_public.txt" target="_blank">dba_indexDefrag_sp_v40_public.txt</a></p>
<p>I've had this latest version in production on terabyte-size databases running SQL Server 2005 and 2008 Enterprise editions for the last 3 months, where it runs nightly without issue.  I've also had numerous beta testers report success in their environments, too.  But to be safe, make sure to keep an eye on it the first time it runs to ensure you understand the impact on your server.</p>
<p>Enjoy!</p>
<p>Michelle</p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2010/04/index-defrag-script-v4-0/feed/</wfw:commentRss>
		<slash:comments>45</slash:comments>
		</item>
		<item>
		<title>Filtered Indexes Work-Around</title>
		<link>http://sqlfool.com/2010/02/filtered-indexes-work-around/</link>
		<comments>http://sqlfool.com/2010/02/filtered-indexes-work-around/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 16:00:14 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[SQL Tips]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[2008]]></category>
		<category><![CDATA[filtered indexes]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1307</guid>
		<description><![CDATA[Recently, I needed to create a stored procedure that queried a rather large table. The table has a filtered index on a date column, and it covers the query. However, the Query Optimizer was not using the index, which was increasing the execution time (not to mention IO!) by at least 10x. This wasn't the [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, I needed to create a stored procedure that queried a rather large table.  The table has a filtered index on a date column, and it covers the query.  However, the Query Optimizer was not using the index, which was increasing the execution time (not to mention IO!) by at least 10x.  This wasn't the first time I've had the Optimizer fail to use a filtered index.  Normally when this happens, I use a table hint to force the filtered index -- after I verify that it is indeed faster, of course.  However, since this was a stored procedure, I was receiving the following error message whenever I tried to execute the proc:</p>
<p><span style="color: #ff0000;">Query processor could not produce a query plan because of the hints defined in this query. Resubmit the query without specifying any hints and without using SET FORCEPLAN.</span></p>
<p>SQL Server would not allow me to execute the stored procedure using the filtered index hint.  If I removed the hint, it executed, but it used a different, non-covering and far more expensive index.  For those of you not familiar with this issue, allow me to illustrate the problem.</p>
<p>First, create a table to play with and populate it with some bogus data:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">filteredIndexTest</span>
<span style="color: #808080;">&#40;</span>
      myID   <span style="color: #0000FF;">INT</span> <span style="color: #0000FF;">IDENTITY</span><span style="color: #808080;">&#40;</span><span style="color: #000;">1</span>,<span style="color: #000;">3</span><span style="color: #808080;">&#41;</span>
    , myDate <span style="color: #0000FF;">SMALLDATETIME</span> 
    , myData <span style="color: #0000FF;">CHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">100</span><span style="color: #808080;">&#41;</span>
&nbsp;
    <span style="color: #0000FF;">CONSTRAINT</span> PK_filteredIndexTest
        <span style="color: #0000FF;">PRIMARY</span> <span style="color: #0000FF;">KEY</span> <span style="color: #0000FF;">CLUSTERED</span><span style="color: #808080;">&#40;</span>myID<span style="color: #808080;">&#41;</span>
<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">SET</span> <span style="color: #0000FF;">NOCOUNT</span> <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">DECLARE</span> @<span style="color: #0000FF;">DATE</span> <span style="color: #0000FF;">SMALLDATETIME</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'2010-01-01'</span>;
&nbsp;
<span style="color: #0000FF;">WHILE</span> @<span style="color: #0000FF;">DATE</span> <span style="color: #808080;">&lt;</span> <span style="color: #FF0000;">'2010-02-01'</span>
<span style="color: #0000FF;">BEGIN</span>
&nbsp;
    <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> dbo.<span style="color: #202020;">filteredIndexTest</span>
    <span style="color: #808080;">&#40;</span>
          myDate
        , myData
    <span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">SELECT</span> @<span style="color: #0000FF;">DATE</span>
        , <span style="color: #FF0000;">'Date: '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CONVERT</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">20</span><span style="color: #808080;">&#41;</span>, @<span style="color: #0000FF;">DATE</span>, <span style="color: #000;">102</span><span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #0000FF;">SET</span> @<span style="color: #0000FF;">DATE</span> <span style="color: #808080;">=</span> <span style="color: #FF00FF;">DATEADD</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">MINUTE</span>, <span style="color: #000;">1</span>, @<span style="color: #0000FF;">DATE</span><span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">END</span>;
&nbsp;
<span style="color: #0000FF;">SELECT</span> <span style="color: #FF00FF;">COUNT</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">*</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">filteredIndexTest</span>;</pre></div></div>

<p>It looks like this will generate 44,640 rows of test data... plenty enough for our purposes.  Now, let's create our filtered index and write a query that will use it:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">NONCLUSTERED</span> <span style="color: #0000FF;">INDEX</span> IX_filteredIndexTest_1
    <span style="color: #0000FF;">ON</span> dbo.<span style="color: #202020;">filteredIndexTest</span><span style="color: #808080;">&#40;</span>myDate<span style="color: #808080;">&#41;</span>
    Include <span style="color: #808080;">&#40;</span>myData<span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">WHERE</span> myDate <span style="color: #808080;">&gt;=</span> <span style="color: #FF0000;">'2010-01-27'</span>;
&nbsp;
<span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">DISTINCT</span> myData
<span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">filteredIndexTest</span>
<span style="color: #0000FF;">WHERE</span> myDate <span style="color: #808080;">&gt;=</span> <span style="color: #FF0000;">'2010-01-28'</span>;</pre></div></div>

<p>If you look at the execution plan for this query, you'll notice that the Optimizer is using the filtered index.  Perfect!  Now let's parameterize it.</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">DECLARE</span> @myDate1 <span style="color: #0000FF;">SMALLDATETIME</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'2010-01-28'</span>;
&nbsp;
<span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">DISTINCT</span> myData
<span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">filteredIndexTest</span>
<span style="color: #0000FF;">WHERE</span> myDate <span style="color: #808080;">&gt;=</span> @myDate1;</pre></div></div>

<p>Uh oh.  Looking at the execution plan, we see that SQL Server is no longer using the filtered index.  Instead, it's scanning the clustered index!  Why is this?  There's actually a good explanation for it.  The reason is that I could, in theory, pass a date to my parameter that fell outside of the filtered date range.  If that's the case, then SQL Server could not utilize the filtered index.  Personally, I think it's a bug and SQL Server should identify whether or not a filtered index could be used based on the actual value submitted, but... that's a whole other blog post.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />   </p>
<p>So what can we do?  Well, dynamic SQL may be able to help us out in this case.  Let's give it a go.  First, let's try parameterized dynamic SQL.</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">DECLARE</span> @mySQL1 <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">2000</span><span style="color: #808080;">&#41;</span>
    , @myParam <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">2000</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'@p_myDate2 smalldatetime'</span>
    , @myDate2 <span style="color: #0000FF;">SMALLDATETIME</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'2010-01-28'</span>;
&nbsp;
<span style="color: #0000FF;">SET</span> @mySQL1 <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Select Distinct myData
              From dbo.filteredIndexTest
              Where myDate &gt;= @p_myDate2'</span>;
&nbsp;
<span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">SP_EXECUTESQL</span> @mySQL1, @myParam, @p_myDate2 <span style="color: #808080;">=</span> @myDate2;</pre></div></div>

<p>Looking at the execution plan, we see we're still scanning on the clustered index.  This is because the parameterized dynamic SQL resolves to be the exact same query as the one above it.  Let's try unparameterized SQL instead:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">DECLARE</span> @mySQL2 <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">2000</span><span style="color: #808080;">&#41;</span>
    , @myDate3 <span style="color: #0000FF;">SMALLDATETIME</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'2010-01-28'</span>;
&nbsp;
<span style="color: #0000FF;">SET</span> @mySQL2 <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Select Distinct myData
              From dbo.filteredIndexTest
              Where myDate &gt;= '</span><span style="color: #FF0000;">''</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@myDate3 <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">20</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">''</span><span style="color: #FF0000;">''</span>;
&nbsp;
<span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">SP_EXECUTESQL</span> @mySQL2;
&nbsp;
<span style="color: #008080;">-- Drop Table dbo.filteredIndexTest;</span></pre></div></div>

<p>Voila!  We have a seek on our filtered index.  Why?  Because the statement resolves to be identical to our first query, where we hard-coded the date value in the WHERE clause.</p>
<p>Now, I want to stress this fact: you should always, ALWAYS use parameterized dynamic SQL whenever possible.  Not only is it safer, but it's also faster, because it can reuse cached plans.  But sometimes you just cannot accomplish the same tasks with it.  This is one of those times.  If you do end up needing to use unparameterized dynamic SQL as a work-around, please make sure you're validating your input, especially if you're interfacing with any sort of external source.</p>
<p>There's an even easier work-around for this problem that <a href="http://twitter.com/CrappyCodingGuy ">Dave</a> (<a href="http://www.crappycoding.com" target="_blank">http://www.crappycoding.com</a>) shared with me: <a href="http://msdn.microsoft.com/en-us/library/ms181714.aspx" target="_blank">recompile</a>.</p>
<p>Adding "Option (Recompile)" to the end of your statements will force the Optimizer to re-evaluate which index will best meet the needs of your query every time the statement is executed.  More importantly, it evaluates the plan based on the actual values passed to the parameter... just like in our hard-coded and dynamic SQL examples.  Let's see it in action:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">DECLARE</span> @myDate4 <span style="color: #0000FF;">SMALLDATETIME</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'2010-01-28'</span>;
&nbsp;
<span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">DISTINCT</span> myData
<span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">filteredIndexTest</span> 
<span style="color: #0000FF;">WHERE</span> myDate <span style="color: #808080;">&gt;=</span> @myDate4
<span style="color: #0000FF;">OPTION</span> <span style="color: #808080;">&#40;</span>RECOMPILE<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">DECLARE</span> @myDate5 <span style="color: #0000FF;">SMALLDATETIME</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'2010-01-20'</span>;
&nbsp;
<span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">DISTINCT</span> myData
<span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">filteredIndexTest</span> 
<span style="color: #0000FF;">WHERE</span> myDate <span style="color: #808080;">&gt;=</span> @myDate5
<span style="color: #0000FF;">OPTION</span> <span style="color: #808080;">&#40;</span>RECOMPILE<span style="color: #808080;">&#41;</span>;</pre></div></div>

<p>If we look at the execution plans for the 2 queries above, we see that the first query seeks on the filtered index, and the second query scans on the clustered index.  This is because the second query cannot be satisfied with the filtered index because we initially limited our index to dates greater than or equal to 1/27/2010.  </p>
<p>There are, of course, trade-offs associated with each approach, so use whichever one best meets your needs.  Do you have another work-around for this issue?  If so, please let me know.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Update:  </p>
<p>Alex Kuznetsov (<a href="http://www.simple-talk.com/author/alex-kuznetsov/">http://www.simple-talk.com/author/alex-kuznetsov/</a>) shared this method too:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">DECLARE</span> @myDate1 <span style="color: #0000FF;">SMALLDATETIME</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'2010-01-28'</span>;
&nbsp;
<span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">DISTINCT</span> myData
<span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">filteredIndexTest</span>
<span style="color: #0000FF;">WHERE</span> myDate <span style="color: #808080;">=</span> @myDate1
<span style="color: #808080;">AND</span> myDate <span style="color: #808080;">&gt;=</span> <span style="color: #FF0000;">'2010-01-27'</span>;</pre></div></div>

<p>Like the other examples, this will result in an index seek on the filtered index.  Basically, by explicitly declaring the start date of your filter, you're letting the Optimizer know that the filtered index can satisfy the request, regardless of the parameter value passed.  Thanks for the tip, Alex!  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2010/02/filtered-indexes-work-around/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Index Defrag Script Updates &#8211; Beta Testers Needed</title>
		<link>http://sqlfool.com/2010/01/index-defrag-script-updates-beta-testers-needed/</link>
		<comments>http://sqlfool.com/2010/01/index-defrag-script-updates-beta-testers-needed/#comments</comments>
		<pubDate>Tue, 26 Jan 2010 21:15:37 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Miscellaneous]]></category>
		<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[T-SQL Scripts]]></category>
		<category><![CDATA[defrag]]></category>
		<category><![CDATA[defragment]]></category>
		<category><![CDATA[indexes]]></category>
		<category><![CDATA[script]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1298</guid>
		<description><![CDATA[Update: Wow! I've received a ton of responses to my request for beta testers. Thank you all! The SQL Community is really amazing. I'll hopefully have the new version online in just a few days. Over the last few months, I've received many great comments and suggestions regarding my Index Defrag Script v3.0. I've just [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Update:  </strong>Wow!  I've received a ton of responses to my request for beta testers.  Thank you all!  The SQL Community is really amazing.  I'll hopefully have the new version online in just a few days.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Over the last few months, I've received many great comments and suggestions regarding my Index Defrag Script v3.0.  I've just recently had time to implement most of these suggestions, plus some other things that I thought would be useful.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </p>
<p>Here's some of what you can look forward to shortly:</p>
<ul>
<li>Probably the single most requested feature, the new version of the script allows you to set a time limit for index defrags.</li>
<li>There's now a static table for managing the status of index defrags.  This way, when your time limit is reached, you can pick up where you left off the next day, without the need to rescan indexes.</li>
<li>There's now an option to prioritize defrags by range scan counts, fragmentation level, or page counts.</li>
<li>For those using partitioning, there is now an option to exclude the right-most populated partition from defrags (in theory, the one you're writing to in a sliding-window scenario).</li>
<li>Options such as page count limits and SORT_IN_TEMPDB are now parameterized.</li>
<li>I've enhanced error logging.</li>
<li>... and more!</li>
</ul>
<p>Right now, I'm looking for a few folks who are willing to beta test the script.  If you're interested, please send me an e-mail at <em>michelle </em>at <em>sqlfool </em>dot <em>com</em> with the editions of SQL Server you can test this on (i.e. 2005 Standard, 2008 Enterprise, etc.).  </p>
<p>Thank you!  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2010/01/index-defrag-script-updates-beta-testers-needed/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Replication Bug with Partitioned Tables</title>
		<link>http://sqlfool.com/2009/11/replication-bug-with-partitioned-tables/</link>
		<comments>http://sqlfool.com/2009/11/replication-bug-with-partitioned-tables/#comments</comments>
		<pubDate>Mon, 23 Nov 2009 14:48:54 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Miscellaneous]]></category>
		<category><![CDATA[SQL Tips]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[bug]]></category>
		<category><![CDATA[partitioning]]></category>
		<category><![CDATA[replication]]></category>
		<category><![CDATA[SQL Server 2005]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1290</guid>
		<description><![CDATA[Recently, we came across a bug in SQL Server 2005 on one of our production servers. Apparently, if you execute an ALTER TABLE statement on a replicated table with more than 128 partitions, the log reader will fail. A relatively obscure bug, I know. Microsoft has recognized this as a confirmed bug, but I couldn't [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, we came across a bug in SQL Server 2005 on one of our production servers.  Apparently, if you execute an ALTER TABLE statement on a replicated table with more than 128 partitions, the log reader will fail.  A relatively obscure bug, I know.  Microsoft has recognized this as a confirmed bug, but I couldn't find it anywhere on the intertubes, thus the inspiration for this blog post.  Microsoft's official solution for this issue is to upgrade to SQL Server 2008.  </p>
<p>For various reasons, we were unable to execute an upgrade at the time.  And since this was a 2 terabyte database, we wanted to come up with a solution that wouldn't involve reinitializing the entire publication.  Our quick-fix while we were troubleshooting the issue was to create a <a href="http://msdn.microsoft.com/en-us/library/ms188279.aspx" target="_blank">linked server</a> to the production box.  Not ideal, I know, but it worked in a pinch and minimized exposure of the issue.  Fortunately for us, we were able to solve the problem on the publication database pretty easily.  All of the affected partition functions had empty partitions created several months in the future, so we simply <a href="http://msdn.microsoft.com/en-us/library/ms186307.aspx" target="_blank">merged any empty partition ranges</a> for future dates.  Our solution to our now-out-of-date subscribers was to apply <a href="http://msdn.microsoft.com/en-us/library/ms151775.aspx" target="_blank">static row filtering</a> to any table with more than 100 million records.  While this would introduce some overhead with the replication of these tables, it would allow us a much faster recovery time.  We decided to use the start of the most recent hour as our filtering criteria, just to give us a "clean" filter, so we had to delete data from any table where we were going to apply the filter.  After that, it was simply a matter of resuming replication.  </p>
<p>All things considered, it took us a little over a day to recover from the issue.  Most of that time was spent troubleshooting the problem and identifying a workable solution; actual execution of the changes was pretty quick.  Moral of the story?  Upgrade to SQL Server 2008.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/11/replication-bug-with-partitioned-tables/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
