<?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; performance</title>
	<atom:link href="http://sqlfool.com/tag/performance/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>Wed, 02 Nov 2011 20:39: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>Index Defrag Script, v4.1</title>
		<link>http://sqlfool.com/2011/06/index-defrag-script-v4-1/</link>
		<comments>http://sqlfool.com/2011/06/index-defrag-script-v4-1/#comments</comments>
		<pubDate>Thu, 16 Jun 2011 18:44:11 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<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[partitioning]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[TSQL]]></category>
		<category><![CDATA[tuning]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1544</guid>
		<description><![CDATA[It's been quite some time since my last index defrag script update. A big part of the reason for that is because I wanted to implement many of the suggestions I've received, but I just haven't had the time. I still have those changes planned, but I'm not sure quite when I'll get to it. [...]]]></description>
			<content:encoded><![CDATA[<p>It's been quite some time since my last index defrag script update.  A big part of the reason for that is because I wanted to implement many of the suggestions I've received, but I just haven't had the time.  I still have those changes planned, but I'm not sure quite when I'll get to it.  Rather than continue to wait for a major release, I'm releasing a small update to my defrag that will take care of the most common complaints I receive.  </p>
<p><strong>Change Log:</strong></p>
<ul>
<li>Bug fix for databases containing spaces or special characters</li>
<li>Support for case-sensitive databases</li>
<li>Re-executable CREATE script (for those who want to re-run the whole script)</li>
<li>Comma-delimited list of databases is now supported for the @database parameter</li>
</ul>
<p><strong>Feature List:</strong></p>
<ul>
<li>Defrag a single database, a list of databases, or all databases (@database)</li>
<li>Time Limitations: stop defragging after the specified amount of time has elapsed (@timeLimit).  Please note, it will not kill a defrag that is currently in process, even if it exceeds the threshold.</li>
<li>Optional stop-and-resume functionality: pick up where your defrag last left off without having to rescan sys.dm_db_index_physical_stats. (@forceRescan) </li>
<li>Defrag scheduling: choose which days to defrag certain indexes, or exclude certain indexes altogether, by using the dbo.dba_indexDefragExclusion table.</li>
<li>Defrag priority: choose whether to defrag indexes in ascending or descending order by range_scan_count (default), fragmentation, or page_count.</li>
<li>Current partition exclusion: choose whether or not to exclude the right-most populated partition from the defrag process, common for sliding-window tables (@excludeMaxPartition)</li>
<li>Commands-only mode: Choose to just log the current defrag status and print the defrag commands, rather than executing them, by using @executeSQL.</li>
<li>... and tons more!  Please read the parameter list and notes section for details of all the options available.</li>
</ul>
<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 Microsoft has to say:</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 Understanding Pages and Extents." </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 />
Yes, you can.  </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>Special thanks to <a href="http://twitter.com/SQL_ME_RICH" target="_blank">Richard Yanger</a> for his assistance with beta testing.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>You can download a text file of this script here:  <a href="http://sqlfool.com/wp-content/uploads/2011/06/dba_indexDefrag_sp_v41.txt" target="_blank">dba_indexDefrag_sp_v41</a></p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/*** Scroll down to the see important notes, disclaimers, and licensing information ***/</span>
&nbsp;
<span style="color: #008080;">/* Let's create our parsing function... */</span>
<span style="color: #0000FF;">IF</span> <span style="color: #808080;">EXISTS</span> <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;">objects</span>
            <span style="color: #0000FF;">WHERE</span>   name <span style="color: #808080;">=</span> <span style="color: #FF0000;">'dba_parseString_udf'</span> <span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">FUNCTION</span> dbo.<span style="color: #202020;">dba_parseString_udf</span>;
GO
&nbsp;
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">FUNCTION</span> dbo.<span style="color: #202020;">dba_parseString_udf</span>
<span style="color: #808080;">&#40;</span>
          @stringToParse <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">8000</span><span style="color: #808080;">&#41;</span>  
        , @delimiter     <span style="color: #0000FF;">CHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>
<span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">RETURNS</span> @parsedString <span style="color: #0000FF;">TABLE</span> <span style="color: #808080;">&#40;</span>stringValue <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;">&#41;</span>
<span style="color: #0000FF;">AS</span>
<span style="color: #008080;">/*********************************************************************************
    Name:       dba_parseString_udf
&nbsp;
    Author:     Michelle Ufford, http://sqlfool.com
&nbsp;
    Purpose:    This function parses string input using a variable delimiter.
&nbsp;
    Notes:      Two common delimiter values are space (' ') and comma (',')
&nbsp;
    Date        Initials    Description
    ----------------------------------------------------------------------------
    2011-05-20  MFU         Initial Release
*********************************************************************************
Usage: 		
    SELECT *
    FROM dba_parseString_udf(&lt;string&gt;, &lt;delimiter&gt;);
&nbsp;
Test Cases:
&nbsp;
    1.  multiple strings separated by space
        SELECT * FROM dbo.dba_parseString_udf('  aaa  bbb  ccc ', ' ');
&nbsp;
    2.  multiple strings separated by comma
        SELECT * FROM dbo.dba_parseString_udf(',aaa,bbb,,,ccc,', ',');
*********************************************************************************/</span>
<span style="color: #0000FF;">BEGIN</span>
&nbsp;
    <span style="color: #008080;">/* Declare variables */</span>
    <span style="color: #0000FF;">DECLARE</span> @trimmedString  <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">8000</span><span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #008080;">/* We need to trim our string input in case the user entered extra spaces */</span>
    <span style="color: #0000FF;">SET</span> @trimmedString <span style="color: #808080;">=</span> <span style="color: #FF00FF;">LTRIM</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">RTRIM</span><span style="color: #808080;">&#40;</span>@stringToParse<span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #008080;">/* Let's create a recursive CTE to break down our string for us */</span>
    <span style="color: #0000FF;">WITH</span> parseCTE <span style="color: #808080;">&#40;</span>StartPos, EndPos<span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">AS</span>
    <span style="color: #808080;">&#40;</span>
        <span style="color: #0000FF;">SELECT</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">AS</span> StartPos
            , <span style="color: #FF00FF;">CHARINDEX</span><span style="color: #808080;">&#40;</span>@delimiter, @trimmedString <span style="color: #808080;">+</span> @delimiter<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> EndPos
        <span style="color: #0000FF;">UNION</span> <span style="color: #808080;">ALL</span>
        <span style="color: #0000FF;">SELECT</span> EndPos <span style="color: #808080;">+</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">AS</span> StartPos
            , <span style="color: #FF00FF;">CHARINDEX</span><span style="color: #808080;">&#40;</span>@delimiter, @trimmedString <span style="color: #808080;">+</span> @delimiter , EndPos <span style="color: #808080;">+</span> <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> EndPos
        <span style="color: #0000FF;">FROM</span> parseCTE
        <span style="color: #0000FF;">WHERE</span> <span style="color: #FF00FF;">CHARINDEX</span><span style="color: #808080;">&#40;</span>@delimiter, @trimmedString <span style="color: #808080;">+</span> @delimiter, EndPos <span style="color: #808080;">+</span> <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">0</span>
    <span style="color: #808080;">&#41;</span>
&nbsp;
    <span style="color: #008080;">/* Let's take the results and stick it in a table */</span>  
    <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> @parsedString
    <span style="color: #0000FF;">SELECT</span> <span style="color: #FF00FF;">SUBSTRING</span><span style="color: #808080;">&#40;</span>@trimmedString, StartPos, EndPos <span style="color: #808080;">-</span> StartPos<span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">FROM</span> parseCTE
    <span style="color: #0000FF;">WHERE</span> <span style="color: #FF00FF;">LEN</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">LTRIM</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">RTRIM</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">SUBSTRING</span><span style="color: #808080;">&#40;</span>@trimmedString, StartPos, EndPos <span style="color: #808080;">-</span> StartPos<span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span><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;">OPTION</span> <span style="color: #808080;">&#40;</span>MaxRecursion <span style="color: #000;">8000</span><span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #0000FF;">RETURN</span>;   
<span style="color: #0000FF;">END</span>
GO
&nbsp;
<span style="color: #008080;">/* First, we need to take care of schema updates, in case you have a legacy 
   version of the script installed */</span>
<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>;
&nbsp;
<span style="color: #0000FF;">IF</span> <span style="color: #808080;">EXISTS</span> <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;">indexes</span>
            <span style="color: #0000FF;">WHERE</span>   name <span style="color: #808080;">=</span> <span style="color: #FF0000;">'PK_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> <span style="color: #808080;">EXISTS</span> <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;">indexes</span>
            <span style="color: #0000FF;">WHERE</span>   name <span style="color: #808080;">=</span> <span style="color: #FF0000;">'PK_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> <span style="color: #808080;">NOT</span> <span style="color: #808080;">EXISTS</span> <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;">indexes</span>
                <span style="color: #0000FF;">WHERE</span>   name <span style="color: #808080;">=</span> <span style="color: #FF0000;">'PK_indexDefragLog_v40'</span> <span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">BEGIN</span>
&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>  <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
       , databaseID         <span style="color: #0000FF;">INT</span>                 <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</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>       <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
       , objectID           <span style="color: #0000FF;">INT</span>                 <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</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>       <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
       , indexID            <span style="color: #0000FF;">INT</span>                 <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</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>       <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
       , partitionNumber    <span style="color: #0000FF;">SMALLINT</span>            <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
       , fragmentation      <span style="color: #0000FF;">FLOAT</span>               <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
       , page_count         <span style="color: #0000FF;">INT</span>                 <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
       , dateTimeStart      <span style="color: #0000FF;">DATETIME</span>            <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
       , dateTimeEnd        <span style="color: #0000FF;">DATETIME</span>            <span style="color: #808080;">NULL</span>
       , durationSeconds    <span style="color: #0000FF;">INT</span>                 <span style="color: #808080;">NULL</span>
       , 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>       <span style="color: #808080;">NULL</span>
       , 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>       <span style="color: #808080;">NULL</span> 
&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;">END</span>
&nbsp;
<span style="color: #0000FF;">IF</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">EXISTS</span> <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;">indexes</span>
                <span style="color: #0000FF;">WHERE</span>   name <span style="color: #808080;">=</span> <span style="color: #FF0000;">'PK_indexDefragExclusion_v40'</span> <span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">BEGIN</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>             <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</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>   <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
       , objectID           <span style="color: #0000FF;">INT</span>             <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</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>   <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
       , indexID            <span style="color: #0000FF;">INT</span>             <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</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>   <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
       , exclusionMask      <span style="color: #0000FF;">INT</span>             <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
            <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;">END</span>
&nbsp;
<span style="color: #0000FF;">IF</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">EXISTS</span> <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;">indexes</span>
                <span style="color: #0000FF;">WHERE</span>   name <span style="color: #808080;">=</span> <span style="color: #FF0000;">'PK_indexDefragStatus_v40'</span> <span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">BEGIN</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>             <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</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>   <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
       , objectID           <span style="color: #0000FF;">INT</span>             <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
       , indexID            <span style="color: #0000FF;">INT</span>             <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
       , partitionNumber    <span style="color: #0000FF;">SMALLINT</span>        <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
       , fragmentation      <span style="color: #0000FF;">FLOAT</span>           <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
       , page_count         <span style="color: #0000FF;">INT</span>             <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
       , range_scan_count   <span style="color: #0000FF;">BIGINT</span>          <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</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>   <span style="color: #808080;">NULL</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>   <span style="color: #808080;">NULL</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>   <span style="color: #808080;">NULL</span>
       , scanDate           <span style="color: #0000FF;">DATETIME</span>        <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
       , defragDate         <span style="color: #0000FF;">DATETIME</span>        <span style="color: #808080;">NULL</span>
       , 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> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</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> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</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;">END</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> <span style="color: #808080;">NULL</span>
        <span style="color: #008080;">/* Option to specify one or more database names, separated by commas; 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> <span style="color: #808080;">NULL</span>  <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> <span style="color: #808080;">NULL</span>
        <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> <span style="color: #808080;">NULL</span>
        <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>
<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
    2011-04-28  MFU         4.1     Bug fixes for databases requiring []
                                    , cleaned up the create table section
                                    , updated syntax for case-sensitive databases
                                    , comma-delimited list for @database now supported
*********************************************************************************
    Example of how to call this script:
&nbsp;
        EXECUTE 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
            , @database             = 'sandbox,sandbox_caseSensitive';
*********************************************************************************/</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_AB<span style="color: #808080;">OR</span>T <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> <span style="color: #808080;">NULL</span> 
            <span style="color: #808080;">OR</span> @minFragmentation <span style="color: #808080;">NOT</span> <span style="color: #808080;">BETWEEN</span> <span style="color: #000;">0.00</span> <span style="color: #808080;">AND</span> <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> <span style="color: #808080;">NULL</span>
            <span style="color: #808080;">OR</span> @rebuildThreshold <span style="color: #808080;">NOT</span> <span style="color: #808080;">BETWEEN</span> <span style="color: #000;">0.00</span> <span style="color: #808080;">AND</span> <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 <span style="color: #808080;">NOT</span> <span style="color: #808080;">LIKE</span> <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> <span style="color: #808080;">NULL</span>
            <span style="color: #808080;">OR</span> @defragOrderColumn <span style="color: #808080;">NOT</span> <span style="color: #808080;">IN</span> <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> <span style="color: #808080;">NULL</span>
            <span style="color: #808080;">OR</span> @defragSortOrder <span style="color: #808080;">NOT</span> <span style="color: #808080;">IN</span> <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 <span style="color: #808080;">NOT</span> <span style="color: #808080;">IN</span> <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> <span style="color: #808080;">NULL</span>
            <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> <span style="color: #808080;">NULL</span>
            <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> <span style="color: #808080;">NULL</span>
            <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> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span> <span style="color: #808080;">AND</span> @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> <span style="color: #808080;">IN</span> <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> <span style="color: #808080;">NULL</span> <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> <span style="color: #808080;">NULL</span> <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(s)'</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> <span style="color: #808080;">NULL</span> <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> <span style="color: #808080;">EXISTS</span><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> <span style="color: #808080;">NULL</span><span style="color: #808080;">&#41;</span>
                <span style="color: #808080;">AND</span> @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> <span style="color: #808080;">NULL</span> <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> <span style="color: #808080;">OR</span> @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> <span style="color: #808080;">OR</span> @maxDopRestriction <span style="color: #0000FF;">IS</span> <span style="color: #808080;">NULL</span> 
                <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: #008080;">/* If @database is NULL, it means we want to defrag *all* databases */</span>
        <span style="color: #0000FF;">IF</span> @<span style="color: #0000FF;">database</span> <span style="color: #0000FF;">IS</span> <span style="color: #808080;">NULL</span>
        <span style="color: #0000FF;">BEGIN</span>
&nbsp;
            <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> <span style="color: #808080;">&#91;</span>name<span style="color: #808080;">&#93;</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">IN</span> <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>
                <span style="color: #808080;">AND</span> <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>
                <span style="color: #808080;">AND</span> 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: #0000FF;">END</span>;
        <span style="color: #0000FF;">ELSE</span>
        <span style="color: #008080;">/* Otherwise, we're going to just defrag our list of databases */</span>
        <span style="color: #0000FF;">BEGIN</span>
&nbsp;
            <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;">AS</span> d
            <span style="color: #808080;">JOIN</span> dbo.<span style="color: #202020;">dba_parseString_udf</span><span style="color: #808080;">&#40;</span>@<span style="color: #0000FF;">database</span>, <span style="color: #FF0000;">','</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> x
                <span style="color: #0000FF;">ON</span> d.<span style="color: #202020;">name</span> <span style="color: #808080;">=</span> x.<span style="color: #202020;">stringValue</span>
            <span style="color: #0000FF;">WHERE</span> <span style="color: #808080;">&#91;</span>name<span style="color: #808080;">&#93;</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">IN</span> <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>
                <span style="color: #808080;">AND</span> <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>
                <span style="color: #808080;">AND</span> 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: #0000FF;">END</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> <span style="color: #808080;">NOT</span> <span style="color: #808080;">EXISTS</span><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> <span style="color: #808080;">NULL</span><span style="color: #808080;">&#41;</span>
            <span style="color: #808080;">OR</span> @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: #808080;">&#91;</span><span style="color: #FF00FF;">object_id</span><span style="color: #808080;">&#93;</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>, <span style="color: #808080;">NULL</span> , <span style="color: #808080;">NULL</span>, @scanMode<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> ps
                <span style="color: #808080;">JOIN</span> 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>, <span style="color: #808080;">NULL</span> , <span style="color: #808080;">NULL</span><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>
                    <span style="color: #808080;">AND</span> ps.<span style="color: #808080;">&#91;</span><span style="color: #FF00FF;">object_id</span><span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> os.<span style="color: #808080;">&#91;</span><span style="color: #FF00FF;">object_id</span><span style="color: #808080;">&#93;</span>
                    <span style="color: #808080;">AND</span> ps.<span style="color: #202020;">index_id</span> <span style="color: #808080;">=</span> os.<span style="color: #202020;">index_id</span>
                    <span style="color: #808080;">AND</span> 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 
                    <span style="color: #808080;">AND</span> 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>
                    <span style="color: #808080;">AND</span> ps.<span style="color: #202020;">page_count</span> <span style="color: #808080;">&gt;</span> @minPageCount 
                    <span style="color: #808080;">AND</span> 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: #808080;">&#91;</span><span style="color: #FF00FF;">object_id</span><span style="color: #808080;">&#93;</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
                <span style="color: #808080;">JOIN</span> #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>
                    <span style="color: #808080;">AND</span> ids.<span style="color: #202020;">objectID</span> <span style="color: #808080;">=</span> mpl.<span style="color: #202020;">objectID</span>
                    <span style="color: #808080;">AND</span> ids.<span style="color: #202020;">indexID</span> <span style="color: #808080;">=</span> mpl.<span style="color: #202020;">indexID</span>
                    <span style="color: #808080;">AND</span> 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
            <span style="color: #808080;">JOIN</span> 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>
                <span style="color: #808080;">AND</span> ids.<span style="color: #202020;">objectID</span> <span style="color: #808080;">=</span> ide.<span style="color: #202020;">objectID</span>
                <span style="color: #808080;">AND</span> 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> <span style="color: #808080;">NULL</span>
            <span style="color: #808080;">AND</span> page_count <span style="color: #808080;">BETWEEN</span> @minPageCount <span style="color: #808080;">AND</span> IS<span style="color: #808080;">NULL</span><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> <span style="color: #808080;">AND</span> defragDate <span style="color: #0000FF;">IS</span> <span style="color: #808080;">NULL</span><span style="color: #808080;">&#41;</span> 
                        <span style="color: #808080;">OR</span> <span style="color: #808080;">&#40;</span>@executeSQL <span style="color: #808080;">=</span> <span style="color: #000;">0</span> <span style="color: #808080;">AND</span> defragDate <span style="color: #0000FF;">IS</span> <span style="color: #808080;">NULL</span> <span style="color: #808080;">AND</span> printStatus <span style="color: #808080;">=</span> <span style="color: #000;">0</span><span style="color: #808080;">&#41;</span>
                     <span style="color: #808080;">&#41;</span>
                <span style="color: #808080;">AND</span> 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>
                <span style="color: #808080;">AND</span> page_count <span style="color: #808080;">BETWEEN</span> @minPageCount <span style="color: #808080;">AND</span> IS<span style="color: #808080;">NULL</span><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> IS<span style="color: #808080;">NULL</span><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
                <span style="color: #808080;">AND</span> indexID <span style="color: #808080;">=</span> @indexID
                <span style="color: #808080;">AND</span> 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 <span style="color: #808080;">OR</span> @containsLOB <span style="color: #808080;">&gt;=</span> <span style="color: #000;">1</span> <span style="color: #808080;">OR</span> @partitionCount <span style="color: #808080;">&gt;</span> <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>
                <span style="color: #808080;">AND</span> @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 <span style="color: #808080;">OR</span> @allowPageLocks <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">0</span><span style="color: #808080;">&#41;</span>
                <span style="color: #808080;">AND</span> IS<span style="color: #808080;">NULL</span><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> <span style="color: #808080;">AND</span> @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> <span style="color: #808080;">AND</span> @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> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span> <span style="color: #808080;">AND</span> @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> <span style="color: #808080;">OR</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;">'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> <span style="color: #808080;">OR</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;">/* 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> ERR<span style="color: #808080;">OR</span>_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
                  <span style="color: #808080;">AND</span> objectID         <span style="color: #808080;">=</span> @objectID
                  <span style="color: #808080;">AND</span> indexID          <span style="color: #808080;">=</span> @indexID
                  <span style="color: #808080;">AND</span> 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> <span style="color: #808080;">OR</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> 
                    <span style="color: #0000FF;">PRINT</span> IS<span style="color: #808080;">NULL</span><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
                  <span style="color: #808080;">AND</span> objectID         <span style="color: #808080;">=</span> @objectID
                  <span style="color: #808080;">AND</span> indexID          <span style="color: #808080;">=</span> @indexID
                  <span style="color: #808080;">AND</span> 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> ERR<span style="color: #808080;">OR</span>_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>ERR<span style="color: #808080;">OR</span>_L<span style="color: #808080;">IN</span>E<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>

]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2011/06/index-defrag-script-v4-1/feed/</wfw:commentRss>
		<slash:comments>57</slash:comments>
		</item>
		<item>
		<title>Disposable Indexes</title>
		<link>http://sqlfool.com/2010/12/disposable-indexes/</link>
		<comments>http://sqlfool.com/2010/12/disposable-indexes/#comments</comments>
		<pubDate>Wed, 15 Dec 2010 20:50:10 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[indexes]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[tuning]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1443</guid>
		<description><![CDATA[Today I had to run an ad hoc query on a 8.5 billion row table. The table had a dozen columns of a variety of data types and was clustered on a bigint identity. There were no other indexes on the table. My query involved a join to a smaller table with a date range [...]]]></description>
			<content:encoded><![CDATA[<p>Today I had to run an ad hoc query on a 8.5 billion row table.  The table had a dozen columns of a variety of data types and was clustered on a bigint identity.  There were no other indexes on the table.  My query involved a join to a smaller table with a date range restriction.  Without an adequate index to use, SQL Server was going to be forced to scan this 8.5 billion row table.  Now, I don't have much patience for waiting for long running queries.  I want to run the ad hoc, e-mail the results, and forget about it.  But short of adding a nonclustered index, which would take a very long time to build and probably require additional space requisitioned from the SAN team, what could I do?  Enter disposable indexes.  Now, you might be asking yourself, "What the frilly heck does she mean by a disposable index?  Is that new in Denali?"  No, dear reader.  I am actually referring to filtered indexes, which is available in SQL Server 2008 and 2008 R2.  I call them "disposable" because I create them to significantly speed up ad hoc queries, then I drop them when I'm done.  </p>
<p>Here, allow me to demonstrate using the AdventureWorks2008R2 database.  Although the tables are smaller, this query is very similar in structure to what I needed to run today.</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">Select</span> <span style="color: #FF00FF;">Count</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">Distinct</span> sod.<span style="color: #202020;">SalesOrderID</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">As</span> <span style="color: #FF0000;">'distinctCount'</span>
<span style="color: #0000FF;">From</span> AdventureWorks2008R2.<span style="color: #202020;">Sales</span>.<span style="color: #202020;">SalesOrderDetail</span> <span style="color: #0000FF;">As</span> sod
Join AdventureWorks2008R2.<span style="color: #202020;">Production</span>.<span style="color: #202020;">Product</span> <span style="color: #0000FF;">As</span> p
    <span style="color: #0000FF;">On</span> sod.<span style="color: #202020;">ProductID</span> <span style="color: #808080;">=</span> p.<span style="color: #202020;">ProductID</span>
<span style="color: #0000FF;">Where</span> sod.<span style="color: #202020;">ModifiedDate</span> Between <span style="color: #FF0000;">'2008-01-01'</span> And <span style="color: #FF0000;">'2008-07-31'</span>
    And p.<span style="color: #202020;">MakeFlag</span> <span style="color: #808080;">=</span> <span style="color: #000;">0</span>;</pre></div></div>

<p>Now, let's take a look at the type of indexes we currently have available:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">Select</span> name, has_filter, filter_definition
<span style="color: #0000FF;">From</span> sys.<span style="color: #202020;">indexes</span>
<span style="color: #0000FF;">Where</span> <span style="color: #FF00FF;">object_id</span> <span style="color: #808080;">=</span> <span style="color: #FF00FF;">object_id</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Sales.SalesOrderDetail'</span><span style="color: #808080;">&#41;</span>;</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">name                                                    has_filter filter_definition
-----------------------------------------------------------------------------------------
PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailID     0          NULL
AK_SalesOrderDetail_rowguid                             0          NULL
IX_SalesOrderDetail_ProductID                           0          NULL
&nbsp;
(3 row(s) affected)</pre></div></div>

<p>We need an index on ModifiedDate and ProductID, which it doesn't look like we have currently.  Without this, we're going to end up scanning on the clustered index.  That means SQL Server will have to evaluate each and every single row in the table to see if the row matches the criteria of our query.  Not pretty, and certainly not fast.  So instead, let's create a filtered index on date.  But we can greatly speed up the time it takes to create our filtered index by doing a little investigating upfront and finding a range of clustering key values that will cover the query.  Doing this allows SQL Server to seek on the clustered index, greatly reducing the amount of reads necessary to create our filtered index.  So let's see this in action.  First, let's find out the current max value of the table:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">Select</span> <span style="color: #FF00FF;">Max</span><span style="color: #808080;">&#40;</span>SalesOrderDetailID<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">As</span> <span style="color: #FF0000;">'maxID'</span>
<span style="color: #0000FF;">From</span> AdventureWorks2008R2.<span style="color: #202020;">Sales</span>.<span style="color: #202020;">SalesOrderDetail</span>;</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">maxID
-----------
121317</pre></div></div>

<p>Now we get to do a little guessing.  Let's go back and see what date we get if we look at half of the records:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">Select</span> SalesOrderDetailID, ModifiedDate
<span style="color: #0000FF;">From</span> AdventureWorks2008R2.<span style="color: #202020;">Sales</span>.<span style="color: #202020;">SalesOrderDetail</span>
<span style="color: #0000FF;">Where</span> SalesOrderDetailID <span style="color: #808080;">=</span> <span style="color: #808080;">&#40;</span><span style="color: #000;">121317</span><span style="color: #808080;">/</span><span style="color: #000;">2</span><span style="color: #808080;">&#41;</span>;</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">SalesOrderDetailID ModifiedDate
------------------ -----------------------
60658              2007-11-01 00:00:00.000</pre></div></div>

<p>Okay, SalesOrderDetailID 60658 gets us back to 11/1/2007.  That's a little too far.  Let's see how a SalesOrderDetailID value of 75000 does...</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">Select</span> SalesOrderDetailID, ModifiedDate
<span style="color: #0000FF;">From</span> AdventureWorks2008R2.<span style="color: #202020;">Sales</span>.<span style="color: #202020;">SalesOrderDetail</span>
<span style="color: #0000FF;">Where</span> SalesOrderDetailID <span style="color: #808080;">=</span> <span style="color: #000;">75000</span>;</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">SalesOrderDetailID ModifiedDate
------------------ -----------------------
75000              2007-12-27 00:00:00.000</pre></div></div>

<p>Okay, SalesOrderDetailID 75000 takes us back to 12/27/2007.  That's close enough to 1/1/2008 for my purposes.  Of course, depending on the size of the table, in real life it may make sense to try to get closer to the value you're looking for.  But for now, this will do.  And because we're looking for data through the "current date" (7/31/2008 in the AdventureWorks2008R2 database), we already know our outer limit is 121317.</p>
<p>Now let's take these ranges and create a filtered index that will cover our query:</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_SalesOrderDetail_filtered
    <span style="color: #0000FF;">On</span> Sales.<span style="color: #202020;">SalesOrderDetail</span><span style="color: #808080;">&#40;</span>ModifiedDate, ProductID<span style="color: #808080;">&#41;</span>
    Include <span style="color: #808080;">&#40;</span>SalesOrderID<span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">Where</span> SalesOrderDetailID <span style="color: #808080;">&gt;=</span> <span style="color: #000;">75000</span>
      And SalesOrderDetailID <span style="color: #808080;">&lt;</span>  <span style="color: #000;">121317</span>;</pre></div></div>

<p>By having this range identified, SQL Server can perform a seek on the clustered index to create the nonclustered index on just the subset of records that you need for your query.  Remember that 8.5 billion row table I mentioned earlier?  I was able to create a filtered index that covered my query in 10 seconds.  Yes, that's right... 10 SECONDS.  </p>
<p>The last thing we need to do is include our filtered index definition in our ad hoc query to ensure that the filtered index is used.  It also doesn't hurt to explicitly tell SQL Server to use the filtered index if you're absolutely sure it's the best index for the job.</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">Select</span> <span style="color: #FF00FF;">Count</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">Distinct</span> sod.<span style="color: #202020;">SalesOrderID</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">As</span> <span style="color: #FF0000;">'distinctCount'</span>
<span style="color: #0000FF;">From</span> AdventureWorks2008R2.<span style="color: #202020;">Sales</span>.<span style="color: #202020;">SalesOrderDetail</span> <span style="color: #0000FF;">As</span> sod <span style="color: #0000FF;">With</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">Index</span><span style="color: #808080;">&#40;</span>IX_SalesOrderDetail_filtered<span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>
Join AdventureWorks2008R2.<span style="color: #202020;">Production</span>.<span style="color: #202020;">Product</span> <span style="color: #0000FF;">As</span> p
    <span style="color: #0000FF;">On</span> sod.<span style="color: #202020;">ProductID</span> <span style="color: #808080;">=</span> p.<span style="color: #202020;">ProductID</span>
<span style="color: #0000FF;">Where</span> sod.<span style="color: #202020;">ModifiedDate</span> Between <span style="color: #FF0000;">'2008-01-01'</span> And <span style="color: #FF0000;">'2008-07-31'</span>
    And p.<span style="color: #202020;">MakeFlag</span> <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
    And sod.<span style="color: #202020;">SalesOrderDetailID</span> <span style="color: #808080;">&gt;=</span> <span style="color: #000;">75000</span>
    And sod.<span style="color: #202020;">SalesOrderDetailID</span> <span style="color: #808080;">&lt;</span>  <span style="color: #000;">121317</span>;</pre></div></div>

<p>That's all there is to it.  Using this method, I was able to complete my ad hoc request in 40 seconds: 10 seconds to create the filtered index and 30 seconds to actually execute the ad hoc.  Of course, it also took a couple of minutes to write the query, look at existing indexes, and search for the correct identity values.  All in all, from the time I received the request to the time I send the e-mail was about 5 minutes.  All because of disposable filtered indexes.  How's that for some SQL #awesomesauce?  <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/12/disposable-indexes/feed/</wfw:commentRss>
		<slash:comments>10</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[UPDATE: This script has been updated. Please view the latest version at http://sqlfool.com/2011/06/index-defrag-script-v4-1/. 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 [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p><strong>UPDATE:  </strong>This script has been updated. Please view the latest version at <a href="http://sqlfool.com/2011/06/index-defrag-script-v4-1/">http://sqlfool.com/2011/06/index-defrag-script-v4-1/</a>.</p></blockquote>
<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>
<blockquote><p><strong>UPDATE:  </strong>This script has been updated. Please view the latest version at <a href="http://sqlfool.com/2011/06/index-defrag-script-v4-1/">http://sqlfool.com/2011/06/index-defrag-script-v4-1/</a>.
</p></blockquote>

<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>94</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>#PASSAwesomeness</title>
		<link>http://sqlfool.com/2009/10/passawesomeness/</link>
		<comments>http://sqlfool.com/2009/10/passawesomeness/#comments</comments>
		<pubDate>Fri, 30 Oct 2009 01:39:22 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Miscellaneous]]></category>
		<category><![CDATA[PASS]]></category>
		<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[Presentations]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[380PASS]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[Summit]]></category>
		<category><![CDATA[Super Bowl]]></category>
		<category><![CDATA[VLDB]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1202</guid>
		<description><![CDATA[Allen Kinsel on Twitter (@sqlinsaneo) recently started a new Twitter tag, #PASSAwesomeness, about all of the cool things about PASS Summit. I really like the tag, so I'm going to blatantly steal borrow it for this post. First, and long overdue, I want to give a brief recap of the East Iowa SQL Saturday. On [...]]]></description>
			<content:encoded><![CDATA[<p>Allen Kinsel on Twitter (<a href="http://twitter.com/sqlinsaneo" target="_blank">@sqlinsaneo</a>) recently started a new Twitter tag, <a href="http://twitter.com/#search?q=%23passawesomeness" target="_blank">#PASSAwesomeness</a>, about all of the cool things about <a href="http://summit2009.sqlpass.org" target="_blank">PASS Summit</a>.  I really like the tag, so I'm going to <span style="text-decoration: line-through;">blatantly steal</span> borrow it for this post.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>First, and long overdue, I want to give a brief recap of the <a href="http://sqlsaturday.380pass.org" target="_blank">East Iowa SQL Saturday</a>.  On October 17th, our local PASS chapter, <a href="http://380pass.org" target="_blank">380PASS</a>, sponsored our first ever SQL Saturday at the University of Iowa in Iowa City.  By all accounts, the event was a great success!  We had 90 attendees, 11 speakers, and 21 sessions.  We received numerous compliments on the quality of the speakers, the niceness of the facilities, and the abundance of food.  Not too shabby for our first time hosting the event, if I do say so myself.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>I'd like to thank all of our wonderful speakers, especially those who traveled from out of town and out of state, for making this event such a success.  I'd also like to thank our amazing volunteers for helping put this all together.  Lastly, but certainly not least, I'd like to thank our generous sponsors, without whom this event would not be possible.  Because this event went so smoothly and was so well received in the community, we've already started planning our next big SQL event!  In the meantime, don't forget to check out our monthly <a href="http://380pass.org" target="_blank">380PASS</a> meetings to tide you over.  </p>
<p>I'd also like to take a moment to discuss the <a href="http://summit2009.sqlpass.org/" target="_blank">PASS Summit</a>.  Unless you're a DBA who's been living under a rock, you've probably heard of the PASS Summit.  If you *have* been living under a rock -- and hey, I'm not poking fun, I used to live under a rock, too!  -- then what you need to know is that the Summit is the largest SQL Server conference in the world.  It's a gathering of Microsoft developers and SQL Server gurus; the rest of us show up to try to absorb as much from them as possible.  Since I've <a href="http://sqlfool.com/2009/08/getting-started-with-variables-in-ssis/" target="_blank">recently moved to the Business Intelligence team</a>, I'm extremely excited to delve into the <a href="http://summit2009.sqlpass.org/Agenda/ProgramSessions.aspx" target="_blank">amazing amount of BI content offered</a>.</p>
<p>I'm also deeply honored to be presenting at the Summit this year on some of the performance tuning techniques I've used with great success in my production environments.  The session is titled, <a href="http://summit2009.sqlpass.org/Agenda/ProgramSessions/SuperBowlSuperLoadALookatPerformance.aspx" target="_blank">Super Bowl, Super Load - A Look At Performance Tuning for VLDB's</a>.  If you're interested in performance tuning or VLDB (very large database) topics, consider stopping by to catch my session.  From what I can tell, I'll be presenting on Tuesday from 10:15am - 11:30am in room(s?) 602-604.  </p>
<p>If you read my blog, or if we've ever interacted in any way on the internet -- <a href="http://twitter.com/sqlfool" target="_blank">Twitter</a>, LinkedIn, e-mails, blog comments, etc. -- please stop by and say "hi"!  Aside from all of the awesome SQL Server content, I'm really looking forward to meeting as many new folks as possible.  </p>
<p>And on that note... </p>
<p>Getting to meet all of the amazing SQL Server professionals out there who have inspired and encouraged me in so many ways <a href="http://twitter.com/#search?q=%23passawesomeness" target="_blank">#PASSAwesomeness</a></p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/10/passawesomeness/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Partitioning Tricks</title>
		<link>http://sqlfool.com/2009/10/partitioning-tricks/</link>
		<comments>http://sqlfool.com/2009/10/partitioning-tricks/#comments</comments>
		<pubDate>Fri, 09 Oct 2009 19:12:35 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Miscellaneous]]></category>
		<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[compression]]></category>
		<category><![CDATA[partitioning]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1195</guid>
		<description><![CDATA[For those of you who are using partitioning, or who are considering using partitioning, allow me to share some tips with you. Easy Partition Staging Tables Switching partitions (or more specifically, hobts) in and out of a partitioned table requires the use of a staging table. The staging table has very specific requirements: it must [...]]]></description>
			<content:encoded><![CDATA[<p>For those of you who are using partitioning, or who are considering using partitioning, allow me to share some tips with you.</p>
<p><strong>Easy Partition Staging Tables</strong></p>
<p>Switching partitions (or more specifically, hobts) in and out of a partitioned table requires the use of a staging table.  The staging table has very specific requirements: it must be completely identical to the partitioned table, including indexing structures, and it must have a check constraint that limits data to the partitioning range.  Thanks to my co-worker Jeff, I've recently started using the <a href="http://sqlpartitionmgmt.codeplex.com/" target="_blank">SQL Server Partition Management</a> tool on CodePlex.  I haven't used the automatic partition switching feature -- frankly, using any sort of data modification tool in a production environment makes me nervous -- but I've been using the scripting option to create staging tables in my development environment, which I then copy to production for use.  It's nothing you can't do yourself, but it does make the whole process easy and painless, plus it saves you from annoying typos.  But be careful when using this tool to just create the table and check constraints automatically, because you may need to...</p>
<p><strong>Add Check Constraints After Loading Data</strong></p>
<p>Most of the time, I add the check constraint when I create the staging table, then I load data and perform the partition switch.  However, for some reason, I was receiving the following error:</p>
<p><span style="color: #ff0000;">.Net SqlClient Data Provider: Msg 4972, Level 16, State 1, Line 1<br />
ALTER TABLE SWITCH statement failed. Check constraints or partition function of source table 'myStagingTable' allows values that are not allowed by check constraints or partition function on target table 'myDestinationTable'.</span></p>
<p>This drove me crazy.  I confirmed my check constraints were correct, that I had the correct partition number, and that all schema and indexes matched identically.  After about 30 minutes of this, I decided to drop and recreate the constraint.  For some reason, it fixed the issue.  Repeat tests produced the same results:  the check constraint needed to be added *after* data was loaded.  This error is occurring on a SQL Server 2008 SP1 box; to be honest, I'm not sure what's causing the error, so if you know, please leave me a comment.  But I figured I'd share so that anyone else running into this issue can hopefully save some time and headache.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>Replicating Into Partitioned and Non-Partitioned Tables</strong></p>
<p>Recently, we needed to replicate a non-partitioned table to two different destinations.  We wanted to use partitioning for Server A, which has 2008 Enterprise; Server B, which is on 2005 Standard, could not take advantage of partitioning.  The solution was really easy:  create a pre-snapshot and post-snapshot script for the publication, then modify to handle each server group differently.  Using pseudo-code, it looked something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/* Identify which servers get the partitioned version */</span>
<span style="color: #0000FF;">If</span> <span style="color: #FF00FF;">@@ServerName</span> In <span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'yourServerNameList'</span><span style="color: #808080;">&#41;</span> 
<span style="color: #0000FF;">Begin</span>
&nbsp;
    <span style="color: #008080;">/* Create your partitioning scheme if necessary */</span>
    <span style="color: #0000FF;">If</span> Not Exists<span style="color: #808080;">&#40;</span><span style="color: #0000FF;">Select</span> <span style="color: #808080;">*</span> <span style="color: #0000FF;">From</span> sys.<span style="color: #202020;">partition_schemes</span> <span style="color: #0000FF;">Where</span> name <span style="color: #808080;">=</span> <span style="color: #FF0000;">'InsertPartitionScheme'</span><span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">CREATE</span> PARTITION SCHEME InsertPartitionScheme 
            <span style="color: #0000FF;">AS</span> PARTITION InsertPartitionFunction <span style="color: #808080;">ALL</span> <span style="color: #0000FF;">TO</span> <span style="color: #808080;">&#40;</span><span style="color: #808080;">&#91;</span><span style="color: #0000FF;">PRIMARY</span><span style="color: #808080;">&#93;</span><span style="color: #808080;">&#41;</span>;    
&nbsp;
    <span style="color: #008080;">/* Create your partitioning function if necessary */</span>
    <span style="color: #0000FF;">If</span> Not Exists<span style="color: #808080;">&#40;</span><span style="color: #0000FF;">Select</span> <span style="color: #808080;">*</span> <span style="color: #0000FF;">From</span> sys.<span style="color: #202020;">partition_functions</span> <span style="color: #0000FF;">Where</span> name <span style="color: #808080;">=</span> <span style="color: #FF0000;">'InsertPartitionFunction'</span><span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">CREATE</span> PARTITION <span style="color: #0000FF;">FUNCTION</span> InsertPartitionFunction <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">smalldatetime</span><span style="color: #808080;">&#41;</span> 
            <span style="color: #0000FF;">AS</span> RANGE <span style="color: #0000FF;">RIGHT</span> <span style="color: #0000FF;">FOR</span> <span style="color: #0000FF;">VALUES</span> <span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'insertValues'</span><span style="color: #808080;">&#41;</span>;    
&nbsp;
    <span style="color: #008080;">/* Create a partitioned version of your table */</span>
    <span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> <span style="color: #808080;">&#91;</span>dbo<span style="color: #808080;">&#93;</span>.<span style="color: #808080;">&#91;</span>yourTableName<span style="color: #808080;">&#93;</span> <span style="color: #808080;">&#40;</span>
	    <span style="color: #808080;">&#91;</span>yourTableSchema<span style="color: #808080;">&#93;</span>
    <span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">ON</span> InsertPartitionScheme<span style="color: #808080;">&#40;</span><span style="color: #808080;">&#91;</span>partitioningKey<span style="color: #808080;">&#93;</span><span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">End</span>
<span style="color: #0000FF;">Else</span>
<span style="color: #0000FF;">Begin</span>
&nbsp;
    <span style="color: #008080;">/* Create a non-partitioned version of your table */</span>
    <span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> <span style="color: #808080;">&#91;</span>dbo<span style="color: #808080;">&#93;</span>.<span style="color: #808080;">&#91;</span>yourTableName<span style="color: #808080;">&#93;</span> <span style="color: #808080;">&#40;</span>
	    <span style="color: #808080;">&#91;</span>yourTableSchema<span style="color: #808080;">&#93;</span>
    <span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">ON</span> <span style="color: #808080;">&#91;</span><span style="color: #0000FF;">Primary</span><span style="color: #808080;">&#93;</span>;
&nbsp;
<span style="color: #0000FF;">End</span></pre></div></div>

<p>You could also use an edition check instead of a server name check, if you prefer.  The post-snapshot script basically looked the same, except you create partitioned indexes instead.</p>
<p><strong>Compress Old Partitions</strong></p>
<p>Did you know you can set different compression levels for individual partitions?  It's true!  I've just completed doing this on our largest partitioned table.  Here's how:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/* Apply compression to your partitioned table */</span>
<span style="color: #0000FF;">Alter</span> <span style="color: #0000FF;">Table</span> dbo.<span style="color: #202020;">yourTableName</span>
Rebuild Partition <span style="color: #808080;">=</span> All
<span style="color: #0000FF;">With</span> 
<span style="color: #808080;">&#40;</span>
      Data_Compression <span style="color: #808080;">=</span> Page <span style="color: #0000FF;">On</span> Partitions<span style="color: #808080;">&#40;</span><span style="color: #000;">1</span> <span style="color: #0000FF;">to</span> <span style="color: #000;">9</span><span style="color: #808080;">&#41;</span>
    , Data_Compression <span style="color: #808080;">=</span> <span style="color: #0000FF;">Row</span>  <span style="color: #0000FF;">On</span> Partitions<span style="color: #808080;">&#40;</span><span style="color: #000;">10</span> <span style="color: #0000FF;">to</span> <span style="color: #000;">11</span><span style="color: #808080;">&#41;</span> 
    , Data_Compression <span style="color: #808080;">=</span> <span style="color: #0000FF;">None</span> <span style="color: #0000FF;">On</span> Partitions<span style="color: #808080;">&#40;</span><span style="color: #000;">12</span><span style="color: #808080;">&#41;</span>
<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #008080;">/* Apply compression to your partitioned index */</span>
<span style="color: #0000FF;">Alter</span> <span style="color: #0000FF;">Index</span> YourPartitionedIndex
    <span style="color: #0000FF;">On</span> dbo.<span style="color: #202020;">yourTableName</span>
    Rebuild Partition <span style="color: #808080;">=</span> All
    <span style="color: #0000FF;">With</span> 
    <span style="color: #808080;">&#40;</span>
      Data_Compression <span style="color: #808080;">=</span> Page <span style="color: #0000FF;">On</span> Partitions<span style="color: #808080;">&#40;</span><span style="color: #000;">1</span> <span style="color: #0000FF;">to</span> <span style="color: #000;">9</span><span style="color: #808080;">&#41;</span>
    , Data_Compression <span style="color: #808080;">=</span> <span style="color: #0000FF;">Row</span>  <span style="color: #0000FF;">On</span> Partitions<span style="color: #808080;">&#40;</span><span style="color: #000;">10</span> <span style="color: #0000FF;">to</span> <span style="color: #000;">11</span><span style="color: #808080;">&#41;</span> 
    , Data_Compression <span style="color: #808080;">=</span> <span style="color: #0000FF;">None</span> <span style="color: #0000FF;">On</span> Partitions<span style="color: #808080;">&#40;</span><span style="color: #000;">12</span><span style="color: #808080;">&#41;</span>
    <span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #008080;">/* Apply compression to your unpartitioned index */</span>
<span style="color: #0000FF;">Alter</span> <span style="color: #0000FF;">Index</span> YourUnpartitionedIndex
    <span style="color: #0000FF;">On</span> dbo.<span style="color: #202020;">yourTableName</span>
    Rebuild <span style="color: #0000FF;">With</span> <span style="color: #808080;">&#40;</span>Data_Compression <span style="color: #808080;">=</span> <span style="color: #0000FF;">Row</span><span style="color: #808080;">&#41;</span>;</pre></div></div>

<p>A couple of things to note.  In all of our proof-of-concept testing, we found that compression significantly reduced query execution time, reads (IO), and storage.  However, CPU was also increased significantly.  The results were more dramatic, both good and bad, with page compression versus row compression.  Still, for our older partitions, which aren't queried regularly, it made sense to turn on page compression.  The newer partitions receive row compression, and the newest partitions, which are still queried very regularly by routine processes, were left completely uncompressed.  This seems to strike a nice balance in our environment, but of course, results will vary depending on how you use your data.</p>
<p>Something to be aware of is that compressing your clustered index does *not* compress your non-clustered indexes; those are separate operations.  Lastly, for those who are curious, it took us about 1 minute to apply row compression and about 7 minutes to apply page compression to partitions averaging 30 million rows.</p>
<p>Looking for more information on table partitioning?  Check out my <a href="http://sqlfool.com/2008/11/partitioning-101/" target="_blank">overview of partitioning</a>, my <a href="http://sqlfool.com/2008/11/102/" target="_blank">example code</a>, and my article on <a href="http://sqlfool.com/2008/12/indexing-for-partitioned-tables/" target="_blank">indexing on partitioned tables</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/10/partitioning-tricks/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Monitoring Process for Performance Counters</title>
		<link>http://sqlfool.com/2009/09/monitoring-process-for-performance-counters/</link>
		<comments>http://sqlfool.com/2009/09/monitoring-process-for-performance-counters/#comments</comments>
		<pubDate>Wed, 16 Sep 2009 17:19:12 +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[monitor]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[script]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1161</guid>
		<description><![CDATA[Recently I needed to create a process to monitor performance counters over a short period of time. We were going to implement a change and we wanted to compare performance before and after to see if there was any impact. To do this, I first created a couple of tables. One table is used to [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I needed to create a process to monitor performance counters over a short period of time.  We were going to implement a change and we wanted to compare performance before and after to see if there was any impact.  </p>
<p>To do this, I first created a couple of tables.  One table is used to actually store the monitored values.  The second table is used for configuration; you insert only the counters you want to monitor.</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/* Create the table to store our logged perfmon counters */</span>
<span style="color: #0000FF;">Create</span> <span style="color: #0000FF;">Table</span> dbo.<span style="color: #202020;">dba_perfCounterMonitor</span>
<span style="color: #808080;">&#40;</span>
      capture_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
    , captureDate   <span style="color: #0000FF;">smalldatetime</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
    , counterName   <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
    , instanceName  <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
    , <span style="color: #0000FF;">value</span>         <span style="color: #0000FF;">float</span><span style="color: #808080;">&#40;</span><span style="color: #000;">6</span><span style="color: #808080;">&#41;</span>            Not Null
    , valueType     <span style="color: #0000FF;">nvarchar</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span>        Not Null
&nbsp;
    <span style="color: #0000FF;">Constraint</span> PK_dba_perfCounterMonitor
        <span style="color: #0000FF;">Primary</span> <span style="color: #0000FF;">Key</span> <span style="color: #0000FF;">Clustered</span><span style="color: #808080;">&#40;</span>capture_id<span style="color: #808080;">&#41;</span>
<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #008080;">/* Create the table that controls which counters we're going to monitor */</span>
<span style="color: #0000FF;">Create</span> <span style="color: #0000FF;">Table</span> dbo.<span style="color: #202020;">dba_perfCounterMonitorConfig</span>
<span style="color: #808080;">&#40;</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>   Not Null
    , counterName   <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
    , instanceName  <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
<span style="color: #808080;">&#41;</span>;</pre></div></div>

<p>If you leave the instanceName NULL in the config table, it'll monitor all instances.  Now we're going to insert some sample performance counters into the config table.  The counters you're interested in can, and likely will, vary.</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/* Insert some perfmon counters to be monitored */</span>
<span style="color: #0000FF;">Insert</span> <span style="color: #0000FF;">Into</span> dbo.<span style="color: #202020;">dba_perfCounterMonitorConfig</span>
<span style="color: #0000FF;">Select</span> <span style="color: #FF0000;">'SQLServer:Buffer Manager'</span>, <span style="color: #FF0000;">'Page Life Expectancy'</span>, Null <span style="color: #0000FF;">Union</span> All
<span style="color: #0000FF;">Select</span> <span style="color: #FF0000;">'SQLServer:Locks'</span>, <span style="color: #FF0000;">'Lock Requests/sec'</span>, Null <span style="color: #0000FF;">Union</span> All
<span style="color: #0000FF;">Select</span> <span style="color: #FF0000;">'SQLServer:Locks'</span>, <span style="color: #FF0000;">'Lock Waits/sec'</span>, Null <span style="color: #0000FF;">Union</span> All
<span style="color: #0000FF;">Select</span> <span style="color: #FF0000;">'SQLServer:Locks'</span>, <span style="color: #FF0000;">'Lock Wait Time (ms)'</span>, Null <span style="color: #0000FF;">Union</span> All
<span style="color: #0000FF;">Select</span> <span style="color: #FF0000;">'SQLServer:Buffer Manager'</span>, <span style="color: #FF0000;">'Page reads/sec'</span>, Null <span style="color: #0000FF;">Union</span> All
<span style="color: #0000FF;">Select</span> <span style="color: #FF0000;">'SQLServer:Buffer Manager'</span>, <span style="color: #FF0000;">'Page writes/sec'</span>, Null <span style="color: #0000FF;">Union</span> All
<span style="color: #0000FF;">Select</span> <span style="color: #FF0000;">'SQLServer:Buffer Manager'</span>, <span style="color: #FF0000;">'Buffer cache hit ratio'</span>, Null <span style="color: #0000FF;">Union</span> All
<span style="color: #0000FF;">Select</span> <span style="color: #FF0000;">'SQLServer:Databases'</span>, <span style="color: #FF0000;">'Transactions/sec'</span>, <span style="color: #FF0000;">'AdventureWorks'</span> <span style="color: #0000FF;">Union</span> All
<span style="color: #0000FF;">Select</span> <span style="color: #FF0000;">'SQLServer:General Statistics'</span>, <span style="color: #FF0000;">'Processes blocked'</span>, Null;</pre></div></div>

<p>Now let's create our proc.  This proc will run for a specified time period and will *average* the counters over that time.  I personally take snapshots every 15 seconds for 4 minutes; I have a scheduled task that runs this every 5 minutes.  It's not perfect, but it gives me a good idea of what's happening on the server.</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;">Procedure</span> dbo.<span style="color: #202020;">dba_perfCounterMonitor_sp</span>
&nbsp;
        <span style="color: #008080;">/* Declare Parameters */</span>
          @samplePeriod    <span style="color: #0000FF;">int</span>      <span style="color: #808080;">=</span>  <span style="color: #000;">240</span>  <span style="color: #008080;">/* how long to sample, in seconds */</span>
        , @sampleRate      <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:15'</span>  <span style="color: #008080;">/* how frequently to sample, in seconds */</span>
        , @displayResults  <span style="color: #0000FF;">bit</span>      <span style="color: #808080;">=</span>  <span style="color: #000;">0</span>  <span style="color: #008080;">/* display the results when done */</span>
<span style="color: #0000FF;">As</span>
<span style="color: #008080;">/*********************************************************************************
    Name:       dba_perfCounterMonitor_sp
&nbsp;
    Author:     Michelle Ufford, http://sqlfool.com
&nbsp;
    Purpose:    Monitors performance counters.  Uses the dba_perfCounterMonitorConfig
                table to manage which perf counters to monitor.  
&nbsp;
                @samplePeriod - specifies how long the process will try to monitor
                                performance counters; in seconds.
&nbsp;
                @sampleRate - how long inbetween samples; in seconds.
&nbsp;
                The average values over sample period is then logged to the
                dba_perfCounterMonitor table.
&nbsp;
    Notes:      There are 3 basic types of performance counter calculations:
&nbsp;
                Value/Base: these calculations require 2 counters. The value 
                            counter (cntr_type = 537003264) has to be divided 
                            by the base counter (cntr_type = 1073939712).
&nbsp;
                Per Second: these counters are store cumulative values; the
                            value must be compared at 2 different times to
                            calculate the difference (cntr_type = 537003264).
&nbsp;
                Point In Time:  these counters show what the value of the
                                counter is at the current point-in-time 
                                (cntr_type = 65792).  No calculation is 
                                necessary to derive the value.
&nbsp;
    Called by:  DBA
&nbsp;
    Date        User    Description
    ----------------------------------------------------------------------------
    2009-09-04  MFU     Initial Release
*********************************************************************************
    Exec dbo.dba_perfCounterMonitor_sp
          @samplePeriod     = 60
        , @sampleRate       = '00:00:01'
        , @displayResults   = 1;
*********************************************************************************/</span>
&nbsp;
<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> Ansi_Padding <span style="color: #0000FF;">On</span>;
<span style="color: #0000FF;">Set</span> Ansi_Warnings <span style="color: #0000FF;">On</span>;
<span style="color: #0000FF;">Set</span> ArithAbort <span style="color: #0000FF;">On</span>;
<span style="color: #0000FF;">Set</span> Concat_Null_Yields_Null <span style="color: #0000FF;">On</span>;
<span style="color: #0000FF;">Set</span> Numeric_RoundAbort <span style="color: #0000FF;">Off</span>;
&nbsp;
<span style="color: #0000FF;">Begin</span>
&nbsp;
    <span style="color: #008080;">/* Declare Variables */</span>
    <span style="color: #0000FF;">Declare</span> @startTime <span style="color: #0000FF;">datetime</span>
        , @endTime <span style="color: #0000FF;">datetime</span>
        , @iteration <span style="color: #0000FF;">int</span>;
&nbsp;
    <span style="color: #0000FF;">Select</span> @startTime <span style="color: #808080;">=</span> <span style="color: #FF00FF;">GetDate</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>
        , @iteration <span style="color: #808080;">=</span> <span style="color: #000;">1</span>;
&nbsp;
    <span style="color: #0000FF;">Declare</span> @samples <span style="color: #0000FF;">Table</span>
    <span style="color: #808080;">&#40;</span>
          iteration     <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
        , counterName   <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
        , instanceName  <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
        , cntr_value    <span style="color: #0000FF;">float</span>           Not Null
        , base_value    <span style="color: #0000FF;">float</span>           Null
        , cntr_type     <span style="color: #0000FF;">bigint</span>          Not Null
    <span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #0000FF;">Begin</span> Try
&nbsp;
        <span style="color: #008080;">/* Start a new transaction */</span>
        <span style="color: #0000FF;">Begin</span> <span style="color: #0000FF;">Transaction</span>;
&nbsp;
        <span style="color: #008080;">/* Grab all of our counters */</span>
        <span style="color: #0000FF;">Insert</span> <span style="color: #0000FF;">Into</span> @samples
        <span style="color: #0000FF;">Select</span> @iteration
            , <span style="color: #FF00FF;">RTrim</span><span style="color: #808080;">&#40;</span>dopc.<span style="color: #FF00FF;">object_name</span><span style="color: #808080;">&#41;</span>
            , <span style="color: #FF00FF;">RTrim</span><span style="color: #808080;">&#40;</span>dopc.<span style="color: #202020;">counter_name</span><span style="color: #808080;">&#41;</span>
            , <span style="color: #FF00FF;">RTrim</span><span style="color: #808080;">&#40;</span>dopc.<span style="color: #202020;">instance_name</span><span style="color: #808080;">&#41;</span>
            , <span style="color: #FF00FF;">RTrim</span><span style="color: #808080;">&#40;</span>dopc.<span style="color: #202020;">cntr_value</span><span style="color: #808080;">&#41;</span>
            , <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">Select</span> cntr_value <span style="color: #0000FF;">From</span> sys.<span style="color: #202020;">dm_os_performance_counters</span> <span style="color: #0000FF;">As</span> dopc1
                <span style="color: #0000FF;">Where</span> dopc1.<span style="color: #FF00FF;">object_name</span> <span style="color: #808080;">=</span> pcml.<span style="color: #202020;">objectName</span>
                And dopc1.<span style="color: #202020;">counter_name</span> <span style="color: #808080;">=</span> pcml.<span style="color: #202020;">counterName</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">' base'</span>
                And dopc1.<span style="color: #202020;">instance_name</span> <span style="color: #808080;">=</span> IsNull<span style="color: #808080;">&#40;</span>pcml.<span style="color: #202020;">instanceName</span>, dopc.<span style="color: #202020;">instance_name</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>
            , dopc.<span style="color: #202020;">cntr_type</span>
        <span style="color: #0000FF;">From</span> sys.<span style="color: #202020;">dm_os_performance_counters</span> <span style="color: #0000FF;">As</span> dopc
        Join dbo.<span style="color: #202020;">dba_perfCounterMonitorConfig</span> <span style="color: #0000FF;">As</span> pcml
            <span style="color: #0000FF;">On</span> dopc.<span style="color: #FF00FF;">object_name</span> <span style="color: #808080;">=</span> pcml.<span style="color: #202020;">objectName</span>
                And dopc.<span style="color: #202020;">counter_name</span> <span style="color: #808080;">=</span> pcml.<span style="color: #202020;">counterName</span>
                And dopc.<span style="color: #202020;">instance_name</span> <span style="color: #808080;">=</span> IsNull<span style="color: #808080;">&#40;</span>pcml.<span style="color: #202020;">instanceName</span>, dopc.<span style="color: #202020;">instance_name</span><span style="color: #808080;">&#41;</span>;
&nbsp;
        <span style="color: #008080;">/* During our sample period, grab our counter values and store the results */</span>
        <span style="color: #0000FF;">While</span> <span style="color: #FF00FF;">GetDate</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">&lt;</span> <span style="color: #FF00FF;">DateAdd</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">second</span>, @samplePeriod, @startTime<span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">Begin</span>
&nbsp;
            <span style="color: #0000FF;">Set</span> @iteration <span style="color: #808080;">=</span> @iteration <span style="color: #808080;">+</span> <span style="color: #000;">1</span>;
&nbsp;
            <span style="color: #0000FF;">Insert</span> <span style="color: #0000FF;">Into</span> @samples
            <span style="color: #0000FF;">Select</span> @iteration
                , <span style="color: #FF00FF;">RTrim</span><span style="color: #808080;">&#40;</span>dopc.<span style="color: #FF00FF;">object_name</span><span style="color: #808080;">&#41;</span>
                , <span style="color: #FF00FF;">RTrim</span><span style="color: #808080;">&#40;</span>dopc.<span style="color: #202020;">counter_name</span><span style="color: #808080;">&#41;</span>
                , <span style="color: #FF00FF;">RTrim</span><span style="color: #808080;">&#40;</span>dopc.<span style="color: #202020;">instance_name</span><span style="color: #808080;">&#41;</span>
                , dopc.<span style="color: #202020;">cntr_value</span>
                , <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">Select</span> cntr_value <span style="color: #0000FF;">From</span> sys.<span style="color: #202020;">dm_os_performance_counters</span> <span style="color: #0000FF;">As</span> dopc1
                    <span style="color: #0000FF;">Where</span> dopc1.<span style="color: #FF00FF;">object_name</span> <span style="color: #808080;">=</span> pcml.<span style="color: #202020;">objectName</span>
                    And dopc1.<span style="color: #202020;">counter_name</span> <span style="color: #808080;">=</span> pcml.<span style="color: #202020;">counterName</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">' base'</span>
                    And dopc1.<span style="color: #202020;">instance_name</span> <span style="color: #808080;">=</span> IsNull<span style="color: #808080;">&#40;</span>pcml.<span style="color: #202020;">instanceName</span>, dopc.<span style="color: #202020;">instance_name</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>
                , dopc.<span style="color: #202020;">cntr_type</span>
            <span style="color: #0000FF;">From</span> sys.<span style="color: #202020;">dm_os_performance_counters</span> <span style="color: #0000FF;">As</span> dopc
            Join dbo.<span style="color: #202020;">dba_perfCounterMonitorConfig</span> <span style="color: #0000FF;">As</span> pcml
                <span style="color: #0000FF;">On</span> dopc.<span style="color: #FF00FF;">object_name</span> <span style="color: #808080;">=</span> pcml.<span style="color: #202020;">objectName</span>
                    And dopc.<span style="color: #202020;">counter_name</span> <span style="color: #808080;">=</span> pcml.<span style="color: #202020;">counterName</span>
                    And dopc.<span style="color: #202020;">instance_name</span> <span style="color: #808080;">=</span> IsNull<span style="color: #808080;">&#40;</span>pcml.<span style="color: #202020;">instanceName</span>, dopc.<span style="color: #202020;">instance_name</span><span style="color: #808080;">&#41;</span>;
&nbsp;
            <span style="color: #008080;">/* Wait for a small delay */</span>
            <span style="color: #0000FF;">WaitFor</span> Delay @sampleRate;
&nbsp;
        <span style="color: #0000FF;">End</span>;
&nbsp;
        <span style="color: #008080;">/* Grab our end time for calculations */</span>
        <span style="color: #0000FF;">Set</span> @endTime <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;">/* Store the average of our point-in-time counters */</span>
        <span style="color: #0000FF;">Insert</span> <span style="color: #0000FF;">Into</span> dbo.<span style="color: #202020;">dba_perfCounterMonitor</span> 
        <span style="color: #808080;">&#40;</span>
			  captureDate
			, objectName
			, counterName
			, instanceName
			, <span style="color: #0000FF;">value</span>
			, valueType
		<span style="color: #808080;">&#41;</span> 
		<span style="color: #0000FF;">Select</span> @startTime
		    , objectName
		    , counterName
		    , instanceName
		    , <span style="color: #FF00FF;">Avg</span><span style="color: #808080;">&#40;</span>cntr_value<span style="color: #808080;">&#41;</span>
		    , <span style="color: #FF0000;">'value'</span>
		<span style="color: #0000FF;">From</span> @samples
		<span style="color: #0000FF;">Where</span> cntr_type <span style="color: #808080;">=</span> <span style="color: #000;">65792</span>
		<span style="color: #0000FF;">Group</span> <span style="color: #0000FF;">By</span> objectName
		    , counterName
		    , instanceName;
&nbsp;
        <span style="color: #008080;">/* Store the average of the value vs the base for cntr_type = 537003264 */</span>
        <span style="color: #0000FF;">Insert</span> <span style="color: #0000FF;">Into</span> dbo.<span style="color: #202020;">dba_perfCounterMonitor</span> 
        <span style="color: #808080;">&#40;</span>
			  captureDate
			, objectName
			, counterName
			, instanceName
			, <span style="color: #0000FF;">value</span>
			, valueType
		<span style="color: #808080;">&#41;</span> 
		<span style="color: #0000FF;">Select</span> @startTime
		    , objectName
		    , counterName
		    , instanceName
		    , <span style="color: #FF00FF;">Avg</span><span style="color: #808080;">&#40;</span>cntr_value<span style="color: #808080;">&#41;</span><span style="color: #808080;">/</span><span style="color: #FF00FF;">Avg</span><span style="color: #808080;">&#40;</span>IsNull<span style="color: #808080;">&#40;</span>base_value, <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>
		    , <span style="color: #FF0000;">'percent'</span>
		<span style="color: #0000FF;">From</span> @samples
		<span style="color: #0000FF;">Where</span> cntr_type <span style="color: #808080;">=</span> <span style="color: #000;">537003264</span>
		<span style="color: #0000FF;">Group</span> <span style="color: #0000FF;">By</span> objectName
		    , counterName
		    , instanceName;
&nbsp;
        <span style="color: #008080;">/* Compare the first and last values for our cumulative, per-second counters */</span>
        <span style="color: #0000FF;">Insert</span> <span style="color: #0000FF;">Into</span> dbo.<span style="color: #202020;">dba_perfCounterMonitor</span> 
        <span style="color: #808080;">&#40;</span>
			  captureDate
			, objectName
			, counterName
			, instanceName
			, <span style="color: #0000FF;">value</span>
			, valueType
		<span style="color: #808080;">&#41;</span> 
		<span style="color: #0000FF;">Select</span> @startTime
		    , objectName
		    , counterName
		    , instanceName
		    , <span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">Max</span><span style="color: #808080;">&#40;</span>cntr_value<span style="color: #808080;">&#41;</span> <span style="color: #808080;">-</span> <span style="color: #FF00FF;">Min</span><span style="color: #808080;">&#40;</span>cntr_value<span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">/</span> <span style="color: #FF00FF;">DateDiff</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">second</span>, @startTime, @endTime<span style="color: #808080;">&#41;</span>
		    , <span style="color: #FF0000;">'value'</span>
		<span style="color: #0000FF;">From</span> @samples
		<span style="color: #0000FF;">Where</span> cntr_type <span style="color: #808080;">=</span> <span style="color: #000;">272696576</span>
        <span style="color: #0000FF;">Group</span> <span style="color: #0000FF;">By</span> objectName
		    , counterName
		    , instanceName;
&nbsp;
        <span style="color: #008080;">/* Should we display the results of our most recent execution?  */</span>
        <span style="color: #0000FF;">If</span> @displayResults <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
            <span style="color: #0000FF;">Select</span> captureDate
                , objectName
                , counterName
                , instanceName
                , <span style="color: #0000FF;">value</span>
                , valueType
            <span style="color: #0000FF;">From</span> dbo.<span style="color: #202020;">dba_perfCounterMonitor</span> <span style="color: #0000FF;">With</span> <span style="color: #808080;">&#40;</span>NoLock<span style="color: #808080;">&#41;</span>
            <span style="color: #0000FF;">Where</span> captureDate <span style="color: #808080;">=</span> <span style="color: #0000FF;">Cast</span><span style="color: #808080;">&#40;</span>@startTime <span style="color: #0000FF;">As</span> <span style="color: #0000FF;">smalldatetime</span><span style="color: #808080;">&#41;</span>
            <span style="color: #0000FF;">Order</span> <span style="color: #0000FF;">By</span> objectName
                , counterName
                , instanceName;
&nbsp;
        <span style="color: #008080;">/* If you have an open transaction, commit it */</span>
        <span style="color: #0000FF;">If</span> <span style="color: #FF00FF;">@@TranCount</span> <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span>
            <span style="color: #0000FF;">Commit</span> <span style="color: #0000FF;">Transaction</span>;
&nbsp;
    <span style="color: #0000FF;">End</span> Try
    <span style="color: #0000FF;">Begin</span> Catch
&nbsp;
        <span style="color: #008080;">/* Whoops, there was an error... rollback! */</span>
        <span style="color: #0000FF;">If</span> <span style="color: #FF00FF;">@@TranCount</span> <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span>
            <span style="color: #0000FF;">Rollback</span> <span style="color: #0000FF;">Transaction</span>;
&nbsp;
        <span style="color: #008080;">/* Return an error message and log it */</span>
        <span style="color: #0000FF;">Execute</span> dbo.<span style="color: #202020;">dba_logError_sp</span>;
&nbsp;
    <span style="color: #0000FF;">End</span> Catch;
&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>
Go</pre></div></div>

<p>Like I said, it's not perfect, but it gets the job done.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Getting an error about dba_logError_sp?  Take a look at my <a href="http://sqlfool.com/2008/12/error-handling-in-t-sql/" target="_blank">error handling proc</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/09/monitoring-process-for-performance-counters/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Overhead in Non-Unique Clustered Indexes</title>
		<link>http://sqlfool.com/2009/05/overhead-i-non-unique-clustered-indexes/</link>
		<comments>http://sqlfool.com/2009/05/overhead-i-non-unique-clustered-indexes/#comments</comments>
		<pubDate>Thu, 21 May 2009 13:22:29 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Internals]]></category>
		<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[indexes]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=961</guid>
		<description><![CDATA[I've received a couple of questions regarding my article, Performance Considerations of Data Types, and the overhead associated with non-unique clustered indexes. I started to respond via e-mail, but my response was so long I decided to turn it into a blog post instead. I should start by clarifying that non-unique clustered indexes do not [...]]]></description>
			<content:encoded><![CDATA[<p>I've received a couple of questions regarding my article, <a href="http://sqlfool.com/2009/05/performance-considerations-of-data-types/" target="_blank">Performance Considerations of Data Types</a>, and the overhead associated with non-unique clustered indexes.  I started to respond via e-mail, but my response was so long I decided to turn it into a blog post instead.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>I should start by clarifying that <strong>non-unique clustered indexes do not necessarily consume more space and overhead</strong>; it depends on the data stored.  If you have duplicate clustered key values, the first instance of the value will be handled as though it were unique.  Any subsequent values, however, will incur overhead to manage the uniquifier that SQL Server adds to maintain row uniqueness.  This same overhead is also incurred in non-clustered indexes, too, adding to the overall expense of this approach.</p>
<p>I think it helps to actually look at the data, so let's walk through a few different common scenarios.  We'll create a table with a unique clustered index, a table with a non-unique clustered index but no duplicates, and a table with duplicate key values.  </p>
<p>Also, a little warning that I started to write this in SQL Server 2008, and since I'm on a 2008 kick, I decided to leave it that way.  You can modify this pretty easily to work in 2005, if necessary.</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">Use</span> sandbox;
Go
&nbsp;
<span style="color: #008080;">/* Unique, clustered index, no duplicate values */</span>
<span style="color: #0000FF;">Create</span> <span style="color: #0000FF;">Table</span> dbo.<span style="color: #202020;">uniqueClustered</span>
<span style="color: #808080;">&#40;</span>
      myDate    <span style="color: #0000FF;">date</span>        Not Null
    , myNumber  <span style="color: #0000FF;">int</span>         Not Null
    , myColumn  <span style="color: #0000FF;">char</span><span style="color: #808080;">&#40;</span><span style="color: #000;">995</span><span style="color: #808080;">&#41;</span>   Not Null
<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">Create</span> <span style="color: #0000FF;">Unique</span> <span style="color: #0000FF;">Clustered</span> <span style="color: #0000FF;">Index</span> CIX_uniqueClustered
    <span style="color: #0000FF;">On</span> dbo.<span style="color: #202020;">uniqueClustered</span><span style="color: #808080;">&#40;</span>myDate<span style="color: #808080;">&#41;</span>;
&nbsp;
&nbsp;
<span style="color: #008080;">/* Non-unique clustered index, but no duplicate values */</span>
<span style="color: #0000FF;">Create</span> <span style="color: #0000FF;">Table</span> dbo.<span style="color: #202020;">nonUniqueNoDups</span>
<span style="color: #808080;">&#40;</span>
      myDate    <span style="color: #0000FF;">date</span>        Not Null
    , myNumber  <span style="color: #0000FF;">int</span>         Not Null
    , myColumn  <span style="color: #0000FF;">char</span><span style="color: #808080;">&#40;</span><span style="color: #000;">995</span><span style="color: #808080;">&#41;</span>   Not Null
<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">Create</span> <span style="color: #0000FF;">Clustered</span> <span style="color: #0000FF;">Index</span> CIX_nonUniqueNoDups
    <span style="color: #0000FF;">On</span> dbo.<span style="color: #202020;">nonUniqueNoDups</span><span style="color: #808080;">&#40;</span>myDate<span style="color: #808080;">&#41;</span>;
&nbsp;
&nbsp;
<span style="color: #008080;">/* Non-unique clustered index, duplicate values */</span>
<span style="color: #0000FF;">Create</span> <span style="color: #0000FF;">Table</span> dbo.<span style="color: #202020;">nonUniqueDuplicates</span>
<span style="color: #808080;">&#40;</span>
      myDate    <span style="color: #0000FF;">date</span>        Not Null
    , myNumber  <span style="color: #0000FF;">int</span>         Not Null
    , myColumn  <span style="color: #0000FF;">char</span><span style="color: #808080;">&#40;</span><span style="color: #000;">995</span><span style="color: #808080;">&#41;</span>   Not Null
<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">Create</span> <span style="color: #0000FF;">Clustered</span> <span style="color: #0000FF;">Index</span> CIX_nonUniqueDuplicates
    <span style="color: #0000FF;">On</span> dbo.<span style="color: #202020;">nonUniqueDuplicates</span><span style="color: #808080;">&#40;</span>myDate<span style="color: #808080;">&#41;</span>;</pre></div></div>

<p>I'm going to use the <a href="http://msdn.microsoft.com/en-us/library/bb630352.aspx" target="_blank">date</a> data type in 2008 for my clustered index key.  To ensure uniqueness for the first two tables, I'll iterate through a few years' worth of dates.  This is typical of what you may see in a data mart, where you'd have one record with an aggregation of each day's data.  For the table with duplicate values, I'm going to insert the same date for each row.</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/* Populate some test data */</span>
<span style="color: #0000FF;">Set</span> <span style="color: #0000FF;">NoCount</span> <span style="color: #0000FF;">On</span>;
<span style="color: #0000FF;">Declare</span> @myDate <span style="color: #0000FF;">date</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'1990-01-01'</span>
    , @myNumber <span style="color: #0000FF;">int</span> <span style="color: #808080;">=</span> <span style="color: #000;">1</span>;
&nbsp;
<span style="color: #0000FF;">While</span> @myDate <span style="color: #808080;">&lt;</span> <span style="color: #FF0000;">'2010-01-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;">uniqueClustered</span>
    <span style="color: #0000FF;">Select</span> @myDate, @myNumber, <span style="color: #FF0000;">'data'</span>;
&nbsp;
    <span style="color: #0000FF;">Insert</span> <span style="color: #0000FF;">Into</span> dbo.<span style="color: #202020;">nonUniqueNoDups</span>
    <span style="color: #0000FF;">Select</span> @myDate, @myNumber, <span style="color: #FF0000;">'data'</span>;
&nbsp;
    <span style="color: #0000FF;">Insert</span> <span style="color: #0000FF;">Into</span> dbo.<span style="color: #202020;">nonUniqueDuplicates</span>
    <span style="color: #0000FF;">Select</span> <span style="color: #FF0000;">'2009-01-01'</span>, @myNumber, <span style="color: #FF0000;">'data'</span>;
&nbsp;
    <span style="color: #0000FF;">Select</span> @myDate <span style="color: #808080;">=</span> <span style="color: #FF00FF;">DateAdd</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">day</span>, <span style="color: #000;">1</span>, @myDate<span style="color: #808080;">&#41;</span>
        , @myNumber <span style="color: #808080;">+=</span> <span style="color: #000;">1</span>;
&nbsp;
<span style="color: #0000FF;">End</span>;</pre></div></div>

<p>After running the above script, each table should have 7,305 records.  This is obviously pretty small for a table, but it'll serve our purposes.  Now let's take a look at the size of our tables:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/* Look at the details of our indexes */</span>
&nbsp;
<span style="color: #008080;">/* Unique, clustered index, no duplicate values */</span>
<span style="color: #0000FF;">Select</span> <span style="color: #FF0000;">'unique'</span> <span style="color: #0000FF;">As</span> <span style="color: #FF0000;">'type'</span>, page_count, avg_page_space_used_in_percent, record_count
    , min_record_size_in_bytes, max_record_size_in_bytes
<span style="color: #0000FF;">From</span> sys.<span style="color: #202020;">dm_db_index_physical_stats</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">DB_ID</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>, <span style="color: #FF00FF;">Object_ID</span><span style="color: #808080;">&#40;</span>N<span style="color: #FF0000;">'uniqueClustered'</span><span style="color: #808080;">&#41;</span>, Null, Null, N<span style="color: #FF0000;">'Detailed'</span><span style="color: #808080;">&#41;</span> 
<span style="color: #0000FF;">Where</span> index_level <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
<span style="color: #0000FF;">Union</span> All
<span style="color: #008080;">/* Non-unique clustered index, but no duplicate values */</span>
<span style="color: #0000FF;">Select</span> <span style="color: #FF0000;">'non-unique, no dups'</span>, page_count, avg_page_space_used_in_percent, record_count
    , min_record_size_in_bytes, max_record_size_in_bytes
<span style="color: #0000FF;">From</span> sys.<span style="color: #202020;">dm_db_index_physical_stats</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">DB_ID</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>, <span style="color: #FF00FF;">Object_ID</span><span style="color: #808080;">&#40;</span>N<span style="color: #FF0000;">'nonUniqueNoDups'</span><span style="color: #808080;">&#41;</span>, Null, Null, N<span style="color: #FF0000;">'Detailed'</span><span style="color: #808080;">&#41;</span> 
<span style="color: #0000FF;">Where</span> index_level <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
<span style="color: #0000FF;">Union</span> All
<span style="color: #008080;">/* Non-unique clustered index, duplicate values */</span>
<span style="color: #0000FF;">Select</span> <span style="color: #FF0000;">'duplicates'</span>, page_count, avg_page_space_used_in_percent, record_count
    , min_record_size_in_bytes, max_record_size_in_bytes
<span style="color: #0000FF;">From</span> sys.<span style="color: #202020;">dm_db_index_physical_stats</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">DB_ID</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>, <span style="color: #FF00FF;">Object_ID</span><span style="color: #808080;">&#40;</span>N<span style="color: #FF0000;">'nonUniqueDuplicates'</span><span style="color: #808080;">&#41;</span>, Null, Null, N<span style="color: #FF0000;">'Detailed'</span><span style="color: #808080;">&#41;</span> 
<span style="color: #0000FF;">Where</span> index_level <span style="color: #808080;">=</span> <span style="color: #000;">0</span>;</pre></div></div>

<p>Here's the results:</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">type                page_count           avg_page_space_used_in_percent record_count         min_record_size_in_bytes max_record_size_in_bytes
------------------- -------------------- ------------------------------ -------------------- ------------------------ ------------------------
unique              914                  99.8055102545095               7305                 1009                     1009
non-unique, no dups 914                  99.8055102545095               7305                 1009                     1009
duplicates          1044                 88.066036570299                7305                 1009                     1017</pre></div></div>

<p>I want to point out a couple of things.  First, there is no difference in the number of pages between the non-unique clustered index with no duplicates ([nonUniqueNoDups]) and the unique clustered index ([uniqueClustered]).  The table with duplicate clustered key values, however, requires 14% more pages to store the same amount of data.  Secondly, the [max_record_size_in_bytes] of the [nonUniqueDuplicates] table is 8 bytes more than that of the other two.  We'll discuss why in a minute.  </p>
<p>Now let's take a look at the actual data pages.  For this, I'm going to use my <a href="http://sqlfool.com/2009/05/page-internals-investigation-proc/" target="_blank">page internals proc</a>.</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;">Execute dbo<span style="color: #66cc66;">.</span>dba_viewPageData_sp
      @databaseName <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'sandbox'</span>
    <span style="color: #66cc66;">,</span> @tableName    <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'sandbox.dbo.uniqueClustered'</span>
    <span style="color: #66cc66;">,</span> @indexName    <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'CIX_uniqueClustered'</span>;</pre></div></div>

<p>I'm not going to post the entire results here, but I want to draw your attention to "m_slotCnt = 8", which is near the top of the page.  That means 8 records are stored on this page.  Also, when you look near the end of the first record (Slot 0), you should see the following results:</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">Slot 0 Offset 0x60 Length 1009
Record Type = PRIMARY_RECORD         Record Attributes =  NULL_BITMAP     Record Size = 1009
Memory Dump @0x00A9C060
00000000:   1000ee03 c3150b01 00000064 61746120 †..î.Ã......data 
[...]
000003F0:   00†††††††††††††††††††††††††††††††††††.  
&nbsp;
Slot 0 Column 1 Offset 0x4 Length 3 Length (physical) 3
myDate = 1990-01-01                  
&nbsp;
Slot 0 Column 2 Offset 0x7 Length 4 Length (physical) 4
myNumber = 1                         
&nbsp;
Slot 0 Column 3 Offset 0xb Length 995 Length (physical) 995
myColumn = data</pre></div></div>

<p>Now let's look at the table that has a non-unique clustered index but no duplicates:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">Execute</span> dbo.<span style="color: #202020;">dba_viewPageData_sp</span>
      @databaseName <span style="color: #808080;">=</span> <span style="color: #FF0000;">'sandbox'</span>
    , @tableName    <span style="color: #808080;">=</span> <span style="color: #FF0000;">'sandbox.dbo.nonUniqueNoDups'</span>
    , @indexName    <span style="color: #808080;">=</span> <span style="color: #FF0000;">'CIX_nonUniqueNoDups'</span>;</pre></div></div>

<p>The m_slotCnt count is also 8 for this page.  This time, let's glance at the first and second records (Slot 0 and 1 respectively):</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">Slot 0 Offset 0x60 Length 1009
Record Type = PRIMARY_RECORD         Record Attributes =  NULL_BITMAP     Record Size = 1009
Memory Dump @0x62FDC060
00000000:   1000ee03 c3150b01 00000064 61746120 †..î.Ã......data    
[...]
000003F0:   00†††††††††††††††††††††††††††††††††††.                        
&nbsp;
Slot 0 Column 0 Offset 0x0 Length 4 Length (physical) 0
UNIQUIFIER = 0                       
&nbsp;
Slot 0 Column 1 Offset 0x4 Length 3 Length (physical) 3
myDate = 1990-01-01                  
&nbsp;
Slot 0 Column 2 Offset 0x7 Length 4 Length (physical) 4
myNumber = 1                         
&nbsp;
Slot 0 Column 3 Offset 0xb Length 995 Length (physical) 995
myColumn = data
&nbsp;
&nbsp;
Slot 1 Offset 0x451 Length 1009
Record Type = PRIMARY_RECORD         Record Attributes =  NULL_BITMAP     Record Size = 1009
Memory Dump @0x62FDC451
&nbsp;
00000000:   1000ee03 c4150b02 00000064 61746120 †..î.Ä......data          
[...]
000003F0:   00†††††††††††††††††††††††††††††††††††.                        
&nbsp;
Slot 1 Column 0 Offset 0x0 Length 4 Length (physical) 0
UNIQUIFIER = 0                       
&nbsp;
Slot 1 Column 1 Offset 0x4 Length 3 Length (physical) 3
myDate = 1990-01-02                  
&nbsp;
Slot 1 Column 2 Offset 0x7 Length 4 Length (physical) 4
myNumber = 2                         
&nbsp;
Slot 1 Column 3 Offset 0xb Length 995 Length (physical) 995
myColumn = data</pre></div></div>

<p>We now see a new addition to the row, "UNIQUIFIER = 0."  This is SQL Server's way of managing row uniqueness internally.  You'll notice that, because the clustered key values are unique, the UNIQUIFIER is set to 0 and the row size is still 1009; for all intents and purposes, the UNIQUIFIER is not consuming any space.</p>
<p><strong>Update:</strong>  The DBCC God himself, <a href="http://www.sqlskills.com/blogs/paul/" target="_blank">Paul Randal</a>, explained that non-dupes actually have a NULL UNIQUIFIER, which DBCC PAGE displays as a 0.  Thanks for explaining, Paul!  I wondered about that but chalked it up to SQL voodoo.  </p>
<p>Now let's look at our final case, a non-unique clustered index with duplicate key values:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">Execute</span> dbo.<span style="color: #202020;">dba_viewPageData_sp</span>
      @databaseName <span style="color: #808080;">=</span> <span style="color: #FF0000;">'sandbox'</span>
    , @tableName    <span style="color: #808080;">=</span> <span style="color: #FF0000;">'sandbox.dbo.nonUniqueDuplicates'</span>
    , @indexName    <span style="color: #808080;">=</span> <span style="color: #FF0000;">'CIX_nonUniqueDuplicates'</span>;</pre></div></div>

<p>Here's where things get interesting.  The m_slotCnt value is now 7, which means we're now storing 1 record less per page.  Let's look at the details:</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">Slot 0 Offset 0x60 Length 1009
Record Type = PRIMARY_RECORD         Record Attributes =  NULL_BITMAP     Record Size = 1009
Memory Dump @0x00A9C060
00000000:   1000ee03 df300b01 00000064 61746120 †..î.ß0.....data  
[...]
000003F0:   00†††††††††††††††††††††††††††††††††††.                        
&nbsp;
Slot 0 Column 0 Offset 0x0 Length 4 Length (physical) 0
UNIQUIFIER = 0                       
&nbsp;
Slot 0 Column 1 Offset 0x4 Length 3 Length (physical) 3
myDate = 2009-01-01                  
&nbsp;
Slot 0 Column 2 Offset 0x7 Length 4 Length (physical) 4
myNumber = 1                         
&nbsp;
Slot 0 Column 3 Offset 0xb Length 995 Length (physical) 995
myColumn = data
&nbsp;
&nbsp;
Slot 1 Offset 0x451 Length 1017
&nbsp;
Record Type = PRIMARY_RECORD         Record Attributes =  NULL_BITMAP VARIABLE_COLUMNS
Record Size = 1017                   
Memory Dump @0x00A9C451
00000000:   3000ee03 df300b02 00000064 61746120 †0.î.ß0.....data  
[...]
000003F0:   000100f9 03010000 00†††††††††††††††††...ù.....                
&nbsp;
Slot 1 Column 0 Offset 0x3f5 Length 4 Length (physical) 4
UNIQUIFIER = 1                       
&nbsp;
Slot 1 Column 1 Offset 0x4 Length 3 Length (physical) 3
myDate = 2009-01-01                  
&nbsp;
Slot 1 Column 2 Offset 0x7 Length 4 Length (physical) 4
myNumber = 2                         
&nbsp;
Slot 1 Column 3 Offset 0xb Length 995 Length (physical) 995
myColumn = data</pre></div></div>

<p>The first record, Slot 0, looks exactly the same as in the previous table; the UNIQUIFIER is 0 and the row size is 1009.  The second record (Slot 1), however, now has a UNIQUIFIER value of 1 and the row size is 1017.  If you notice, the "Record Attributes" of Slot 1 are also different, with the addition of "VARIABLE_COLUMNS."  This is because the UNIQUIFIER is stored as a variable column.  The extra 8 bytes of overhead break down to 4 bytes to store the UNIQUIFIER, 2 bytes to store the variable column offset, and 2 bytes to store the variable count.  The tables we created used all fixed-length columns; you may notice some minor overhead differences if your table already contains variable columns.</p>
<p>To summarize, there is indeed a difference in the page structure between a unique clustered index and a non-unique clustered index; however, there's only a possible performance and space impact when storing duplicate clustered key values.  So there you go, more detail than you ever wanted to know about clustered indexes and uniqueness!</p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/05/overhead-i-non-unique-clustered-indexes/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Performance Considerations of Data Types</title>
		<link>http://sqlfool.com/2009/05/performance-considerations-of-data-types/</link>
		<comments>http://sqlfool.com/2009/05/performance-considerations-of-data-types/#comments</comments>
		<pubDate>Wed, 13 May 2009 16:55:06 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[PASS]]></category>
		<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[SQL Tips]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[SIG]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=951</guid>
		<description><![CDATA[I've just finished my first real content for the PASS Performance SIG. I decided to write on "Performance Considerations of Data Types," as I think this is one of the easiest and most overlooked topics in performance tuning. Here's a summary: Selecting inappropriate data types, especially on large tables with millions or billions of rows, [...]]]></description>
			<content:encoded><![CDATA[<p>I've just finished my first real content for the PASS Performance SIG.  I decided to write on "Performance Considerations of Data Types," as I think this is one of the easiest and most overlooked topics in performance tuning.  Here's a summary:</p>
<blockquote><p>Selecting inappropriate data types, especially on large tables with millions or billions of rows, can have significant performance implications. In this article, I’ll explain why and offer suggestions on how to select the most appropriate data type for your needs. The primary focus will be on common data types in SQL Server 2005 and 2008, but I’ll also discuss some aspects of clustered indexes and column properties. Most importantly, I’ll show some examples of common data-type misuse.</p></blockquote>
<p>If you're interested in this content, you can find it here: <a href="http://sqlfool.com/content/PerformanceConsiderationsOfDataTypes.pdf" target="_blank">Performance Considerations of Data Types</a>.</p>
<p>Special thanks to <a href="http://www.sqlskills.com/blogs/paul/" target="_blank">Paul Randal</a> and <a href="http://sqlserverbible.com/" target="_blank">Paul Nielsen</a> for providing me with technical reviews and great feedback.  You guys are awesome!</p>
<p>Thanks also to <a href="http://weblogs.sqlteam.com/mladenp/" target="_blank">Mladen Prajdic</a> and <a href="http://facility9.com" target="_blank">Jeremiah Peschka</a> for their great input.  You guys are awesome, too!</p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/05/performance-considerations-of-data-types/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>A Look at Missing Indexes</title>
		<link>http://sqlfool.com/2009/04/a-look-at-missing-indexes/</link>
		<comments>http://sqlfool.com/2009/04/a-look-at-missing-indexes/#comments</comments>
		<pubDate>Tue, 28 Apr 2009 16:30:55 +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[indexes]]></category>
		<category><![CDATA[maintenace]]></category>
		<category><![CDATA[missing indexes]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=868</guid>
		<description><![CDATA[Tim Ford (@SQLAgentMan) recently blogged about his Top 5 SQL Server Indexing Best Practices. I thought it was a good list, and it inspired this blog post. I've recently been doing a little index spring cleaning, and I thought some people may be interested in the process I go through. So, here it is... a [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.ford-it.com/sqlagentman/" target="_blank">Tim Ford</a> (<a href="http://twitter.com/sqlagentman">@SQLAgentMan</a>) recently blogged about his <a href="http://www.ford-it.com/sqlagentman/?p=206" target="_blank">Top 5 SQL Server Indexing Best Practices</a>.  I thought it was a good list, and it inspired this blog post.  I've recently been doing a little index spring cleaning, and I thought some people may be interested in the process I go through.  So, here it is... <span style="text-decoration: line-through;">a journey through madness</span> an overview of my general missing index process.</p>
<p>I start with my trusty dba_missingIndexStoredProc table.  If this table sounds completely foreign to you, check out my post, <a href="http://sqlfool.com/2009/03/find-missing-indexes/" target="_blank">Find Missing Indexes In Stored Procs</a>.  Basically, I have a process that runs every night, scanning the XML of every query plan on the server to find procs that are possibly missing indexes.  I then log the details for later action.</p>
<p>So I take a look at my table, and I find 8 stored procedures that are possibly missing indexes.  Clicking on the XML link will show me the logged query plan:</p>
<div id="attachment_869" class="wp-caption alignnone" style="width: 310px"><a href="http://sqlfool.com/wp-content/uploads/2009/04/20090428_1.jpg" target="_blank"><img src="http://sqlfool.com/wp-content/uploads/2009/04/20090428_1-300x78.jpg" alt="Procs With Missing Indexes" title="20090428_1" width="300" height="78" class="size-medium wp-image-869" /></a><p class="wp-caption-text">Procs With Missing Indexes</p></div>
<p>Right clicking on the "Missing Index" description will give me the details of the recommended index:</p>
<div id="attachment_870" class="wp-caption alignnone" style="width: 310px"><a href="http://sqlfool.com/wp-content/uploads/2009/04/20090428_2.jpg" target="_blank"><img src="http://sqlfool.com/wp-content/uploads/2009/04/20090428_2-300x138.jpg" alt="Missing Index Details" title="20090428_2" width="300" height="138" class="size-medium wp-image-870" /></a><p class="wp-caption-text">Missing Index Details</p></div>
<p>Here's an example of what SQL Server will return for you:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/*
Missing Index Details from ExecutionPlan2.sqlplan
The Query Processor estimates that implementing the following index 
could improve the query cost by 85.7327%.
*/</span>
&nbsp;
<span style="color: #008080;">/*
USE [msdb]
GO
CREATE NONCLUSTERED INDEX [&lt;Name of Missing Index, sysname,&gt;]
ON [dbo].[sysjobhistory] ([job_id])
INCLUDE ([instance_id],[step_id],[sql_message_id],[sql_severity],
[run_status],[run_date],[run_time],[run_duration],[operator_id_emailed], 
[operator_id_netsent],[operator_id_paged],[retries_attempted],[server])
GO
*/</span></pre></div></div>

<p>I now compare the details of this proposed index to the missing index DMV suggestions, using this query:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">SELECT</span> t.<span style="color: #202020;">name</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'affected_table'</span>
    , <span style="color: #FF0000;">'Create NonClustered Index IX_'</span> <span style="color: #808080;">+</span> t.<span style="color: #202020;">name</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">'_missing_'</span> 
        <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>ddmid.<span style="color: #202020;">index_handle</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;">' On '</span> <span style="color: #808080;">+</span> ddmid.<span style="color: #0000FF;">STATEMENT</span> 
        <span style="color: #808080;">+</span> <span style="color: #FF0000;">' ('</span> <span style="color: #808080;">+</span> IsNull<span style="color: #808080;">&#40;</span>ddmid.<span style="color: #202020;">equality_columns</span>,<span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span> 
        <span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> ddmid.<span style="color: #202020;">equality_columns</span> <span style="color: #0000FF;">IS</span> Not Null 
            And ddmid.<span style="color: #202020;">inequality_columns</span> <span style="color: #0000FF;">IS</span> Not Null <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">','</span> 
                <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">''</span> <span style="color: #0000FF;">END</span> 
        <span style="color: #808080;">+</span> IsNull<span style="color: #808080;">&#40;</span>ddmid.<span style="color: #202020;">inequality_columns</span>, <span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>
        <span style="color: #808080;">+</span> <span style="color: #FF0000;">')'</span> 
        <span style="color: #808080;">+</span> IsNull<span style="color: #808080;">&#40;</span><span style="color: #FF0000;">' Include ('</span> <span style="color: #808080;">+</span> ddmid.<span style="color: #202020;">included_columns</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">');'</span>, <span style="color: #FF0000;">';'</span>
        <span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> sql_statement
    , ddmigs.<span style="color: #202020;">user_seeks</span>
    , ddmigs.<span style="color: #202020;">user_scans</span>
    , <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#40;</span>ddmigs.<span style="color: #202020;">user_seeks</span> <span style="color: #808080;">+</span> ddmigs.<span style="color: #202020;">user_scans</span><span style="color: #808080;">&#41;</span> 
        <span style="color: #808080;">*</span> ddmigs.<span style="color: #202020;">avg_user_impact</span> <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">INT</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'est_impact'</span>
    , ddmigs.<span style="color: #202020;">last_user_seek</span>
<span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">dm_db_missing_index_groups</span> <span style="color: #0000FF;">AS</span> ddmig
<span style="color: #0000FF;">INNER</span> <span style="color: #808080;">JOIN</span> sys.<span style="color: #202020;">dm_db_missing_index_group_stats</span> <span style="color: #0000FF;">AS</span> ddmigs
    <span style="color: #0000FF;">ON</span> ddmigs.<span style="color: #202020;">group_handle</span> <span style="color: #808080;">=</span> ddmig.<span style="color: #202020;">index_group_handle</span>
<span style="color: #0000FF;">INNER</span> <span style="color: #808080;">JOIN</span> sys.<span style="color: #202020;">dm_db_missing_index_details</span> <span style="color: #0000FF;">AS</span> ddmid 
    <span style="color: #0000FF;">ON</span> ddmig.<span style="color: #202020;">index_handle</span> <span style="color: #808080;">=</span> ddmid.<span style="color: #202020;">index_handle</span>
<span style="color: #0000FF;">INNER</span> <span style="color: #808080;">JOIN</span> sys.<span style="color: #202020;">tables</span> <span style="color: #0000FF;">AS</span> t
    <span style="color: #0000FF;">ON</span> ddmid.<span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> t.<span style="color: #FF00FF;">OBJECT_ID</span>
<span style="color: #0000FF;">WHERE</span> ddmid.<span style="color: #202020;">database_id</span> <span style="color: #808080;">=</span> <span style="color: #FF00FF;">DB_ID</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>
    <span style="color: #008080;">--AND t.name = 'myTableName' </span>
<span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#40;</span>ddmigs.<span style="color: #202020;">user_seeks</span> <span style="color: #808080;">+</span> ddmigs.<span style="color: #202020;">user_scans</span><span style="color: #808080;">&#41;</span> 
    <span style="color: #808080;">*</span> ddmigs.<span style="color: #202020;">avg_user_impact</span> <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">INT</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">DESC</span>;</pre></div></div>

<p>I usually find the data in both places, but not always.  One reason why is because the missing index DMV will only store data since your last reboot.  So if I'm taking a look at this DMV on Monday and I just rebooted on Sunday, I may not have enough history to give me meaningful recommendations.  This is just something to be aware of.</p>
<p>What I'm looking for in this DMV is the number of user_seeks and the est_impact.  Also, if I haven't rebooted my server in a while, I take a look at last_user_seek so I can determine whether or not it's still accurate.  </p>
<p>Next, I take a look at my existing indexes using Kimberly Tripp's <a href="http://www.sqlskills.com/blogs/Kimberly/post/sp_helpindex2-to-show-included-columns-(20052b)-and-filtered-indexes-(2008)-which-are-not-shown-by-sp_helpindex.aspx" target="_blank">sp_helpindex2</a> system stored proc.  I use her proc instead of sp_helpindex because I need to see included columns.  </p>
<p>If you're wondering why I'm looking at existing indexes, the reason is because I'm looking for indexes that can be modified <em>slightly</em> to accommodate my missing index needs.  By "modified slightly," I mean that I'd only want to make a change to an existing index if it did not drastically change the size or composition of an index, i.e. adding one or two narrow columns as included columns.  I do NOT mean making changes that double the size of your index; in those cases, you'd probably be better off creating a brand new index.  </p>
<p>Looking at existing indexes is actually a pretty critical part of the puzzle.  If I have a proc that only gets called a few times an hour and could benefit from a better index, I may not create that index if it means adding a wide, expensive index to a busy table.  If I can make a small modification to an existing index, then there's a greater chance I'll make the change and cover my query.</p>
<p>At this point, I should have enough information to start making decisions.  I was going to write out the path I normally take when making decisions, but I thought, "Hey!  What a great time for a diagram."  So here you go:</p>
<div id="attachment_873" class="wp-caption alignnone" style="width: 219px"><a href="http://sqlfool.com/wp-content/uploads/2009/04/20090428_tree.jpg" target="_blank"><img src="http://sqlfool.com/wp-content/uploads/2009/04/20090428_tree-209x300.jpg" alt="Decision Path" title="20090428_tree" width="209" height="300" class="size-medium wp-image-873" /></a><p class="wp-caption-text">Decision Path</p></div>
<p><em><strong>Disclaimer:</strong>  I'm *not* a Visio wizard, so if I butchered the use of certain symbols in my diagram, please let me know so I can a) fix it, and b) learn from it!</em></p>
<p>It's hard to really put all of the decision paths into a single, small diagram like this.  There's a lot of variables that I'm not even touching here.  But I think this is a fairly good "generic" representation of the path I take.  When I hit an "end" process, it means I don't create the missing index at this time.  Maybe in the future, it'll become necessary, but I prefer to err on the side of less indexes.  </p>
<p>So there you have it, a brief look at my missing index process.  Hopefully someone finds it helpful.  <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/04/a-look-at-missing-indexes/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
	</channel>
</rss>

