<?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; T-SQL Scripts</title>
	<atom:link href="http://sqlfool.com/category/sql-scripts/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, 03 Feb 2010 22:47:55 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Index Defrag Script Updates &#8211; Beta Testers Needed</title>
		<link>http://sqlfool.com/2010/01/index-defrag-script-updates-beta-testers-needed/</link>
		<comments>http://sqlfool.com/2010/01/index-defrag-script-updates-beta-testers-needed/#comments</comments>
		<pubDate>Tue, 26 Jan 2010 21:15:37 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Miscellaneous]]></category>
		<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[T-SQL Scripts]]></category>
		<category><![CDATA[defrag]]></category>
		<category><![CDATA[defragment]]></category>
		<category><![CDATA[indexes]]></category>
		<category><![CDATA[script]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1298</guid>
		<description><![CDATA[Update:  Wow!  I&#8217;ve received a ton of responses to my request for beta testers.  Thank you all!  The SQL Community is really amazing.  I&#8217;ll hopefully have the new version online in just a few days.   
Over the last few months, I&#8217;ve received many great comments and suggestions regarding [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Update:  </strong>Wow!  I&#8217;ve received a ton of responses to my request for beta testers.  Thank you all!  The SQL Community is really amazing.  I&#8217;ll hopefully have the new version online in just a few days.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Over the last few months, I&#8217;ve received many great comments and suggestions regarding my Index Defrag Script v3.0.  I&#8217;ve just recently had time to implement most of these suggestions, plus some other things that I thought would be useful.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </p>
<p>Here&#8217;s some of what you can look forward to shortly:</p>
<ul>
<li>Probably the single most requested feature, the new version of the script allows you to set a time limit for index defrags.</li>
<li>There&#8217;s now a static table for managing the status of index defrags.  This way, when your time limit is reached, you can pick up where you left off the next day, without the need to rescan indexes.</li>
<li>There&#8217;s now an option to prioritize defrags by range scan counts, fragmentation level, or page counts.</li>
<li>For those using partitioning, there is now an option to exclude the right-most populated partition from defrags (in theory, the one you&#8217;re writing to in a sliding-window scenario).</li>
<li>Options such as page count limits and SORT_IN_TEMPDB are now parameterized.</li>
<li>I&#8217;ve enhanced error logging.</li>
<li>&#8230; and more!</li>
</ul>
<p>Right now, I&#8217;m looking for a few folks who are willing to beta test the script.  If you&#8217;re interested, please send me an e-mail at <em>michelle </em>at <em>sqlfool </em>dot <em>com</em> with the editions of SQL Server you can test this on (i.e. 2005 Standard, 2008 Enterprise, etc.).  </p>
<p>Thank you!  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2010/01/index-defrag-script-updates-beta-testers-needed/feed/</wfw:commentRss>
		<slash:comments>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 [...]]]></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&#8217;ll monitor all instances.  Now we&#8217;re going to insert some sample performance counters into the config table.  The counters you&#8217;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&#8217;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&#8217;s not perfect, but it gives me a good idea of what&#8217;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&#8217;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>Find Recently Executed Stored Procedures</title>
		<link>http://sqlfool.com/2009/08/find-recently-executed-stored-procedures/</link>
		<comments>http://sqlfool.com/2009/08/find-recently-executed-stored-procedures/#comments</comments>
		<pubDate>Mon, 03 Aug 2009 15:14:39 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[SQL Tips]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[T-SQL Scripts]]></category>
		<category><![CDATA[DMV]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[TSQL]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1120</guid>
		<description><![CDATA[This past weekend, we had an issue where replication fell far behind on one of our databases.  The replicated database is used for all sorts of reporting, so the immediate need was to identify processes that may have been affected by the incomplete data.  
Now, there&#8217;s hundreds of stored procedures that reference the [...]]]></description>
			<content:encoded><![CDATA[<p>This past weekend, we had an issue where replication fell far behind on one of our databases.  The replicated database is used for all sorts of reporting, so the immediate need was to identify processes that may have been affected by the incomplete data.  </p>
<p>Now, there&#8217;s hundreds of stored procedures that reference the affected database; the trick is finding out which ones are relevant.  To do this, I used the <a href="http://msdn.microsoft.com/en-us/library/ms189741.aspx" target="_blank">sys.dm_exec_query_stats</a> DMV.  This does two things for me.  One, it shows me a list of stored procedures <strong>in cache</strong>, meaning they&#8217;ve been executed relatively recently and are probably relevant to the search.  Secondly, it shows me the last execution time, which in some cases may have been before the issue, meaning I do not need to worry about re-running those processes.  </p>
<p>Here&#8217;s the query I used:</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;">DB_NAME</span><span style="color: #808080;">&#40;</span>dest.<span style="color: #808080;">&#91;</span>dbid<span style="color: #808080;">&#93;</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'databaseName'</span>
    , <span style="color: #FF00FF;">OBJECT_NAME</span><span style="color: #808080;">&#40;</span>dest.<span style="color: #202020;">objectid</span>, dest.<span style="color: #808080;">&#91;</span>dbid<span style="color: #808080;">&#93;</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'procName'</span>
    , <span style="color: #FF00FF;">MAX</span><span style="color: #808080;">&#40;</span>deqs.<span style="color: #202020;">last_execution_time</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'last_execution'</span>
<span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">dm_exec_query_stats</span> <span style="color: #0000FF;">AS</span> deqs
Cross Apply sys.<span style="color: #202020;">dm_exec_sql_text</span><span style="color: #808080;">&#40;</span>deqs.<span style="color: #202020;">sql_handle</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> dest
<span style="color: #0000FF;">WHERE</span> dest.<span style="color: #808080;">&#91;</span><span style="color: #0000FF;">TEXT</span><span style="color: #808080;">&#93;</span> Like <span style="color: #FF0000;">'%yourTableName%'</span> <span style="color: #008080;">-- replace</span>
    And dest.<span style="color: #808080;">&#91;</span>dbid<span style="color: #808080;">&#93;</span> <span style="color: #0000FF;">IS</span> Not Null  <span style="color: #008080;">-- exclude ad-hocs</span>
<span style="color: #0000FF;">GROUP</span> <span style="color: #0000FF;">BY</span> <span style="color: #FF00FF;">DB_NAME</span><span style="color: #808080;">&#40;</span>dest.<span style="color: #808080;">&#91;</span>dbid<span style="color: #808080;">&#93;</span><span style="color: #808080;">&#41;</span>
    , <span style="color: #FF00FF;">OBJECT_NAME</span><span style="color: #808080;">&#40;</span>dest.<span style="color: #202020;">objectid</span>, dest.<span style="color: #808080;">&#91;</span>dbid<span style="color: #808080;">&#93;</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> databaseName
    , procName
<span style="color: #0000FF;">OPTION</span> <span style="color: #808080;">&#40;</span>MaxDop <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>;</pre></div></div>

<p>This will return results similar to:</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">databaseName         procName                       last_execution
-------------------- ------------------------------ -----------------------
AdventureWorks       ufnGetProductListPrice         2009-08-03 09:57:25.390
AdventureWorksDW     DimProductCategoryGet_sp       2009-08-03 09:59:05.820
AdventureWorksDW     DimProductGet_sp               2009-08-03 09:58:38.370</pre></div></div>

<p>I want to stress that this is *not* a list of all referencing objects, but rather a list of recently executed stored procedures that are still in memory.  This list may not be accurate if your cache has recently been flushed or if you&#8217;ve recently rebooted your server.  </p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/08/find-recently-executed-stored-procedures/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Index Defrag Script Update</title>
		<link>http://sqlfool.com/2009/07/index-defrag-script-update/</link>
		<comments>http://sqlfool.com/2009/07/index-defrag-script-update/#comments</comments>
		<pubDate>Thu, 09 Jul 2009 16:45:02 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Syndication]]></category>
		<category><![CDATA[T-SQL Scripts]]></category>
		<category><![CDATA[defrag]]></category>
		<category><![CDATA[defragment]]></category>
		<category><![CDATA[indexes]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[TSQL]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1082</guid>
		<description><![CDATA[A couple of people pointed out to me that the stats rebuild feature in my defrag script will only complete for one database.  Whoopsies!  I&#8217;ve fixed the bug and updated the script in my previous post, so if you&#8217;re using my defrag script, please update it.  Thanks to Derick and SuperCoolMoss for [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of people pointed out to me that the stats rebuild feature in my defrag script will only complete for one database.  Whoopsies!  I&#8217;ve fixed the bug and updated the script in my <a href="http://sqlfool.com/2009/06/index-defrag-script-v30/" target="_blank">previous post</a>, so if you&#8217;re using my defrag script, please update it.  Thanks to Derick and SuperCoolMoss for letting me know about the bug.  </p>
<p>I&#8217;ve also received a couple of other requests for feature enhancements.  I&#8217;m currently swamped at work and outside of work, but as soon as I get time, I will release the latest version.  Realistically, it&#8217;ll probably be sometime after summer ends.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Thank you to everyone for their comments and suggestions!</p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/07/index-defrag-script-update/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Index Defrag Script, v3.0</title>
		<link>http://sqlfool.com/2009/06/index-defrag-script-v30/</link>
		<comments>http://sqlfool.com/2009/06/index-defrag-script-v30/#comments</comments>
		<pubDate>Wed, 24 Jun 2009 00:37:24 +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[maintenace]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[tuning]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1072</guid>
		<description><![CDATA[I&#8217;ve just completed the latest version of my index defrag script!  Here&#8217;s a brief list of the updates:

Fixed a bug with the LOB logic.  In the previous version, after a LOB was encountered, all subsequent indexes would be reorganized.
Added support for stat rebuilds after the index defrag is complete (@rebuildStats)
Added an exclusion list [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve just completed the latest version of my index defrag script!  Here&#8217;s a brief list of the updates:</p>
<ul>
<li>Fixed a bug with the LOB logic.  In the previous version, after a LOB was encountered, all subsequent indexes would be reorganized.</li>
<li>Added support for stat rebuilds after the index defrag is complete (@rebuildStats)</li>
<li>Added an exclusion list table (dba_indexDefragExclusion) to support index scheduling</li>
<li>Modified logging to show which defrags are &#8220;in progress&#8221;; added columns to dba_indexDefragLog</li>
<li>Added support for the defrag of the model and msdb databases</li>
<li>Added @scanMode as a configurable parameter</li>
</ul>
<p>So what can this index defrag script do?  Well, for starters, you can:</p>
<ul>
<li>Schedule it to run with the default settings; it works &#8220;right out of the box&#8221; with no additional configuration necessary</li>
<li>Run this one script from a centralized database for all databases on a server</li>
<li>Run this script for a specific database or table</li>
<li>Configure custom threshold limits and the point at which a rebuild should be performed (instead of a reorganize)</li>
<li>Defrag individual partitions</li>
<li>Log its actions and the duration of the defrag</li>
<li>Run in &#8220;commands only&#8221; mode (@executeSQL = 0, @printCommands = 1)</li>
<li>Customize performance parameters such as @maxDopRestriction and @defragDelay to minimize impact on the server</li>
<li>Schedule specific indexes to only be defragged on weekends, or every other day</li>
</ul>
<p>To use this last option, you need to add a record to the dba_indexDefragExclusion table.  I think all of the columns are pretty self-explanatory except the [exclusionMask] column.  The way this works is each day of the week is assigned a value:<br />
1=Sunday, 2=Monday, 4=Tuesday, 8=Wednesday, 16=Thursday, 32=Friday, 64=Saturday</p>
<p>Take a SUM of the values for the days that you want <strong>excluded</strong>.  So if you want an index to only be defragged on weekends, you would add up Monday through Friday (2+4+8+16+32) and use a value of 62 for the exclusionMask column.  For a little more information on how this works, check out my blog post on <a href="http://sqlfool.com/2009/02/bitwise-operations/" target="_blank">Bitwise Operations</a>.</p>
<p>Please note:  if you don&#8217;t insert any records into the dba_indexDefragExclusion table, by default all indexes will be defragged every run-time if they exceed the specified thresholds.  This is normal behavior and may be perfectly fine in your environment.  However, if the dba_indexDefragExclusion table does not exist, the script will fail.  </p>
<p>I try to document each parameter within the code, so check the comments section in the script for a full list of parameters and what they do.  </p>
<p>Special thanks to everyone who helped beta test this script!  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Without further ado, the script:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/* Drop Table Scripts:
Drop Table dbo.dba_indexDefragLog;
Drop Table dbo.dba_indexDefragExclusion;
*/</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;">&#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> In <span style="color: #808080;">&#40;</span>N<span style="color: #FF0000;">'dba_indexDefragLog'</span>, <span style="color: #FF0000;">'dba_indexDefragExclusion'</span><span style="color: #808080;">&#41;</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>   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
&nbsp;
        <span style="color: #0000FF;">CONSTRAINT</span> PK_indexDefragLog 
            <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 
            <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>
<span style="color: #0000FF;">ELSE</span>
    <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'One or more tables already exist.  Please drop or rename before proceeding.'</span>, <span style="color: #000;">16</span>, <span style="color: #000;">0</span><span style="color: #808080;">&#41;</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;
&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;">5.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>
    , @<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>
    , @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>
    , @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>
    , @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>
    , @rebuildStats         <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
        <span style="color: #008080;">/* option to rebuild stats after completed index defrags */</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 all indexes for the current database
&nbsp;
    Notes:
&nbsp;
    CAUTION: TRANSACTION LOG SIZE SHOULD BE MONITORED CLOSELY WHEN DEFRAGMENTING.
&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;
      @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;
      @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;
      @onlineRebuild        1 = online rebuild; 
                            0 = offline rebuild
&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;
      @rebuildStats         Affects only statistics that need to be rebuilt
                            1 = rebuild stats
                            0 = do not rebuild stats
&nbsp;
    Called by:  SQL Agent Job or DBA
&nbsp;
    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)
*********************************************************************************
    Exec dbo.dba_indexDefrag_sp
          @executeSQL           = 0
        , @printCommands        = 1
        , @debugMode            = 1
        , @printFragmentation   = 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>;
<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;">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;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</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>
            , @rebuildStatsID       <span style="color: #0000FF;">INT</span>
            , @rebuildStatsSQL      <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>;
&nbsp;
    <span style="color: #008080;">/* Create our temporary tables */</span>
    <span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> #indexDefragList
    <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>
        , defragStatus      <span style="color: #0000FF;">BIT</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
    <span style="color: #808080;">&#41;</span>;
&nbsp;
    <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>
        , statsStatus       <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;">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;">/* Just a little validation... */</span>
    <span style="color: #0000FF;">IF</span> @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 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> @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: #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: #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: #000;">0</span> <span style="color: #008080;">-- statistics not yet updated</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>
&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> #indexDefragList
        <span style="color: #0000FF;">SELECT</span>
              database_id <span style="color: #0000FF;">AS</span> databaseID
            , <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>database_id<span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'databaseName'</span>
            , <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> objectID
            , index_id <span style="color: #0000FF;">AS</span> indexID
            , partition_number <span style="color: #0000FF;">AS</span> partitionNumber
            , avg_fragmentation_in_percent <span style="color: #0000FF;">AS</span> fragmentation
            , page_count 
            , <span style="color: #000;">0</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'defragStatus'</span> <span style="color: #008080;">/* 0 = unprocessed, 1 = processed */</span>
            , Null <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'schemaName'</span>
            , Null <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'objectName'</span>
            , Null <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'indexName'</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;">WHERE</span> avg_fragmentation_in_percent <span style="color: #808080;">&gt;=</span> @minFragmentation 
            And index_id <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span> <span style="color: #008080;">-- ignore heaps</span>
            And page_count <span style="color: #808080;">&gt;</span> <span style="color: #000;">8</span> <span style="color: #008080;">-- ignore objects with less than 1 extent</span>
            And index_level <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;">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;">/* 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: #0000FF;">CREATE</span> <span style="color: #0000FF;">CLUSTERED</span> <span style="color: #0000FF;">INDEX</span> CIX_temp_indexDefragList
        <span style="color: #0000FF;">ON</span> #indexDefragList<span style="color: #808080;">&#40;</span>databaseID, objectID, indexID, partitionNumber<span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #008080;">/* Delete any indexes from our to-do that are also in our exclusion list for today */</span>
    <span style="color: #0000FF;">DELETE</span> idl
    <span style="color: #0000FF;">FROM</span> #indexDefragList <span style="color: #0000FF;">AS</span> idl
    Join dbo.<span style="color: #202020;">dba_indexDefragExclusion</span> <span style="color: #0000FF;">AS</span> ide
        <span style="color: #0000FF;">ON</span> idl.<span style="color: #202020;">databaseID</span> <span style="color: #808080;">=</span> ide.<span style="color: #202020;">databaseID</span>
        And idl.<span style="color: #202020;">objectID</span> <span style="color: #808080;">=</span> ide.<span style="color: #202020;">objectID</span>
        And idl.<span style="color: #202020;">indexID</span> <span style="color: #808080;">=</span> ide.<span style="color: #202020;">indexID</span>
    <span style="color: #0000FF;">WHERE</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;">&gt;</span> <span style="color: #000;">0</span>;
&nbsp;
    <span style="color: #0000FF;">SELECT</span> @debugMessage <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Looping through our list... there'</span><span style="color: #FF0000;">'s '</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> #indexDefragList;
&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> #indexDefragList <span style="color: #0000FF;">WHERE</span> defragStatus <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;">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 most fragmented index first to defrag */</span>
        <span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">TOP</span> <span style="color: #000;">1</span> 
              @objectID         <span style="color: #808080;">=</span> objectID
            , @indexID          <span style="color: #808080;">=</span> indexID
            , @databaseID       <span style="color: #808080;">=</span> databaseID
            , @databaseName     <span style="color: #808080;">=</span> databaseName
            , @fragmentation    <span style="color: #808080;">=</span> fragmentation
            , @partitionNumber  <span style="color: #808080;">=</span> partitionNumber
            , @pageCount        <span style="color: #808080;">=</span> page_count
        <span style="color: #0000FF;">FROM</span> #indexDefragList
        <span style="color: #0000FF;">WHERE</span> defragStatus <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
        <span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> fragmentation <span style="color: #0000FF;">DESC</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 idl
            Set schemaName = QuoteName(s.name)
                , objectName = QuoteName(o.name)
                , indexName = QuoteName(i.name)
            From #indexDefragList As idl
            Inner Join '</span> <span style="color: #808080;">+</span> @databaseName <span style="color: #808080;">+</span> <span style="color: #FF0000;">'.sys.objects As o
                On idl.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
            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 idl.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> #indexDefragList
        <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'</span><span style="color: #FF0000;">'s 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;">'  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> @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: #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>;
&nbsp;
        <span style="color: #008080;">/* If the index is heavily fragmented and doesn't contain any partitions or LOB's, rebuild it */</span>
        <span style="color: #0000FF;">IF</span> @fragmentation <span style="color: #808080;">&gt;=</span> @rebuildThreshold 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 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>;
&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;">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;">'  Executing 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;">/* 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
            <span style="color: #808080;">&#41;</span>
            <span style="color: #0000FF;">SELECT</span>
                  @databaseID
                , @databaseName
                , @objectID
                , @objectName
                , @indexID
                , @indexName
                , @partitionNumber
                , @fragmentation
                , @pageCount
                , @dateTimeStart;
&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;">/* 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: #008080;">/* Just a little breather for the server */</span>
            <span style="color: #0000FF;">WAITFOR</span> Delay @defragDelay;
&nbsp;
            <span style="color: #008080;">/* Print 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: #0000FF;">PRINT</span> N<span style="color: #FF0000;">'Executed: '</span> <span style="color: #808080;">+</span> @sqlCommand;
        <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: #0000FF;">PRINT</span> IsNull<span style="color: #808080;">&#40;</span>@sqlCommand, <span style="color: #FF0000;">'error!'</span><span style="color: #808080;">&#41;</span>;
        <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;">'  Updating our index defrag status...'</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;">/* Update our index defrag list so we know we've finished with that index */</span>
        <span style="color: #0000FF;">UPDATE</span> #indexDefragList
        <span style="color: #0000FF;">SET</span> defragStatus <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>
&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 fragmentation results...'</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
            , fragmentation
            , page_count
        <span style="color: #0000FF;">FROM</span> #indexDefragList;
&nbsp;
    <span style="color: #0000FF;">END</span>;
&nbsp;
    <span style="color: #008080;">/* Do we want to rebuild stats? */</span>
    <span style="color: #0000FF;">IF</span> @rebuildStats <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
    <span style="color: #0000FF;">BEGIN</span>
&nbsp;
        <span style="color: #0000FF;">WHILE</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> #databaseList <span style="color: #0000FF;">WHERE</span> statsStatus <span style="color: #808080;">=</span> <span style="color: #000;">0</span><span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">BEGIN</span>
&nbsp;
            <span style="color: #008080;">/* Build our SQL statement to update stats */</span>
            <span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">TOP</span> <span style="color: #000;">1</span> @rebuildStatsSQL <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Use ['</span> <span style="color: #808080;">+</span> databaseName <span style="color: #808080;">+</span> <span style="color: #FF0000;">']; '</span> <span style="color: #808080;">+</span> 
                                            <span style="color: #FF0000;">'Execute sp_updatestats;'</span>
                    , @rebuildStatsID <span style="color: #808080;">=</span> databaseID
            <span style="color: #0000FF;">FROM</span> #databaseList
            <span style="color: #0000FF;">WHERE</span> statsStatus <span style="color: #808080;">=</span> <span style="color: #000;">0</span>;
&nbsp;
            <span style="color: #0000FF;">SET</span> @debugMessage <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Rebuilding Statistics: '</span> <span style="color: #808080;">+</span> @rebuildStatsSQL;
&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;">/* Execute our stats update! */</span>
            <span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">SP_EXECUTESQL</span> @rebuildStatsSQL;
&nbsp;
            <span style="color: #008080;">/* Keep track of which databases have been updated */</span>
            <span style="color: #0000FF;">UPDATE</span> #databaseList 
            <span style="color: #0000FF;">SET</span> statsStatus <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
            <span style="color: #0000FF;">WHERE</span> databaseID <span style="color: #808080;">=</span> @rebuildStatsID;
&nbsp;
        <span style="color: #0000FF;">END</span>;
    <span style="color: #0000FF;">END</span>;
&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> #indexDefragList;
    <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;
&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>
Go
&nbsp;
<span style="color: #0000FF;">SET</span> Quoted_Identifier <span style="color: #0000FF;">OFF</span> 
<span style="color: #0000FF;">SET</span> ANSI_Nulls <span style="color: #0000FF;">ON</span>
Go</pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/06/index-defrag-script-v30/feed/</wfw:commentRss>
		<slash:comments>89</slash:comments>
		</item>
		<item>
		<title>sp_WhoIsActive</title>
		<link>http://sqlfool.com/2009/05/sp_whoisactive/</link>
		<comments>http://sqlfool.com/2009/05/sp_whoisactive/#comments</comments>
		<pubDate>Fri, 29 May 2009 02:20:57 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Miscellaneous]]></category>
		<category><![CDATA[Presentations]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[T-SQL Scripts]]></category>
		<category><![CDATA[presentation]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[webcast]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1020</guid>
		<description><![CDATA[For those who attended the webcast I did with Brent Ozar today, &#8220;Getting Started With SQL Server Management Studio,&#8221; here&#8217;s the link to Adam Machanic&#8217;s excellent sp_WhoIsActive stored proc:
http://sqlblog.com/blogs/adam_machanic/archive/2009/03/30/who-is-active-v8-40-now-with-delta-power.aspx
Thanks for attending!   
]]></description>
			<content:encoded><![CDATA[<p>For those who attended the webcast I did with <a href="http://brentozar.com" target="_blank">Brent Ozar</a> today, &#8220;Getting Started With SQL Server Management Studio,&#8221; here&#8217;s the link to <a href="http://sqlblog.com/blogs/adam_machanic/default.aspx" target="_blank">Adam Machanic&#8217;s</a> excellent sp_WhoIsActive stored proc:</p>
<p><a href="http://sqlblog.com/blogs/adam_machanic/archive/2009/03/30/who-is-active-v8-40-now-with-delta-power.aspx" target="_blank">http://sqlblog.com/blogs/adam_machanic/archive/2009/03/30/who-is-active-v8-40-now-with-delta-power.aspx</a></p>
<p>Thanks for attending!  <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/05/sp_whoisactive/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Page Internals &#8211; Investigation Proc</title>
		<link>http://sqlfool.com/2009/05/page-internals-investigation-proc/</link>
		<comments>http://sqlfool.com/2009/05/page-internals-investigation-proc/#comments</comments>
		<pubDate>Wed, 06 May 2009 19:01:11 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Internals]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[T-SQL Scripts]]></category>
		<category><![CDATA[script]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=935</guid>
		<description><![CDATA[As many of you know, I like to crawl around in page internals in my free time.  It can be very enlightening, or just a good check to make sure that what you think is happening, is actually happening.  To help with this process, I&#8217;ve created myself a little stored procedure that I [...]]]></description>
			<content:encoded><![CDATA[<p>As many of you know, I like to crawl around in page internals in my free time.  It can be very enlightening, or just a good check to make sure that what you think is happening, is actually happening.  To help with this process, I&#8217;ve created myself a little stored procedure that I can simply pass a few parameters to and have it return the page data for me.  So for those <span style="text-decoration: line-through;">who don&#8217;t have anything better to do</span> who are as interested in page internals as I am, here&#8217;s my proc:</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_viewPageData_sp</span>
&nbsp;
        <span style="color: #008080;">/* Declare Parameters */</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>
        , @tableName    <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;">-- database.schema.tableName</span>
        , @indexName    <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
        , @fileNumber   <span style="color: #0000FF;">INT</span>             <span style="color: #808080;">=</span> Null
        , @pageNumber   <span style="color: #0000FF;">INT</span>             <span style="color: #808080;">=</span> Null
        , @printOption  <span style="color: #0000FF;">INT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">3</span>    <span style="color: #008080;">-- 0, 1, 2, or 3</span>
        , @pageType     <span style="color: #0000FF;">CHAR</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;">'Leaf'</span> <span style="color: #008080;">-- Leaf, Root, or IAM</span>
&nbsp;
<span style="color: #0000FF;">AS</span>
<span style="color: #008080;">/*********************************************************************************
    Name:       dba_viewPageData_sp
&nbsp;
    Author:     Michelle Ufford
&nbsp;
    Purpose:    Retrieves page data for the specified table/page.
&nbsp;
    Notes:      Can pass either the table name or the pageID, but must pass one, or
                you'll end up with no results. 
                If the table name is passed, it will return the first page.
&nbsp;
        @tableName must be '&lt;databaseName&gt;.&lt;schemaName&gt;.&lt;tableName&gt;' in order to
            function correctly for cross-database joins.  
&nbsp;
        @printOption can be one of following values:
            0 - print just the page header
            1 - page header plus per-row hex dumps and a dump of the page slot array
            2 - page header plus whole page hex dump
            3 - page header plus detailed per-row interpretation
&nbsp;
        Page Options borrowed from: 
        https://blogs.msdn.com/sqlserverstorageengine/archive/2006/06/10/625659.aspx
&nbsp;
        @pageType must be one of the following values:
            Leaf - returns the first page of the leaf level of your index or heap
            Root - returns the root page of your index
            IAM - returns the index allocation map chain for your index or heap
&nbsp;
        Conversions borrowed from:
        http://sqlskills.com/blogs/paul/post/Inside-The-Storage-Engine-
        sp_AllocationMetadata-putting-undocumented-system-catalog-views-to-work.aspx
&nbsp;
    Called by:  DBA
&nbsp;
    Date        User    Description
    ----------------------------------------------------------------------------
    2009-05-06  MFU     Initial release for public consumption
*********************************************************************************
    Exec dbo.dba_viewPageData_sp
          @databaseName = 'AdventureWorks'
        , @tableName    = 'AdventureWorks.Sales.SalesOrderDetail'
        , @indexName    = 'IX_SalesOrderDetail_ProductID'
        --, @fileNumber   = 1
        --, @pageNumber   = 38208
        , @printOption  = 3
        , @pageType     = 'Root';
*********************************************************************************/</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: #0000FF;">DECLARE</span> @fileID         <span style="color: #0000FF;">INT</span>
        , @pageID           <span style="color: #0000FF;">INT</span>
        , @sqlStatement     <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">1200</span><span style="color: #808080;">&#41;</span>
        , @sqlParameters    <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">255</span><span style="color: #808080;">&#41;</span>
        , @errorMessage     <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">100</span><span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #0000FF;">BEGIN</span> Try
&nbsp;
        <span style="color: #0000FF;">IF</span> @fileNumber <span style="color: #0000FF;">IS</span> Null And @pageNumber <span style="color: #0000FF;">IS</span> Null And @tableName <span style="color: #0000FF;">IS</span> Null
        <span style="color: #0000FF;">BEGIN</span>
            <span style="color: #0000FF;">SET</span> @errorMessage <span style="color: #808080;">=</span> <span style="color: #FF0000;">'You must provide either a file/page number, or a table name!'</span>;
            <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span>@errorMessage, <span style="color: #000;">16</span>, <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>;
        <span style="color: #0000FF;">END</span>;
&nbsp;
        <span style="color: #0000FF;">IF</span> @pageType Not In <span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Leaf'</span>, <span style="color: #FF0000;">'Root'</span>, <span style="color: #FF0000;">'IAM'</span><span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">BEGIN</span>
            <span style="color: #0000FF;">SET</span> @errorMessage <span style="color: #808080;">=</span> <span style="color: #FF0000;">'You have entered an invalid page type; valid options are &quot;Leaf&quot;, &quot;Root&quot;, or &quot;IAM&quot;'</span>;
            <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span>@errorMessage, <span style="color: #000;">16</span>, <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>;
        <span style="color: #0000FF;">END</span>;
&nbsp;
        <span style="color: #0000FF;">IF</span> @fileNumber <span style="color: #0000FF;">IS</span> Null Or @pageNumber <span style="color: #0000FF;">IS</span> Null
        <span style="color: #0000FF;">BEGIN</span>
&nbsp;
            <span style="color: #0000FF;">SET</span> @sqlStatement <span style="color: #808080;">=</span> 
            <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> @pageType <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Leaf'</span> <span style="color: #0000FF;">THEN</span>
                <span style="color: #FF0000;">'Select Top 1 @p_fileID = Convert (varchar(6), Convert (int, 
                    SubString (au.first_page, 6, 1) +
                    SubString (au.first_page, 5, 1)))
                , @p_pageID = Convert (varchar(20), Convert (int, 
                     SubString (au.first_page, 4, 1) +
                     SubString (au.first_page, 3, 1) +
                     SubString (au.first_page, 2, 1) +
                     SubString (au.first_page, 1, 1)))'</span>
            <span style="color: #0000FF;">WHEN</span> @pageType <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Root'</span> <span style="color: #0000FF;">THEN</span>
                <span style="color: #FF0000;">'Select Top 1 @p_fileID = Convert (varchar(6), Convert (int, 
                    SubString (au.root_page, 6, 1) +
                    SubString (au.root_page, 5, 1)))
                , @p_pageID = Convert (varchar(20), Convert (int, 
                     SubString (au.root_page, 4, 1) +
                     SubString (au.root_page, 3, 1) +
                     SubString (au.root_page, 2, 1) +
                     SubString (au.root_page, 1, 1)))'</span>
            <span style="color: #0000FF;">WHEN</span> @pageType <span style="color: #808080;">=</span> <span style="color: #FF0000;">'IAM'</span> <span style="color: #0000FF;">THEN</span>
                <span style="color: #FF0000;">'Select Top 1 @p_fileID = Convert (varchar(6), Convert (int, 
                    SubString (au.first_iam_page, 6, 1) +
                    SubString (au.first_iam_page, 5, 1)))
                , @p_pageID = Convert (varchar(20), Convert (int, 
                     SubString (au.first_iam_page, 4, 1) +
                     SubString (au.first_iam_page, 3, 1) +
                     SubString (au.first_iam_page, 2, 1) +
                     SubString (au.first_iam_page, 1, 1)))'</span>
            <span style="color: #0000FF;">END</span> <span style="color: #808080;">+</span> 
            <span style="color: #FF0000;">'From '</span> <span style="color: #808080;">+</span> <span style="color: #FF00FF;">QUOTENAME</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">PARSENAME</span><span style="color: #808080;">&#40;</span>@databaseName, <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">'.sys.indexes AS i
            Join '</span> <span style="color: #808080;">+</span> <span style="color: #FF00FF;">QUOTENAME</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">PARSENAME</span><span style="color: #808080;">&#40;</span>@databaseName, <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">'.sys.partitions AS p
                On i.[object_id] = p.[object_id]
                And i.index_id = p.index_id
            Join '</span> <span style="color: #808080;">+</span> <span style="color: #FF00FF;">QUOTENAME</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">PARSENAME</span><span style="color: #808080;">&#40;</span>@databaseName, <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">'.sys.system_internals_allocation_units AS au
                On p.hobt_id = au.container_id
            Where p.[object_id] = Object_ID(@p_tableName)
                And au.first_page &gt; 0x000000000000 '</span> 
                <span style="color: #808080;">+</span> <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> @indexName <span style="color: #0000FF;">IS</span> Null 
                    <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">';'</span> 
                    <span style="color: #0000FF;">ELSE</span> <span style="color: #FF0000;">'And i.name = @p_indexName;'</span> <span style="color: #0000FF;">END</span>;
&nbsp;
            <span style="color: #0000FF;">SET</span> @sqlParameters <span style="color: #808080;">=</span> <span style="color: #FF0000;">'@p_tableName varchar(128)
                                , @p_indexName varchar(128)
                                , @p_fileID int OUTPUT
                                , @p_pageID int OUTPUT'</span>;
&nbsp;
            <span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">SP_EXECUTESQL</span> @sqlStatement
                        , @sqlParameters
                        , @p_tableName <span style="color: #808080;">=</span> @tableName
                        , @p_indexName <span style="color: #808080;">=</span> @indexName
                        , @p_fileID <span style="color: #808080;">=</span> @fileID <span style="color: #0000FF;">OUTPUT</span>
                        , @p_pageID <span style="color: #808080;">=</span> @pageID <span style="color: #0000FF;">OUTPUT</span>;
&nbsp;
            <span style="color: #0000FF;">END</span>
            <span style="color: #0000FF;">ELSE</span>
            <span style="color: #0000FF;">BEGIN</span>
                <span style="color: #0000FF;">SELECT</span> @fileID <span style="color: #808080;">=</span> @fileNumber
                    , @pageID <span style="color: #808080;">=</span> @pageNumber;
            <span style="color: #0000FF;">END</span>;
&nbsp;
        <span style="color: #0000FF;">DBCC</span> TraceOn <span style="color: #808080;">&#40;</span><span style="color: #000;">3604</span><span style="color: #808080;">&#41;</span>;
        <span style="color: #0000FF;">DBCC</span> Page <span style="color: #808080;">&#40;</span>@databaseName, @fileID, @pageID, @printOption<span style="color: #808080;">&#41;</span>;
        <span style="color: #0000FF;">DBCC</span> TraceOff <span style="color: #808080;">&#40;</span><span style="color: #000;">3604</span><span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #0000FF;">END</span> Try
    <span style="color: #0000FF;">BEGIN</span> Catch
&nbsp;
        <span style="color: #0000FF;">PRINT</span> @errorMessage;
&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>This proc does have cross-database support, i.e. you can install it in your DBA database and use it to investigate data in other databases.  Here&#8217;s an example&#8230;</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;">    <span style="color: #0000FF;">EXEC</span> dbo.<span style="color: #202020;">dba_viewPageData_sp</span>
          @databaseName <span style="color: #808080;">=</span> <span style="color: #FF0000;">'AdventureWorks'</span>
        , @tableName    <span style="color: #808080;">=</span> <span style="color: #FF0000;">'AdventureWorks.Sales.SalesOrderDetail'</span>
        , @indexName    <span style="color: #808080;">=</span> <span style="color: #FF0000;">'IX_SalesOrderDetail_ProductID'</span>;</pre></div></div>

<p>&#8230; will return a nice data page:</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">DBCC execution completed. If DBCC printed error messages, contact your system administrator.
&nbsp;
PAGE: (1:11000)
&nbsp;
BUFFER:
&nbsp;
BUF @0x0391F140
&nbsp;
bpage = 0x0C0C0000                   bhash = 0x00000000                   bpageno = (1:11000)
bdbid = 7                            breferences = 0                      bUse1 = 35177
bstat = 0x1c00009                    blog = 0x21212159                    bnext = 0x00000000</pre></div></div>

<p>[waits for the "oohs" and "aahs" to subside...]</p>
<p>I also give you the option to specify a specific page, in case you want to follow the page trail (i.e. m_nextPage).  I&#8217;m not really providing support for partitions, although I do have a little dirty piece of code to return a hobt with data if possible (i.e. &#8220;first_page > 0&#215;000000000000&#8243;).  </p>
<p><strong>Update:</strong> Special thanks to <a href="http://twitter.com/peschkaj" target="_blank">Jeremiah Peschka</a> and <a href="http://twitter.com/AdamMachanic" target="_blank">Adam Machanic</a> for showing me<br />
QUOTENAME(PARSENAME(@databaseName, 1))!  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Also, thanks to <a href="http://www.sqlskills.com/BLOGS/PAUL/" target="_blank">Paul Randal</a> for his excellent blog posts on this very topic!  Check out his blog post on <a href="https://blogs.msdn.com/sqlserverstorageengine/archive/2006/06/10/625659.aspx" target="_blank">DBCC Page</a>.  The conversion code was borrowed from his <a href="http://www.sqlskills.com/BLOGS/PAUL/post/Inside-The-Storage-Engine-sp_AllocationMetadata-putting-undocumented-system-catalog-views-to-work.aspx" target="_blank">sp_AllocationMetadata</a> proc.  </p>
<p><strong>Update 2:</strong> I&#8217;ve made some quick changes based on some feedback from Twitter.  Thanks for the suggestions and hopefully you enjoy the updates.  </p>
<p>Happy crawling!</p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/05/page-internals-investigation-proc/feed/</wfw:commentRss>
		<slash:comments>6</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&#8217;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 [...]]]></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&#8217;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&#8230; <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 &#8220;Missing Index&#8221; 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&#8217;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&#8217;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&#8217;m looking for in this DMV is the number of user_seeks and the est_impact.  Also, if I haven&#8217;t rebooted my server in a while, I take a look at last_user_seek so I can determine whether or not it&#8217;s still accurate.  </p>
<p>Next, I take a look at my existing indexes using Kimberly Tripp&#8217;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&#8217;re wondering why I&#8217;m looking at existing indexes, the reason is because I&#8217;m looking for indexes that can be modified <em>slightly</em> to accommodate my missing index needs.  By &#8220;modified slightly,&#8221; I mean that I&#8217;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&#8217;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&#8217;s a greater chance I&#8217;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, &#8220;Hey!  What a great time for a diagram.&#8221;  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&#8217;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&#8217;s hard to really put all of the decision paths into a single, small diagram like this.  There&#8217;s a lot of variables that I&#8217;m not even touching here.  But I think this is a fairly good &#8220;generic&#8221; representation of the path I take.  When I hit an &#8220;end&#8221; process, it means I don&#8217;t create the missing index at this time.  Maybe in the future, it&#8217;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>8</slash:comments>
		</item>
		<item>
		<title>Automated Index Defrag Script</title>
		<link>http://sqlfool.com/2009/03/automated-index-defrag-script/</link>
		<comments>http://sqlfool.com/2009/03/automated-index-defrag-script/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 13:34:13 +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[T-SQL Scripts]]></category>
		<category><![CDATA[defrag]]></category>
		<category><![CDATA[fragmentation]]></category>
		<category><![CDATA[indexes]]></category>
		<category><![CDATA[maintenace]]></category>
		<category><![CDATA[partitioning]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=689</guid>
		<description><![CDATA[Note: This script has been updated.  You can find the latest version here: http://sqlfool.com/2009/06/index-defrag-script-v30/
So after much delay, here’s the latest and greatest version of my index defrag script. 
A summary of the changes:

Added support for centralized execution. Option to defrag indexes for a single database from another database, or for all non-system databases. 
Consolidated [...]]]></description>
			<content:encoded><![CDATA[<p><em>Note: This script has been updated.  You can find the latest version here: <a href="http://sqlfool.com/2009/06/index-defrag-script-v30/">http://sqlfool.com/2009/06/index-defrag-script-v30/</a></em></p>
<p>So after much delay, here’s the latest and greatest version of my index defrag script. </p>
<p>A summary of the changes:</p>
<ul>
<li>Added support for centralized execution. Option to defrag indexes for a single database from another database, or for all non-system databases. </li>
<li>Consolidated Enterprise and Standard versions of the script with new @editionCheck variable. </li>
<li>Added parametrization for MaxDop restrictions during rebuilds; validates that the value does not exceed the actual number of processors on the server. </li>
<li>Changed minimum fragmentation default value from 10 to 5 to match BOL recommendations. </li>
<li>Limited defrags to objects with more than 8 pages. </li>
<li>Added a debug option to give a little more insight into what’s happening and to assist with troubleshooting. </li>
<li>Updated logic for handling partitions and LOBs. </li>
</ul>
<p>And a couple of notes and explanations:</p>
<p><strong>Don’t you know you can just pass NULL to sys.dm_db_index_physical_stats for the DatabaseID?</strong><br />
Yes, I realize you can do this. But I don’t want to defrag the system databases, i.e. tempdb, so I opted to handle it this way instead.</p>
<p><strong>How long will this take?</strong><br />
It depends. I don’t necessarily recommend running it without specifying a database; at least, not unmonitored. You *can* do that, but it could take a while. For example, to run sys.dm_db_index_physical_stats for all databases and tables, totaling 2TB, took me 4.5 hours; that doesn’t even count the actual defrags.</p>
<p><strong>Where should I put this?</strong><br />
It’s up to you. If you have a database for items like centralized maintenance or scratch tables, that may be a good place for it. If you prefer, you could also put this in each individual database and call it locally, too. I would not put this in the master or msdb databases.</p>
<p>This is pretty close to a complete rewrite, so please let me know if you encounter any bugs. And now… the code!</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">IF</span> Not 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> name <span style="color: #808080;">=</span> N<span style="color: #FF0000;">'dba_indexDefragLog'</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">BEGIN</span>
    <span style="color: #008080;">-- Drop Table dbo.dba_indexDefragLog</span>
    <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
        , durationSeconds   <span style="color: #0000FF;">INT</span>                 Not Null
        <span style="color: #0000FF;">CONSTRAINT</span> PK_indexDefragLog <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>;
<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;
&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;">5.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>
    , @<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>
    , @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>
    , @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>
<span style="color: #0000FF;">AS</span>
<span style="color: #008080;">/*********************************************************************************
    Name:       dba_indexDefrag_sp
&nbsp;
    Author:     Michelle Ufford, http://sqlfool.com
&nbsp;
    Purpose:    Defrags all indexes for one or more databases
&nbsp;
    Notes:
&nbsp;
    CAUTION: TRANSACTION LOG SIZE MUST BE MONITORED CLOSELY WHEN DEFRAGMENTING.
&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;
      @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;
      @onlineRebuild        1 = online rebuild; 
                            0 = offline rebuild
&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;
    Date        Initials	Description
    ----------------------------------------------------------------------------
    2008-10-27  MFU         Initial Release for public consumption
    2008-11-17  MFU         Added page-count to log table
                            , added @printFragmentation option
    2009-03-17  MFU         Provided support for centralized execution, 
                            , consolidated Enterprise &amp; Standard versions
                            , added @debugMode, @maxDopRestriction
                            , modified LOB and partition logic                            
*********************************************************************************
    Exec dbo.dba_indexDefrag_sp
          @executeSQL           = 0
        , @minFragmentation     = 80
        , @printCommands        = 1
        , @debugMode            = 1
        , @printFragmentation   = 1
        , @database             = 'AdventureWorks'
        , @tableName            = 'AdventureWorks.Sales.SalesOrderDetail';
*********************************************************************************/</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> Quoted_Identifier <span style="color: #0000FF;">ON</span>;
&nbsp;
<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;">'Dusting off the spiderwebs 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>
            , @partitions           <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;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</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>;
&nbsp;
    <span style="color: #008080;">/* Create our temporary tables */</span>
    <span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> #indexDefragList
    <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>
        , defragStatus      <span style="color: #0000FF;">BIT</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
    <span style="color: #808080;">&#41;</span>;
&nbsp;
    <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>
    <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;">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;">/* Just a little validation... */</span>
    <span style="color: #0000FF;">IF</span> @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;">5.0</span>;
&nbsp;
    <span style="color: #0000FF;">IF</span> @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: #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: #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: #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 database_id <span style="color: #808080;">&gt;</span> <span style="color: #000;">4</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>
&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: #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;
&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> #indexDefragList
        <span style="color: #0000FF;">SELECT</span>
              database_id <span style="color: #0000FF;">AS</span> databaseID
            , <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>database_id<span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'databaseName'</span>
            , <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> objectID
            , index_id <span style="color: #0000FF;">AS</span> indexID
            , partition_number <span style="color: #0000FF;">AS</span> partitionNumber
            , avg_fragmentation_in_percent <span style="color: #0000FF;">AS</span> fragmentation
            , page_count 
            , <span style="color: #000;">0</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'defragStatus'</span> <span style="color: #008080;">/* 0 = unprocessed, 1 = processed */</span>
            , Null <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'schemaName'</span>
            , Null <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'objectName'</span>
            , Null <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'indexName'</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, N<span style="color: #FF0000;">'Limited'</span><span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">WHERE</span> avg_fragmentation_in_percent <span style="color: #808080;">&gt;=</span> @minFragmentation 
            And index_id <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span> <span style="color: #008080;">-- ignore heaps</span>
            And page_count <span style="color: #808080;">&gt;</span> <span style="color: #000;">8</span> <span style="color: #008080;">-- ignore objects with less than 1 extent</span>
        <span style="color: #0000FF;">OPTION</span> <span style="color: #808080;">&#40;</span>MaxDop <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>;
&nbsp;
        <span style="color: #0000FF;">DELETE</span> <span style="color: #0000FF;">FROM</span> #databaseList
        <span style="color: #0000FF;">WHERE</span> databaseID <span style="color: #808080;">=</span> @databaseID;
&nbsp;
    <span style="color: #0000FF;">END</span>
&nbsp;
    <span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">CLUSTERED</span> <span style="color: #0000FF;">INDEX</span> CIX_temp_indexDefragList
        <span style="color: #0000FF;">ON</span> #indexDefragList<span style="color: #808080;">&#40;</span>databaseID, objectID, indexID, partitionNumber<span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #0000FF;">SELECT</span> @debugMessage <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Looping through our list... there'</span><span style="color: #FF0000;">'s '</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> #indexDefragList;
&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> #indexDefragList <span style="color: #0000FF;">WHERE</span> defragStatus <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;">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 most fragmented index first to defrag */</span>
        <span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">TOP</span> <span style="color: #000;">1</span> 
              @objectID         <span style="color: #808080;">=</span> objectID
            , @indexID          <span style="color: #808080;">=</span> indexID
            , @databaseID       <span style="color: #808080;">=</span> databaseID
            , @databaseName     <span style="color: #808080;">=</span> databaseName
            , @fragmentation    <span style="color: #808080;">=</span> fragmentation
            , @partitionNumber  <span style="color: #808080;">=</span> partitionNumber
            , @pageCount        <span style="color: #808080;">=</span> page_count
        <span style="color: #0000FF;">FROM</span> #indexDefragList
        <span style="color: #0000FF;">WHERE</span> defragStatus <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
        <span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> fragmentation <span style="color: #0000FF;">DESC</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 idl
            Set schemaName = QuoteName(s.name)
                , objectName = QuoteName(o.name)
                , indexName = QuoteName(i.name)
            From #indexDefragList As idl
            Inner Join '</span> <span style="color: #808080;">+</span> @databaseName <span style="color: #808080;">+</span> <span style="color: #FF0000;">'.sys.objects As o
                On idl.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
            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 idl.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> #indexDefragList
        <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'</span><span style="color: #FF0000;">'s 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 Top 1 @containsLOB_OUT = column_id
                            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;">'  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> @fragmentation <span style="color: #808080;">&lt;</span> @rebuildThreshold Or @containsLOB <span style="color: #808080;">=</span> <span style="color: #000;">1</span> Or @partitionCount <span style="color: #808080;">&gt;</span> <span style="color: #000;">1</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>;
&nbsp;
        <span style="color: #008080;">/* If the index is heavily fragmented and doesn't contain any partitions or LOB's, rebuild it */</span>
        <span style="color: #0000FF;">IF</span> @fragmentation <span style="color: #808080;">&gt;=</span> @rebuildThreshold 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 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>;
&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;">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;">'  Executing 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;">/* 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>;
            <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;">/* 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
                , durationSeconds
            <span style="color: #808080;">&#41;</span>
            <span style="color: #0000FF;">SELECT</span>
                  @databaseID
                , @databaseName
                , @objectID
                , @objectName
                , @indexID
                , @indexName
                , @partitionNumber
                , @fragmentation
                , @pageCount
                , @dateTimeStart
                , <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>;
&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: #008080;">/* Print 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: #0000FF;">PRINT</span> N<span style="color: #FF0000;">'Executed: '</span> <span style="color: #808080;">+</span> @sqlCommand;
        <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: #0000FF;">PRINT</span> IsNull<span style="color: #808080;">&#40;</span>@sqlCommand, <span style="color: #FF0000;">'error!'</span><span style="color: #808080;">&#41;</span>;
        <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;">'  Updating our index defrag status...'</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;">/* Update our index defrag list so we know we've finished with that index */</span>
        <span style="color: #0000FF;">UPDATE</span> #indexDefragList
        <span style="color: #0000FF;">SET</span> defragStatus <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>
&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 fragmentation results...'</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
            , fragmentation
            , page_count
        <span style="color: #0000FF;">FROM</span> #indexDefragList;
&nbsp;
    <span style="color: #0000FF;">END</span>;
&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> #indexDefragList;
    <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;
&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>
Go</pre></div></div>

<p>Thanks to my beta testers, @scoinva, @davidmtate, @jdanton, and @SuperCoolMoss!<br />
Special thanks to SCM for keeping on me to finish this.  </p>
<p>Happy Defragging!</p>
<p>Michelle</p>
<p>Source: <a href="http://sqlfool.com/2009/03/automated-index-defrag-script/">http://sqlfool.com/2009/03/automated-index-defrag-script/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/03/automated-index-defrag-script/feed/</wfw:commentRss>
		<slash:comments>35</slash:comments>
		</item>
		<item>
		<title>Find Missing Indexes in Stored Procs with T-SQL</title>
		<link>http://sqlfool.com/2009/03/find-missing-indexes/</link>
		<comments>http://sqlfool.com/2009/03/find-missing-indexes/#comments</comments>
		<pubDate>Mon, 02 Mar 2009 16:11:37 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[SQL Tips]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[T-SQL Scripts]]></category>
		<category><![CDATA[indexes]]></category>
		<category><![CDATA[missing indexes]]></category>
		<category><![CDATA[query plan]]></category>
		<category><![CDATA[twitter]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=572</guid>
		<description><![CDATA[This post should probably be called &#8220;The Power of Twitter.&#8221;  I&#8217;ve said it before, I&#8217;ll say it again: I love Twitter.  I mostly follow SQL Server people, so it&#8217;s become a great source of new information and help when I feel like banging my head against the wall when I get stumped.
So last [...]]]></description>
			<content:encoded><![CDATA[<p>This post should probably be called &#8220;The Power of Twitter.&#8221;  I&#8217;ve said it before, I&#8217;ll say it again: I love Twitter.  I mostly follow SQL Server people, so it&#8217;s become a great source of new information and help <span style="text-decoration: line-through;">when I feel like banging my head against the wall</span> when I get stumped.</p>
<p>So last week, <a href="http://sqlblog.com/blogs/jonathan_kehayias" target="_blank">Jonathan Kehayias</a> (<a href="http://twitter.com/jmkehayias" target="_blank">@jmkehayias</a>) posted a link to a <a href="http://social.msdn.microsoft.com/Forums/en-US/sqldatabaseengine/thread/71814032-cd8d-4802-80de-7fb2bee80f41" target="_blank">missing index script</a> on the MSDN forums.  Jonathan&#8217;s script is modified from something he put together for a question posed by <a href="http://facility9.com" target="_blank">Jeremiah Peschka</a> (<a href="http://twitter.com/peschkaj" target="_blank">@peschkaj</a>).  </p>
<p>Jonathan&#8217;s script intrigued me.  I&#8217;d never tried to search a query plan&#8217;s XML before, and it certainly presents some interesting possibilities.  After dealing with a missing index in production a few weeks ago (caused by an index change), I thought it&#8217;d be a great idea to put a regular monitor in place.  </p>
<p>Everything was going well until I ran into a problem where I couldn&#8217;t get the proc name returned.  The results spanned numerous databases; I had the object_id and database_id, but I wanted to store the proc name instead.  I tried several different methods, including sp_msforeachdb and sp_executeSQL, and while I had a working solution, it was a little more clunky than I liked.  So I asked my awesome followers on Twitter for any tips and within minutes I had half a dozen responses.  In the end, <a href="http://twitter.com/MladenPrajdic" target="_blank">@MladenPrajdic</a> solved my problem with a pretty simple solution: put &#8216;Use ?;&#8217; at the start of my sp_msforeachdb statement.  Thanks again, Mladen!</p>
<p>I&#8217;ve now had this process running on my server for a few days now, with good success.  The stored procedure below will return the database name, proc name, and query plan XML for any stored proc with a missing index.  This is a centralized proc that will store the results in a table for later action.  If you click on the XML, you should see the actual query plan with the missing index details.  Because this looks at cached query plans, your best bet is to run it fairly regularly (maybe daily) to increase your chances of catching any problem procs.</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/* Create a stored procedure skeleton */</span>
<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_missingIndexStoredProc_sp'</span><span style="color: #808080;">&#41;</span>, N<span style="color: #FF0000;">'IsProcedure'</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">IS</span> Null
<span style="color: #0000FF;">BEGIN</span>
    <span style="color: #0000FF;">EXECUTE</span> <span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Create Procedure dbo.dba_missingIndexStoredProc_sp As Print '</span><span style="color: #FF0000;">'Hello World!'</span><span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Procedure dba_missingIndexStoredProc_sp created.'</span>, <span style="color: #000;">10</span>, <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>;
<span style="color: #0000FF;">END</span>;
Go
&nbsp;
<span style="color: #008080;">/* Drop our table if it already exists */</span>
<span style="color: #0000FF;">IF</span> Exists<span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #FF00FF;">OBJECT_ID</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> N<span style="color: #FF0000;">'dba_missingIndexStoredProc'</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">BEGIN</span>
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">dba_missingIndexStoredProc</span>
    <span style="color: #0000FF;">PRINT</span> <span style="color: #FF0000;">'dba_missingIndexStoredProc table dropped!'</span>;
<span style="color: #0000FF;">END</span>
&nbsp;
<span style="color: #008080;">/* Create our table */</span>
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">dba_missingIndexStoredProc</span>
<span style="color: #808080;">&#40;</span>
      missingIndexSP_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
    , 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>        Not Null
    , databaseID        <span style="color: #0000FF;">INT</span>                 Not Null
    , objectName        <span style="color: #0000FF;">VARCHAR</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
    , query_plan        xml                 Not Null
    , executionDate     <span style="color: #0000FF;">SMALLDATETIME</span>       Not Null
&nbsp;
    <span style="color: #0000FF;">CONSTRAINT</span> PK_missingIndexStoredProc
        <span style="color: #0000FF;">PRIMARY</span> <span style="color: #0000FF;">KEY</span> <span style="color: #0000FF;">CLUSTERED</span><span style="color: #808080;">&#40;</span>missingIndexSP_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_missingIndexStoredProc Table Created'</span>;
&nbsp;
<span style="color: #008080;">/* Configure our settings */</span>
<span style="color: #0000FF;">SET</span> ANSI_Nulls <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">SET</span> Quoted_Identifier <span style="color: #0000FF;">ON</span>;
Go
&nbsp;
<span style="color: #0000FF;">ALTER</span> <span style="color: #0000FF;">PROCEDURE</span> dbo.<span style="color: #202020;">dba_missingIndexStoredProc_sp</span>
&nbsp;
        <span style="color: #008080;">/* Declare Parameters */</span>
            @lastExecuted_inDays    <span style="color: #0000FF;">INT</span> <span style="color: #808080;">=</span> <span style="color: #000;">7</span>
          , @minExecutionCount      <span style="color: #0000FF;">INT</span> <span style="color: #808080;">=</span> <span style="color: #000;">7</span>
          , @logResults             <span style="color: #0000FF;">BIT</span> <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
          , @displayResults         <span style="color: #0000FF;">BIT</span> <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
&nbsp;
<span style="color: #0000FF;">AS</span>
<span style="color: #008080;">/*********************************************************************************
    Name:       dba_missingIndexStoredProc_sp
&nbsp;
    Author:     Michelle Ufford, http://sqlfool.com
&nbsp;
    Purpose:    Retrieves stored procedures with missing indexes in their
                cached query plans.
&nbsp;
                @lastExecuted_inDays = number of days old the cached query plan
                                       can be to still appear in the results;
                                       the HIGHER the number, the longer the
                                       execution time.
&nbsp;
                @minExecutionCount = minimum number of executions the cached
                                     query plan can have to still appear 
                                     in the results; the LOWER the number,
                                     the longer the execution time.
&nbsp;
                @logResults = store results in dba_missingIndexStoredProc
&nbsp;
                @displayResults = return results to the caller
&nbsp;
    Notes:      This is not 100% guaranteed to catch all missing indexes in
                a stored procedure.  It will only catch it if the stored proc's
                query plan is still in cache.  Run regularly to help minimize
                the chance of missing a proc.
&nbsp;
    Called by:  DBA and/or SQL Agent Job
&nbsp;
    Date        User    Description
    ----------------------------------------------------------------------------
    2009-03-02  MFU     Initial Release for public consumption
*********************************************************************************
    Exec dbo.dba_missingIndexStoredProc_sp
          @lastExecuted_inDays  = 30
        , @minExecutionCount    = 5
        , @logResults           = 1
        , @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> @currentDateTime <span style="color: #0000FF;">SMALLDATETIME</span>;
&nbsp;
    <span style="color: #0000FF;">SET</span> @currentDateTime <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: #0000FF;">DECLARE</span> @plan_handles <span style="color: #0000FF;">TABLE</span>
    <span style="color: #808080;">&#40;</span>
        plan_handle     <span style="color: #0000FF;">VARBINARY</span><span style="color: #808080;">&#40;</span><span style="color: #000;">64</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;">TABLE</span> #missingIndexes
    <span style="color: #808080;">&#40;</span>
          databaseID    <span style="color: #0000FF;">INT</span>             Not Null
        , objectID      <span style="color: #0000FF;">INT</span>             Not Null
        , query_plan    xml             Not Null
&nbsp;
        <span style="color: #0000FF;">CONSTRAINT</span> PK_temp_missingIndexes <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
        <span style="color: #808080;">&#41;</span>
    <span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #0000FF;">BEGIN</span> Try
&nbsp;
        <span style="color: #008080;">/* Perform some data validation */</span>
        <span style="color: #0000FF;">IF</span> @logResults <span style="color: #808080;">=</span> <span style="color: #000;">0</span> And @displayResults <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
        <span style="color: #0000FF;">BEGIN</span>
&nbsp;
            <span style="color: #008080;">/* Log the fact that there were open transactions */</span>
            <span style="color: #0000FF;">EXECUTE</span> dbo.<span style="color: #202020;">dba_logError_sp</span>
                  @errorType            <span style="color: #808080;">=</span> <span style="color: #FF0000;">'app'</span>
                , @app_errorProcedure   <span style="color: #808080;">=</span> <span style="color: #FF0000;">'dba_missingIndexStoredProc_sp'</span>
                , @app_errorMessage     <span style="color: #808080;">=</span> <span style="color: #FF0000;">'@logResults = 0 and @displayResults = 0; no action taken, exiting stored proc.'</span>
                , @forceExit            <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
                , @returnError          <span style="color: #808080;">=</span> <span style="color: #000;">1</span>;  
&nbsp;
        <span style="color: #0000FF;">END</span>;
&nbsp;
        <span style="color: #0000FF;">BEGIN</span> <span style="color: #0000FF;">TRANSACTION</span>;
&nbsp;
        <span style="color: #008080;">/* Retrieve distinct plan handles to minimize dm_exec_query_plan lookups */</span>
        <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> @plan_handles
        <span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">DISTINCT</span> plan_handle
        <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">dm_exec_query_stats</span>
        <span style="color: #0000FF;">WHERE</span> last_execution_time <span style="color: #808080;">&gt;</span> <span style="color: #FF00FF;">DATEADD</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">DAY</span>, <span style="color: #808080;">-</span>@lastExecuted_inDays, @currentDateTime<span style="color: #808080;">&#41;</span>
            And execution_count <span style="color: #808080;">&gt;</span> @minExecutionCount;
&nbsp;
        <span style="color: #0000FF;">WITH</span> xmlNameSpaces <span style="color: #808080;">&#40;</span>
            <span style="color: #0000FF;">DEFAULT</span> <span style="color: #FF0000;">'http://schemas.microsoft.com/sqlserver/2004/07/showplan'</span>
        <span style="color: #808080;">&#41;</span>
&nbsp;
        <span style="color: #008080;">/* Retrieve our query plan's XML if there's a missing index */</span>
        <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> #missingIndexes
        <span style="color: #0000FF;">SELECT</span> deqp.<span style="color: #808080;">&#91;</span>dbid<span style="color: #808080;">&#93;</span>
            , deqp.<span style="color: #202020;">objectid</span>
            , deqp.<span style="color: #202020;">query_plan</span> 
        <span style="color: #0000FF;">FROM</span> @plan_handles <span style="color: #0000FF;">AS</span> ph
        Cross Apply sys.<span style="color: #202020;">dm_exec_query_plan</span><span style="color: #808080;">&#40;</span>ph.<span style="color: #202020;">plan_handle</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> deqp 
        <span style="color: #0000FF;">WHERE</span> deqp.<span style="color: #202020;">query_plan</span>.<span style="color: #202020;">exist</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'//MissingIndex'</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
            And deqp.<span style="color: #202020;">objectid</span> <span style="color: #0000FF;">IS</span> Not Null;
&nbsp;
        <span style="color: #008080;">/* Do we want to store the results of our process? */</span>
        <span style="color: #0000FF;">IF</span> @logResults <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
        <span style="color: #0000FF;">BEGIN</span>
            <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> dbo.<span style="color: #202020;">dba_missingIndexStoredProc</span>
            <span style="color: #0000FF;">EXECUTE</span> sp_msForEachDB <span style="color: #FF0000;">'Use ?; 
                                    Select '</span><span style="color: #FF0000;">'?'</span><span style="color: #FF0000;">'
                                        , mi.databaseID
                                        , Object_Name(o.object_id)
                                        , o.object_id
                                        , mi.query_plan
                                        , GetDate()
                                    From sys.objects As o 
                                    Join #missingIndexes As mi 
                                        On o.object_id = mi.objectID 
                                    Where databaseID = DB_ID();'</span>;
&nbsp;
        <span style="color: #0000FF;">END</span>
        <span style="color: #008080;">/* We're not logging it, so let's display it */</span>
        <span style="color: #0000FF;">ELSE</span>
        <span style="color: #0000FF;">BEGIN</span>
            <span style="color: #0000FF;">EXECUTE</span> sp_msForEachDB <span style="color: #FF0000;">'Use ?; 
                                    Select '</span><span style="color: #FF0000;">'?'</span><span style="color: #FF0000;">'
                                        , mi.databaseID
                                        , Object_Name(o.object_id)
                                        , o.object_id
                                        , mi.query_plan
                                        , GetDate()
                                    From sys.objects As o 
                                    Join #missingIndexes As mi 
                                        On o.object_id = mi.objectID 
                                    Where databaseID = DB_ID();'</span>;
        <span style="color: #0000FF;">END</span>;
&nbsp;
        <span style="color: #008080;">/* See above; this part will only work if we've 
           logged our data. */</span>
        <span style="color: #0000FF;">IF</span> @displayResults <span style="color: #808080;">=</span> <span style="color: #000;">1</span> And @logResults <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
        <span style="color: #0000FF;">BEGIN</span>
            <span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">*</span>
            <span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">dba_missingIndexStoredProc</span>
            <span style="color: #0000FF;">WHERE</span> executionDate <span style="color: #808080;">&gt;=</span> @currentDateTime;
        <span style="color: #0000FF;">END</span>;
&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: #008080;">/* Clean-Up! */</span>
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">TABLE</span> #missingIndexes;
&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>Not know what &#8220;EXECUTE dbo.dba_logError_sp;&#8221; is doing?  Check out my blog post on <a href="http://sqlfool.com/2008/12/error-handling-in-t-sql/">Error Handling in T-SQL</a>.</p>
<p>HTH!</p>
<p>Michelle</p>
<p>Source: <a href="http://sqlfool.com/2009/03/find-missing-indexes/">http://sqlfool.com/2009/03/find-missing-indexes/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/03/find-missing-indexes/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
