<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>SQL Fool &#187; Performance &amp; Tuning</title>
	<atom:link href="http://sqlfool.com/category/performance-tuning/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>Filtered Indexes Work-Around</title>
		<link>http://sqlfool.com/2010/02/filtered-indexes-work-around/</link>
		<comments>http://sqlfool.com/2010/02/filtered-indexes-work-around/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 16:00:14 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[SQL Tips]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[2008]]></category>
		<category><![CDATA[filtered indexes]]></category>
		<category><![CDATA[performance]]></category>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/* Apply compression to your partitioned table */</span>
<span style="color: #0000FF;">ALTER</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">yourTableName</span>
Rebuild Partition <span style="color: #808080;">=</span> All
<span style="color: #0000FF;">WITH</span> 
<span style="color: #808080;">&#40;</span>
      Data_Compression <span style="color: #808080;">=</span> Page <span style="color: #0000FF;">ON</span> Partitions<span style="color: #808080;">&#40;</span><span style="color: #000;">1</span> <span style="color: #0000FF;">TO</span> <span style="color: #000;">9</span><span style="color: #808080;">&#41;</span>
    , Data_Compression <span style="color: #808080;">=</span> <span style="color: #0000FF;">ROW</span>  <span style="color: #0000FF;">ON</span> Partitions<span style="color: #808080;">&#40;</span><span style="color: #000;">10</span> <span style="color: #0000FF;">TO</span> <span style="color: #000;">11</span><span style="color: #808080;">&#41;</span> 
    , Data_Compression <span style="color: #808080;">=</span> <span style="color: #0000FF;">NONE</span> <span style="color: #0000FF;">ON</span> Partitions<span style="color: #808080;">&#40;</span><span style="color: #000;">12</span><span style="color: #808080;">&#41;</span>
<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #008080;">/* Apply compression to your partitioned index */</span>
<span style="color: #0000FF;">ALTER</span> <span style="color: #0000FF;">INDEX</span> YourPartitionedIndex
    <span style="color: #0000FF;">ON</span> dbo.<span style="color: #202020;">yourTableName</span>
    Rebuild Partition <span style="color: #808080;">=</span> All
    <span style="color: #0000FF;">WITH</span> 
    <span style="color: #808080;">&#40;</span>
      Data_Compression <span style="color: #808080;">=</span> Page <span style="color: #0000FF;">ON</span> Partitions<span style="color: #808080;">&#40;</span><span style="color: #000;">1</span> <span style="color: #0000FF;">TO</span> <span style="color: #000;">9</span><span style="color: #808080;">&#41;</span>
    , Data_Compression <span style="color: #808080;">=</span> <span style="color: #0000FF;">ROW</span>  <span style="color: #0000FF;">ON</span> Partitions<span style="color: #808080;">&#40;</span><span style="color: #000;">10</span> <span style="color: #0000FF;">TO</span> <span style="color: #000;">11</span><span style="color: #808080;">&#41;</span> 
    , Data_Compression <span style="color: #808080;">=</span> <span style="color: #0000FF;">NONE</span> <span style="color: #0000FF;">ON</span> Partitions<span style="color: #808080;">&#40;</span><span style="color: #000;">12</span><span style="color: #808080;">&#41;</span>
    <span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #008080;">/* Apply compression to your unpartitioned index */</span>
<span style="color: #0000FF;">ALTER</span> <span style="color: #0000FF;">INDEX</span> YourUnpartitionedIndex
    <span style="color: #0000FF;">ON</span> dbo.<span style="color: #202020;">yourTableName</span>
    Rebuild <span style="color: #0000FF;">WITH</span> <span style="color: #808080;">&#40;</span>Data_Compression <span style="color: #808080;">=</span> <span style="color: #0000FF;">ROW</span><span style="color: #808080;">&#41;</span>;</pre></div></div>

<p>A couple of things to note.  In all of our proof-of-concept testing, we found that compression significantly reduced query execution time, reads (IO), and storage.  However, CPU was also increased significantly.  The results were more dramatic, both good and bad, with page compression versus row compression.  Still, for our older partitions, which aren&#8217;t queried regularly, it made sense to turn on page compression.  The newer partitions receive row compression, and the newest partitions, which are still queried very regularly by routine processes, were left completely uncompressed.  This seems to strike a nice balance in our environment, but of course, results will vary depending on how you use your data.</p>
<p>Something to be aware of is that compressing your clustered index does *not* compress your non-clustered indexes; those are separate operations.  Lastly, for those who are curious, it took us about 1 minute to apply row compression and about 7 minutes to apply page compression to partitions averaging 30 million rows.</p>
<p>Looking for more information on table partitioning?  Check out my <a href="http://sqlfool.com/2008/11/partitioning-101/" target="_blank">overview of partitioning</a>, my <a href="http://sqlfool.com/2008/11/102/" target="_blank">example code</a>, and my article on <a href="http://sqlfool.com/2008/12/indexing-for-partitioned-tables/" target="_blank">indexing on partitioned tables</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/10/partitioning-tricks/feed/</wfw:commentRss>
		<slash:comments>3</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>Bored this summer?</title>
		<link>http://sqlfool.com/2009/07/bored-this-summer/</link>
		<comments>http://sqlfool.com/2009/07/bored-this-summer/#comments</comments>
		<pubDate>Sat, 11 Jul 2009 21:18:56 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Miscellaneous]]></category>
		<category><![CDATA[PASS]]></category>
		<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[380PASS]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[shameless begging]]></category>
		<category><![CDATA[SQL Saturday]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1089</guid>
		<description><![CDATA[Bored this summer?  Do you like to help others?  Do you have too much free time?  Do you find yourself thinking, &#8220;Man, I really should spend more time indoors.&#8221;  If you answered &#8220;yes&#8221; to all any of these questions, then have I got a proposition for you!

What could be more fun [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: left;">Bored this summer?  Do you like to help others?  Do you have too much free time?  Do you find yourself thinking, &#8220;Man, I really should spend more time indoors.&#8221;  If you answered &#8220;yes&#8221; to <span style="text-decoration: line-through;">all</span> any of these questions, then have I got a proposition for you!</p>
<p><em><a href="http://www.imdb.com/title/tt0205000/" target="_blank"><div class="wp-caption aligncenter" style="width: 410px"><img title="Sorry, guys, not that kind of proposition" src="http://kurtatdisney.files.wordpress.com/2009/04/deuce_bigalow_male_gigolo_ver2.jpg" alt="Sorry, guys, not that kind of proposition" width="400" height="596" /><p class="wp-caption-text">Sorry, guys, not that kind of proposition</p></div></a></em></p>
<p>What could be more fun than getting second-degree burns at the waterpark, you ask?  Volunteering on the <a href="http://www.sqlpass.org/Community/SIGs/PerformanceSIG.aspx" target="_blank">PASS Performance SIG</a>!  That&#8217;s right, we&#8217;re looking for a few good women and men to join our ranks as content contributors.  Specifically, we&#8217;re looking for people to write articles and/or host LiveMeeting events on performance-related topics.  Not a performance expert?  This can be a great way for you to learn more.</p>
<p>In case I scared you off in my opening paragraph, let me assure you that it really does not take that much time to be a volunteer.  Just 3-4 hours a month can be a huge help.  We&#8217;re also looking for contributors of all experience levels, so if you&#8217;re only comfortable writing intro-level articles, that&#8217;s definitely okay.</p>
<p>Oh, and while I&#8217;m begging for volunteers, <a href="http://sqlfool.com/2009/06/east-iowa-sql-saturday-call-for-speakers/" target="_blank">we&#8217;re still looking for speakers</a> for the <a href="http://sqlsaturday.380pass.org/" target="_blank">SQL Saturday in East Iowa</a>.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>If you&#8217;re interested in either, then please send me an e-mail at michelle <em>at</em> sqlfool <em>dot</em> com for more information.</p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/07/bored-this-summer/feed/</wfw:commentRss>
		<slash:comments>0</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>PASS Summit 2009</title>
		<link>http://sqlfool.com/2009/06/pass-summit-2009/</link>
		<comments>http://sqlfool.com/2009/06/pass-summit-2009/#comments</comments>
		<pubDate>Sun, 14 Jun 2009 20:15:25 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[PASS]]></category>
		<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[Presentations]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[presentation]]></category>
		<category><![CDATA[Summit]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1052</guid>
		<description><![CDATA[My abstract for PASS Summit 2009 was accepted!  Woot!  You may not be able to see it from where you&#8217;re sitting, but I&#8217;m doing the happy dance.   
In case you missed my original post on my abstract submission, here&#8217;s what I&#8217;ll be presenting on:
Super Bowl, Super Load &#8211; A Look at [...]]]></description>
			<content:encoded><![CDATA[<p>My abstract for <a href="http://summit2009.sqlpass.org/AboutSummit.aspx" target="_blank">PASS Summit 2009</a> was accepted!  Woot!  You may not be able to see it from where you&#8217;re sitting, but I&#8217;m doing the happy dance.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>In case you missed <a href="http://sqlfool.com/2009/04/pass-summit-my-abstract-deadline-extended/" target="_blank">my original post</a> on my abstract submission, here&#8217;s what I&#8217;ll be presenting on:</p>
<p><strong>Super Bowl, Super Load &#8211; A Look at Performance Tuning for VLDB’s</strong></p>
<p><em>Few DBA’s have the opportunity to experience a real-life load test in their production environment. Michelle Ufford works for GoDaddy.com, a company that has experienced phenomenal success with its Super Bowl ads. These ads are designed to drive traffic to the company’s websites, which puts the database servers under high load. In her presentation, Michelle will explore the performance tuning techniques that have resulted in an 80% reduction in server response times and allowed her VLDB’s to reach rates of 27k transactions per second. Topics will include vertical and horizontal partitioning, bulk operations, table design, and indexing.</em></p>
<p>Do you read my blog?  Do I read yours?  Do we exchange weird messages on Twitter?  Do you have free cookies?  If you&#8217;re going to to the PASS Summit and answered &#8220;yes&#8221; to any of these questions, then I want to meet you!  Make sure to say &#8220;hi&#8221; to me in Seattle.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><img src="http://summit2009.sqlpass.org/Portals/0/2009PASS_Signature03.gif"></p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/06/pass-summit-2009/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Random Number Generator in T-SQL</title>
		<link>http://sqlfool.com/2009/06/random-number-generator-in-tsql/</link>
		<comments>http://sqlfool.com/2009/06/random-number-generator-in-tsql/#comments</comments>
		<pubDate>Thu, 04 Jun 2009 13:21:17 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[SQL Tips]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[random number]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[TSQL]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=489</guid>
		<description><![CDATA[Ever need to generate a random number in T-SQL?  I have, on a couple of different occasions.  I&#8217;m pretty sure that there&#8217;s several different ways of doing this in T-SQL, but here&#8217;s what I use:

DECLARE @maxRandomValue TINYINT = 100
	, @minRandomValue TINYINT = 0;
&#160;
SELECT CAST&#40;&#40;&#40;@maxRandomValue + 1&#41; - @minRandomValue&#41; 
	* RAND&#40;&#41; + @minRandomValue AS [...]]]></description>
			<content:encoded><![CDATA[<p>Ever need to generate a random number in T-SQL?  I have, on a couple of different occasions.  I&#8217;m pretty sure that there&#8217;s several different ways of doing this in T-SQL, but here&#8217;s what I use:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">DECLARE</span> @maxRandomValue <span style="color: #0000FF;">TINYINT</span> <span style="color: #808080;">=</span> <span style="color: #000;">100</span>
	, @minRandomValue <span style="color: #0000FF;">TINYINT</span> <span style="color: #808080;">=</span> <span style="color: #000;">0</span>;
&nbsp;
<span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#40;</span>@maxRandomValue <span style="color: #808080;">+</span> <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">-</span> @minRandomValue<span style="color: #808080;">&#41;</span> 
	<span style="color: #808080;">*</span> <span style="color: #FF00FF;">RAND</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> @minRandomValue <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">TINYINT</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'randomNumber'</span>;</pre></div></div>

<p>This approach uses the <a href="http://msdn.microsoft.com/en-us/library/ms177610.aspx" target="_blank">RAND()</a> function to generate a random seed; it also ensures that the value returned is between the specified min and max value.  I&#8217;ve been using this method in one stored procedure that&#8217;s called a couple of hundred times per second, and it seems to perform pretty well.</p>
<p>What method do YOU use to generate a random number?  Is it faster than this method?  </p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/06/random-number-generator-in-tsql/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Overhead in Non-Unique Clustered Indexes</title>
		<link>http://sqlfool.com/2009/05/overhead-i-non-unique-clustered-indexes/</link>
		<comments>http://sqlfool.com/2009/05/overhead-i-non-unique-clustered-indexes/#comments</comments>
		<pubDate>Thu, 21 May 2009 13:22:29 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Internals]]></category>
		<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[indexes]]></category>
		<category><![CDATA[performance]]></category>

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

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">USE</span> sandbox;
Go
&nbsp;
<span style="color: #008080;">/* Unique, clustered index, no duplicate values */</span>
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">uniqueClustered</span>
<span style="color: #808080;">&#40;</span>
      myDate    <span style="color: #0000FF;">DATE</span>        Not Null
    , myNumber  <span style="color: #0000FF;">INT</span>         Not Null
    , myColumn  <span style="color: #0000FF;">CHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">995</span><span style="color: #808080;">&#41;</span>   Not Null
<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">UNIQUE</span> <span style="color: #0000FF;">CLUSTERED</span> <span style="color: #0000FF;">INDEX</span> CIX_uniqueClustered
    <span style="color: #0000FF;">ON</span> dbo.<span style="color: #202020;">uniqueClustered</span><span style="color: #808080;">&#40;</span>myDate<span style="color: #808080;">&#41;</span>;
&nbsp;
&nbsp;
<span style="color: #008080;">/* Non-unique clustered index, but no duplicate values */</span>
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">nonUniqueNoDups</span>
<span style="color: #808080;">&#40;</span>
      myDate    <span style="color: #0000FF;">DATE</span>        Not Null
    , myNumber  <span style="color: #0000FF;">INT</span>         Not Null
    , myColumn  <span style="color: #0000FF;">CHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">995</span><span style="color: #808080;">&#41;</span>   Not Null
<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">CLUSTERED</span> <span style="color: #0000FF;">INDEX</span> CIX_nonUniqueNoDups
    <span style="color: #0000FF;">ON</span> dbo.<span style="color: #202020;">nonUniqueNoDups</span><span style="color: #808080;">&#40;</span>myDate<span style="color: #808080;">&#41;</span>;
&nbsp;
&nbsp;
<span style="color: #008080;">/* Non-unique clustered index, duplicate values */</span>
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">nonUniqueDuplicates</span>
<span style="color: #808080;">&#40;</span>
      myDate    <span style="color: #0000FF;">DATE</span>        Not Null
    , myNumber  <span style="color: #0000FF;">INT</span>         Not Null
    , myColumn  <span style="color: #0000FF;">CHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">995</span><span style="color: #808080;">&#41;</span>   Not Null
<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">CLUSTERED</span> <span style="color: #0000FF;">INDEX</span> CIX_nonUniqueDuplicates
    <span style="color: #0000FF;">ON</span> dbo.<span style="color: #202020;">nonUniqueDuplicates</span><span style="color: #808080;">&#40;</span>myDate<span style="color: #808080;">&#41;</span>;</pre></div></div>

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

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/* Populate some test data */</span>
<span style="color: #0000FF;">SET</span> <span style="color: #0000FF;">NOCOUNT</span> <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">DECLARE</span> @myDate <span style="color: #0000FF;">DATE</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'1990-01-01'</span>
    , @myNumber <span style="color: #0000FF;">INT</span> <span style="color: #808080;">=</span> <span style="color: #000;">1</span>;
&nbsp;
<span style="color: #0000FF;">WHILE</span> @myDate <span style="color: #808080;">&lt;</span> <span style="color: #FF0000;">'2010-01-01'</span>
<span style="color: #0000FF;">BEGIN</span>
&nbsp;
    <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> dbo.<span style="color: #202020;">uniqueClustered</span>
    <span style="color: #0000FF;">SELECT</span> @myDate, @myNumber, <span style="color: #FF0000;">'data'</span>;
&nbsp;
    <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> dbo.<span style="color: #202020;">nonUniqueNoDups</span>
    <span style="color: #0000FF;">SELECT</span> @myDate, @myNumber, <span style="color: #FF0000;">'data'</span>;
&nbsp;
    <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> dbo.<span style="color: #202020;">nonUniqueDuplicates</span>
    <span style="color: #0000FF;">SELECT</span> <span style="color: #FF0000;">'2009-01-01'</span>, @myNumber, <span style="color: #FF0000;">'data'</span>;
&nbsp;
    <span style="color: #0000FF;">SELECT</span> @myDate <span style="color: #808080;">=</span> <span style="color: #FF00FF;">DATEADD</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">DAY</span>, <span style="color: #000;">1</span>, @myDate<span style="color: #808080;">&#41;</span>
        , @myNumber <span style="color: #808080;">+=</span> <span style="color: #000;">1</span>;
&nbsp;
<span style="color: #0000FF;">END</span>;</pre></div></div>

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

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

<p>Here&#8217;s the results:</p>

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

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

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

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

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

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

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

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

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

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

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

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

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

<p>The first record, Slot 0, looks exactly the same as in the previous table; the UNIQUIFIER is 0 and the row size is 1009.  The second record (Slot 1), however, now has a UNIQUIFIER value of 1 and the row size is 1017.  If you notice, the &#8220;Record Attributes&#8221; of Slot 1 are also different, with the addition of &#8220;VARIABLE_COLUMNS.&#8221;  This is because the UNIQUIFIER is stored as a variable column.  The extra 8 bytes of overhead break down to 4 bytes to store the UNIQUIFIER, 2 bytes to store the variable column offset, and 2 bytes to store the variable count.  The tables we created used all fixed-length columns; you may notice some minor overhead differences if your table already contains variable columns.</p>
<p>To summarize, there is indeed a difference in the page structure between a unique clustered index and a non-unique clustered index; however, there&#8217;s only a possible performance and space impact when storing duplicate clustered key values.  So there you go, more detail than you ever wanted to know about clustered indexes and uniqueness!</p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/05/overhead-i-non-unique-clustered-indexes/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
