<?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; partitioning</title>
	<atom:link href="http://sqlfool.com/tag/partitioning/feed/" rel="self" type="application/rss+xml" />
	<link>http://sqlfool.com</link>
	<description>Adventures in SQL Tuning - a blog for the rest of us</description>
	<lastBuildDate>Fri, 16 Jul 2010 14:34:11 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Index Interrogation for SQL Server 2008</title>
		<link>http://sqlfool.com/2010/06/index-interrogation-for-sql-server-2008/</link>
		<comments>http://sqlfool.com/2010/06/index-interrogation-for-sql-server-2008/#comments</comments>
		<pubDate>Fri, 04 Jun 2010 19:55:17 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Internals]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[T-SQL Scripts]]></category>
		<category><![CDATA[indexes]]></category>
		<category><![CDATA[partitioning]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[TSQL]]></category>

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

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

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

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


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

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

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

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

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

<p>You can also download it here: <a href="http://sqlfool.com/scripts/dba_indexDefrag_sp_v40_public.txt" target="_blank">dba_indexDefrag_sp_v40_public.txt</a></p>
<p>I've had this latest version in production on terabyte-size databases running SQL Server 2005 and 2008 Enterprise editions for the last 3 months, where it runs nightly without issue.  I've also had numerous beta testers report success in their environments, too.  But to be safe, make sure to keep an eye on it the first time it runs to ensure you understand the impact on your server.</p>
<p>Enjoy!</p>
<p>Michelle</p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2010/04/index-defrag-script-v4-0/feed/</wfw:commentRss>
		<slash:comments>45</slash:comments>
		</item>
		<item>
		<title>Replication Bug with Partitioned Tables</title>
		<link>http://sqlfool.com/2009/11/replication-bug-with-partitioned-tables/</link>
		<comments>http://sqlfool.com/2009/11/replication-bug-with-partitioned-tables/#comments</comments>
		<pubDate>Mon, 23 Nov 2009 14:48:54 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Miscellaneous]]></category>
		<category><![CDATA[SQL Tips]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[bug]]></category>
		<category><![CDATA[partitioning]]></category>
		<category><![CDATA[replication]]></category>
		<category><![CDATA[SQL Server 2005]]></category>

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

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

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

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

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

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

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

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">IF</span> Not Exists<span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">&#91;</span><span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#93;</span> <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">tables</span> <span style="color: #0000FF;">WHERE</span> name <span style="color: #808080;">=</span> N<span style="color: #FF0000;">'dba_indexDefragLog'</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">BEGIN</span>
    <span style="color: #008080;">-- Drop Table dbo.dba_indexDefragLog</span>
    <span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">dba_indexDefragLog</span>
    <span style="color: #808080;">&#40;</span>
          indexDefrag_id    <span style="color: #0000FF;">INT</span> <span style="color: #0000FF;">IDENTITY</span><span style="color: #808080;">&#40;</span><span style="color: #000;">1</span>,<span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>   Not Null
        , databaseID        <span style="color: #0000FF;">INT</span>                 Not Null
        , databaseName      <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>       Not Null
        , objectID          <span style="color: #0000FF;">INT</span>                 Not Null
        , objectName        <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>       Not Null
        , indexID           <span style="color: #0000FF;">INT</span>                 Not Null
        , indexName         <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>       Not Null
        , partitionNumber   <span style="color: #0000FF;">SMALLINT</span>            Not Null
        , fragmentation     <span style="color: #0000FF;">FLOAT</span>               Not Null
        , page_count        <span style="color: #0000FF;">INT</span>                 Not Null
        , dateTimeStart     <span style="color: #0000FF;">DATETIME</span>            Not Null
        , durationSeconds   <span style="color: #0000FF;">INT</span>                 Not Null
        <span style="color: #0000FF;">CONSTRAINT</span> PK_indexDefragLog <span style="color: #0000FF;">PRIMARY</span> <span style="color: #0000FF;">KEY</span> <span style="color: #0000FF;">CLUSTERED</span> <span style="color: #808080;">&#40;</span>indexDefrag_id<span style="color: #808080;">&#41;</span>
    <span style="color: #808080;">&#41;</span>
&nbsp;
    <span style="color: #0000FF;">PRINT</span> <span style="color: #FF0000;">'dba_indexDefragLog Table Created'</span>;
<span style="color: #0000FF;">END</span>
&nbsp;
<span style="color: #0000FF;">IF</span> <span style="color: #FF00FF;">OBJECTPROPERTY</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'dbo.dba_indexDefrag_sp'</span><span style="color: #808080;">&#41;</span>, N<span style="color: #FF0000;">'IsProcedure'</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
<span style="color: #0000FF;">BEGIN</span>
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">PROCEDURE</span> dbo.<span style="color: #202020;">dba_indexDefrag_sp</span>;
    <span style="color: #0000FF;">PRINT</span> <span style="color: #FF0000;">'Procedure dba_indexDefrag_sp dropped'</span>;
<span style="color: #0000FF;">END</span>;
Go
&nbsp;
&nbsp;
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">PROCEDURE</span> dbo.<span style="color: #202020;">dba_indexDefrag_sp</span>
&nbsp;
    <span style="color: #008080;">/* Declare Parameters */</span>
      @minFragmentation     <span style="color: #0000FF;">FLOAT</span>           <span style="color: #808080;">=</span> <span style="color: #000;">5.0</span>  
        <span style="color: #008080;">/* in percent, will not defrag if fragmentation less than specified */</span>
    , @rebuildThreshold     <span style="color: #0000FF;">FLOAT</span>           <span style="color: #808080;">=</span> <span style="color: #000;">30.0</span>  
        <span style="color: #008080;">/* in percent, greater than @rebuildThreshold will result in rebuild instead of reorg */</span>
    , @executeSQL           <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">1</span>     
        <span style="color: #008080;">/* 1 = execute; 0 = print command only */</span>
    , @<span style="color: #0000FF;">DATABASE</span>             <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>    <span style="color: #808080;">=</span> Null
        <span style="color: #008080;">/* Option to specify a database name; null will return all */</span>
    , @tableName            <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>   <span style="color: #808080;">=</span> Null  <span style="color: #008080;">-- databaseName.schema.tableName</span>
        <span style="color: #008080;">/* Option to specify a table name; null will return all */</span>
    , @onlineRebuild        <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">1</span>     
        <span style="color: #008080;">/* 1 = online rebuild; 0 = offline rebuild; only in Enterprise */</span>
    , @maxDopRestriction    <span style="color: #0000FF;">TINYINT</span>         <span style="color: #808080;">=</span> Null
        <span style="color: #008080;">/* Option to restrict the number of processors for the operation; only in Enterprise */</span>
    , @printCommands        <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">0</span>     
        <span style="color: #008080;">/* 1 = print commands; 0 = do not print commands */</span>
    , @printFragmentation   <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
        <span style="color: #008080;">/* 1 = print fragmentation prior to defrag; 
           0 = do not print */</span>
    , @defragDelay          <span style="color: #0000FF;">CHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">8</span><span style="color: #808080;">&#41;</span>         <span style="color: #808080;">=</span> <span style="color: #FF0000;">'00:00:05'</span>
        <span style="color: #008080;">/* time to wait between defrag commands */</span>
    , @debugMode            <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
        <span style="color: #008080;">/* display some useful comments to help determine if/where issues occur */</span>
<span style="color: #0000FF;">AS</span>
<span style="color: #008080;">/*********************************************************************************
    Name:       dba_indexDefrag_sp
&nbsp;
    Author:     Michelle Ufford, http://sqlfool.com
&nbsp;
    Purpose:    Defrags all indexes for one or more databases
&nbsp;
    Notes:
&nbsp;
    CAUTION: TRANSACTION LOG SIZE MUST BE MONITORED CLOSELY WHEN DEFRAGMENTING.
&nbsp;
      @minFragmentation     defaulted to 10%, will not defrag if fragmentation 
                            is less than that
&nbsp;
      @rebuildThreshold     defaulted to 30% as recommended by Microsoft in BOL;
                            greater than 30% will result in rebuild instead
&nbsp;
      @executeSQL           1 = execute the SQL generated by this proc; 
                            0 = print command only
&nbsp;
      @database             Optional, specify specific database name to defrag;
                            If not specified, all non-system databases will
                            be defragged.
&nbsp;
      @tableName            Specify if you only want to defrag indexes for a 
                            specific table, format = databaseName.schema.tableName;
                            if not specified, all tables will be defragged.
&nbsp;
      @onlineRebuild        1 = online rebuild; 
                            0 = offline rebuild
&nbsp;
      @maxDopRestriction    Option to specify a processor limit for index rebuilds
&nbsp;
      @printCommands        1 = print commands to screen; 
                            0 = do not print commands
&nbsp;
      @printFragmentation   1 = print fragmentation to screen;
                            0 = do not print fragmentation
&nbsp;
      @defragDelay          time to wait between defrag commands; gives the
                            server a little time to catch up 
&nbsp;
      @debugMode            1 = display debug comments; helps with troubleshooting
                            0 = do not display debug comments
&nbsp;
    Called by:  SQL Agent Job or DBA
&nbsp;
    Date        Initials	Description
    ----------------------------------------------------------------------------
    2008-10-27  MFU         Initial Release for public consumption
    2008-11-17  MFU         Added page-count to log table
                            , added @printFragmentation option
    2009-03-17  MFU         Provided support for centralized execution, 
                            , consolidated Enterprise &amp; Standard versions
                            , added @debugMode, @maxDopRestriction
                            , modified LOB and partition logic                            
*********************************************************************************
    Exec dbo.dba_indexDefrag_sp
          @executeSQL           = 0
        , @minFragmentation     = 80
        , @printCommands        = 1
        , @debugMode            = 1
        , @printFragmentation   = 1
        , @database             = 'AdventureWorks'
        , @tableName            = 'AdventureWorks.Sales.SalesOrderDetail';
*********************************************************************************/</span>																
&nbsp;
<span style="color: #0000FF;">SET</span> <span style="color: #0000FF;">NOCOUNT</span> <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">SET</span> XACT_Abort <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">SET</span> Quoted_Identifier <span style="color: #0000FF;">ON</span>;
&nbsp;
<span style="color: #0000FF;">BEGIN</span>
&nbsp;
    <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Dusting off the spiderwebs and starting up...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
    <span style="color: #008080;">/* Declare our variables */</span>
    <span style="color: #0000FF;">DECLARE</span>   @objectID             <span style="color: #0000FF;">INT</span>
            , @databaseID           <span style="color: #0000FF;">INT</span>
            , @databaseName         <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>
            , @indexID              <span style="color: #0000FF;">INT</span>
            , @partitionCount       <span style="color: #0000FF;">BIGINT</span>
            , @schemaName           <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>
            , @objectName           <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>
            , @indexName            <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>
            , @partitionNumber      <span style="color: #0000FF;">SMALLINT</span>
            , @partitions           <span style="color: #0000FF;">SMALLINT</span>
            , @fragmentation        <span style="color: #0000FF;">FLOAT</span>
            , @pageCount            <span style="color: #0000FF;">INT</span>
            , @sqlCommand           <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>
            , @rebuildCommand       <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">200</span><span style="color: #808080;">&#41;</span>
            , @dateTimeStart        <span style="color: #0000FF;">DATETIME</span>
            , @dateTimeEnd          <span style="color: #0000FF;">DATETIME</span>
            , @containsLOB          <span style="color: #0000FF;">BIT</span>
            , @editionCheck         <span style="color: #0000FF;">BIT</span>
            , @debugMessage         <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>
            , @updateSQL            <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>
            , @partitionSQL         <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>
            , @partitionSQL_Param   <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">1000</span><span style="color: #808080;">&#41;</span>
            , @LOB_SQL              <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>
            , @LOB_SQL_Param        <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">1000</span><span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #008080;">/* Create our temporary tables */</span>
    <span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> #indexDefragList
    <span style="color: #808080;">&#40;</span>
          databaseID        <span style="color: #0000FF;">INT</span>
        , databaseName      <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>
        , objectID          <span style="color: #0000FF;">INT</span>
        , indexID           <span style="color: #0000FF;">INT</span>
        , partitionNumber   <span style="color: #0000FF;">SMALLINT</span>
        , fragmentation     <span style="color: #0000FF;">FLOAT</span>
        , page_count        <span style="color: #0000FF;">INT</span>
        , defragStatus      <span style="color: #0000FF;">BIT</span>
        , schemaName        <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>   Null
        , objectName        <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>   Null
        , indexName         <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>   Null
    <span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> #databaseList
    <span style="color: #808080;">&#40;</span>
          databaseID        <span style="color: #0000FF;">INT</span>
        , databaseName      <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>
    <span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> #processor 
    <span style="color: #808080;">&#40;</span>
          <span style="color: #808080;">&#91;</span><span style="color: #0000FF;">INDEX</span><span style="color: #808080;">&#93;</span>           <span style="color: #0000FF;">INT</span>
        , Name              <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>
        , Internal_Value    <span style="color: #0000FF;">INT</span>
        , Character_Value   <span style="color: #0000FF;">INT</span>
    <span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Beginning validation...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
    <span style="color: #008080;">/* Just a little validation... */</span>
    <span style="color: #0000FF;">IF</span> @minFragmentation Not Between <span style="color: #000;">0.00</span> And <span style="color: #000;">100.0</span>
        <span style="color: #0000FF;">SET</span> @minFragmentation <span style="color: #808080;">=</span> <span style="color: #000;">5.0</span>;
&nbsp;
    <span style="color: #0000FF;">IF</span> @rebuildThreshold Not Between <span style="color: #000;">0.00</span> And <span style="color: #000;">100.0</span>
        <span style="color: #0000FF;">SET</span> @rebuildThreshold <span style="color: #808080;">=</span> <span style="color: #000;">30.0</span>;
&nbsp;
    <span style="color: #0000FF;">IF</span> @defragDelay Not Like <span style="color: #FF0000;">'00:[0-5][0-9]:[0-5][0-9]'</span>
        <span style="color: #0000FF;">SET</span> @defragDelay <span style="color: #808080;">=</span> <span style="color: #FF0000;">'00:00:05'</span>;
&nbsp;
    <span style="color: #008080;">/* Make sure we're not exceeding the number of processors we have available */</span>
    <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> #processor
    <span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">XP_MSVER</span> <span style="color: #FF0000;">'ProcessorCount'</span>;
&nbsp;
    <span style="color: #0000FF;">IF</span> @maxDopRestriction <span style="color: #0000FF;">IS</span> Not Null And @maxDopRestriction <span style="color: #808080;">&gt;</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> Internal_Value <span style="color: #0000FF;">FROM</span> #processor<span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">SELECT</span> @maxDopRestriction <span style="color: #808080;">=</span> Internal_Value
        <span style="color: #0000FF;">FROM</span> #processor;
&nbsp;
    <span style="color: #008080;">/* Check our server version; 1804890536 = Enterprise, 610778273 = Enterprise Evaluation, -2117995310 = Developer */</span>
    <span style="color: #0000FF;">IF</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #FF00FF;">SERVERPROPERTY</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'EditionID'</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> In <span style="color: #808080;">&#40;</span><span style="color: #000;">1804890536</span>, <span style="color: #000;">610778273</span>, <span style="color: #808080;">-</span><span style="color: #000;">2117995310</span><span style="color: #808080;">&#41;</span> 
        <span style="color: #0000FF;">SET</span> @editionCheck <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #008080;">-- supports online rebuilds</span>
    <span style="color: #0000FF;">ELSE</span>
        <span style="color: #0000FF;">SET</span> @editionCheck <span style="color: #808080;">=</span> <span style="color: #000;">0</span>; <span style="color: #008080;">-- does not support online rebuilds</span>
&nbsp;
    <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Grabbing a list of our databases...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
    <span style="color: #008080;">/* Retrieve the list of databases to investigate */</span>
    <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> #databaseList
    <span style="color: #0000FF;">SELECT</span> database_id
        , name
    <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">databases</span>
    <span style="color: #0000FF;">WHERE</span> name <span style="color: #808080;">=</span> IsNull<span style="color: #808080;">&#40;</span>@<span style="color: #0000FF;">DATABASE</span>, name<span style="color: #808080;">&#41;</span>
        And database_id <span style="color: #808080;">&gt;</span> <span style="color: #000;">4</span> <span style="color: #008080;">-- exclude system databases</span>
        And <span style="color: #808080;">&#91;</span><span style="color: #0000FF;">STATE</span><span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> <span style="color: #000;">0</span>; <span style="color: #008080;">-- state must be ONLINE</span>
&nbsp;
    <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Looping through our list of databases and checking for fragmentation...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
    <span style="color: #008080;">/* Loop through our list of databases */</span>
    <span style="color: #0000FF;">WHILE</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #FF00FF;">COUNT</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">*</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">FROM</span> #databaseList<span style="color: #808080;">&#41;</span> <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span>
    <span style="color: #0000FF;">BEGIN</span>
&nbsp;
        <span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">TOP</span> <span style="color: #000;">1</span> @databaseID <span style="color: #808080;">=</span> databaseID
        <span style="color: #0000FF;">FROM</span> #databaseList;
&nbsp;
        <span style="color: #0000FF;">SELECT</span> @debugMessage <span style="color: #808080;">=</span> <span style="color: #FF0000;">'  working on '</span> <span style="color: #808080;">+</span> <span style="color: #FF00FF;">DB_NAME</span><span style="color: #808080;">&#40;</span>@databaseID<span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">'...'</span>;
&nbsp;
        <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
            <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span>@debugMessage, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
       <span style="color: #008080;">/* Determine which indexes to defrag using our user-defined parameters */</span>
        <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> #indexDefragList
        <span style="color: #0000FF;">SELECT</span>
              database_id <span style="color: #0000FF;">AS</span> databaseID
            , <span style="color: #FF00FF;">QUOTENAME</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">DB_NAME</span><span style="color: #808080;">&#40;</span>database_id<span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'databaseName'</span>
            , <span style="color: #808080;">&#91;</span><span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#93;</span> <span style="color: #0000FF;">AS</span> objectID
            , index_id <span style="color: #0000FF;">AS</span> indexID
            , partition_number <span style="color: #0000FF;">AS</span> partitionNumber
            , avg_fragmentation_in_percent <span style="color: #0000FF;">AS</span> fragmentation
            , page_count 
            , <span style="color: #000;">0</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'defragStatus'</span> <span style="color: #008080;">/* 0 = unprocessed, 1 = processed */</span>
            , Null <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'schemaName'</span>
            , Null <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'objectName'</span>
            , Null <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'indexName'</span>
        <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">dm_db_index_physical_stats</span> <span style="color: #808080;">&#40;</span>@databaseID, <span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#40;</span>@tableName<span style="color: #808080;">&#41;</span>, Null , Null, N<span style="color: #FF0000;">'Limited'</span><span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">WHERE</span> avg_fragmentation_in_percent <span style="color: #808080;">&gt;=</span> @minFragmentation 
            And index_id <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span> <span style="color: #008080;">-- ignore heaps</span>
            And page_count <span style="color: #808080;">&gt;</span> <span style="color: #000;">8</span> <span style="color: #008080;">-- ignore objects with less than 1 extent</span>
        <span style="color: #0000FF;">OPTION</span> <span style="color: #808080;">&#40;</span>MaxDop <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>;
&nbsp;
        <span style="color: #0000FF;">DELETE</span> <span style="color: #0000FF;">FROM</span> #databaseList
        <span style="color: #0000FF;">WHERE</span> databaseID <span style="color: #808080;">=</span> @databaseID;
&nbsp;
    <span style="color: #0000FF;">END</span>
&nbsp;
    <span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">CLUSTERED</span> <span style="color: #0000FF;">INDEX</span> CIX_temp_indexDefragList
        <span style="color: #0000FF;">ON</span> #indexDefragList<span style="color: #808080;">&#40;</span>databaseID, objectID, indexID, partitionNumber<span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #0000FF;">SELECT</span> @debugMessage <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Looping through our list... there'</span><span style="color: #FF0000;">'s '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">COUNT</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">*</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">' indexes to defrag!'</span>
    <span style="color: #0000FF;">FROM</span> #indexDefragList;
&nbsp;
    <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span>@debugMessage, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
    <span style="color: #008080;">/* Begin our loop for defragging */</span>
    <span style="color: #0000FF;">WHILE</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #FF00FF;">COUNT</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">*</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">FROM</span> #indexDefragList <span style="color: #0000FF;">WHERE</span> defragStatus <span style="color: #808080;">=</span> <span style="color: #000;">0</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span>
    <span style="color: #0000FF;">BEGIN</span>
&nbsp;
        <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  Picking an index to beat into shape...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
        <span style="color: #008080;">/* Grab the most fragmented index first to defrag */</span>
        <span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">TOP</span> <span style="color: #000;">1</span> 
              @objectID         <span style="color: #808080;">=</span> objectID
            , @indexID          <span style="color: #808080;">=</span> indexID
            , @databaseID       <span style="color: #808080;">=</span> databaseID
            , @databaseName     <span style="color: #808080;">=</span> databaseName
            , @fragmentation    <span style="color: #808080;">=</span> fragmentation
            , @partitionNumber  <span style="color: #808080;">=</span> partitionNumber
            , @pageCount        <span style="color: #808080;">=</span> page_count
        <span style="color: #0000FF;">FROM</span> #indexDefragList
        <span style="color: #0000FF;">WHERE</span> defragStatus <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
        <span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> fragmentation <span style="color: #0000FF;">DESC</span>;
&nbsp;
        <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  Looking up the specifics for our index...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
        <span style="color: #008080;">/* Look up index information */</span>
        <span style="color: #0000FF;">SELECT</span> @updateSQL <span style="color: #808080;">=</span> N<span style="color: #FF0000;">'Update idl
            Set schemaName = QuoteName(s.name)
                , objectName = QuoteName(o.name)
                , indexName = QuoteName(i.name)
            From #indexDefragList As idl
            Inner Join '</span> <span style="color: #808080;">+</span> @databaseName <span style="color: #808080;">+</span> <span style="color: #FF0000;">'.sys.objects As o
                On idl.objectID = o.object_id
            Inner Join '</span> <span style="color: #808080;">+</span> @databaseName <span style="color: #808080;">+</span> <span style="color: #FF0000;">'.sys.indexes As i
                On o.object_id = i.object_id
            Inner Join '</span> <span style="color: #808080;">+</span> @databaseName <span style="color: #808080;">+</span> <span style="color: #FF0000;">'.sys.schemas As s
                On o.schema_id = s.schema_id
            Where o.object_id = '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@objectID <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">'
                And i.index_id = '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@indexID <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">'
                And i.type &gt; 0
                And idl.databaseID = '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@databaseID <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>;
&nbsp;
        <span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">SP_EXECUTESQL</span> @updateSQL;
&nbsp;
        <span style="color: #008080;">/* Grab our object names */</span>
        <span style="color: #0000FF;">SELECT</span> @objectName  <span style="color: #808080;">=</span> objectName
            , @schemaName   <span style="color: #808080;">=</span> schemaName
            , @indexName    <span style="color: #808080;">=</span> indexName
        <span style="color: #0000FF;">FROM</span> #indexDefragList
        <span style="color: #0000FF;">WHERE</span> objectID <span style="color: #808080;">=</span> @objectID
            And indexID <span style="color: #808080;">=</span> @indexID
            And databaseID <span style="color: #808080;">=</span> @databaseID;
&nbsp;
        <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  Grabbing the partition count...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
        <span style="color: #008080;">/* Determine if the index is partitioned */</span>
        <span style="color: #0000FF;">SELECT</span> @partitionSQL <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Select @partitionCount_OUT = Count(*)
                                    From '</span> <span style="color: #808080;">+</span> @databaseName <span style="color: #808080;">+</span> <span style="color: #FF0000;">'.sys.partitions
                                    Where object_id = '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@objectID <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">'
                                        And index_id = '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@indexID <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">';'</span>
            , @partitionSQL_Param <span style="color: #808080;">=</span> <span style="color: #FF0000;">'@partitionCount_OUT int OutPut'</span>;
&nbsp;
        <span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">SP_EXECUTESQL</span> @partitionSQL, @partitionSQL_Param, @partitionCount_OUT <span style="color: #808080;">=</span> @partitionCount <span style="color: #0000FF;">OUTPUT</span>;
&nbsp;
        <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  Seeing if there'</span><span style="color: #FF0000;">'s any LOBs to be handled...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
        <span style="color: #008080;">/* Determine if the table contains LOBs */</span>
        <span style="color: #0000FF;">SELECT</span> @LOB_SQL <span style="color: #808080;">=</span> <span style="color: #FF0000;">' Select Top 1 @containsLOB_OUT = column_id
                            From '</span> <span style="color: #808080;">+</span> @databaseName <span style="color: #808080;">+</span> <span style="color: #FF0000;">'.sys.columns With (NoLock) 
                            Where [object_id] = '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@objectID <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">'
                                And (system_type_id In (34, 35, 99)
                                        Or max_length = -1);'</span>
                            <span style="color: #008080;">/*  system_type_id --&gt; 34 = image, 35 = text, 99 = ntext
                                max_length = -1 --&gt; varbinary(max), varchar(max), nvarchar(max), xml */</span>
                , @LOB_SQL_Param <span style="color: #808080;">=</span> <span style="color: #FF0000;">'@containsLOB_OUT int OutPut'</span>;
&nbsp;
        <span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">SP_EXECUTESQL</span> @LOB_SQL, @LOB_SQL_Param, @containsLOB_OUT <span style="color: #808080;">=</span> @containsLOB <span style="color: #0000FF;">OUTPUT</span>;
&nbsp;
        <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  Building our SQL statements...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
        <span style="color: #008080;">/* If there's not a lot of fragmentation, or if we have a LOB, we should reorganize */</span>
        <span style="color: #0000FF;">IF</span> @fragmentation <span style="color: #808080;">&lt;</span> @rebuildThreshold Or @containsLOB <span style="color: #808080;">=</span> <span style="color: #000;">1</span> Or @partitionCount <span style="color: #808080;">&gt;</span> <span style="color: #000;">1</span>
        <span style="color: #0000FF;">BEGIN</span>
&nbsp;
            <span style="color: #0000FF;">SET</span> @sqlCommand <span style="color: #808080;">=</span> N<span style="color: #FF0000;">'Alter Index '</span> <span style="color: #808080;">+</span> @indexName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">' On '</span> <span style="color: #808080;">+</span> @databaseName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">'.'</span> 
                                <span style="color: #808080;">+</span> @schemaName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">'.'</span> <span style="color: #808080;">+</span> @objectName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">' ReOrganize'</span>;
&nbsp;
            <span style="color: #008080;">/* If our index is partitioned, we should always reorganize */</span>
            <span style="color: #0000FF;">IF</span> @partitionCount <span style="color: #808080;">&gt;</span> <span style="color: #000;">1</span>
                <span style="color: #0000FF;">SET</span> @sqlCommand <span style="color: #808080;">=</span> @sqlCommand <span style="color: #808080;">+</span> N<span style="color: #FF0000;">' Partition = '</span> 
                                <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@partitionNumber <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>;
&nbsp;
        <span style="color: #0000FF;">END</span>;
&nbsp;
        <span style="color: #008080;">/* If the index is heavily fragmented and doesn't contain any partitions or LOB's, rebuild it */</span>
        <span style="color: #0000FF;">IF</span> @fragmentation <span style="color: #808080;">&gt;=</span> @rebuildThreshold And IsNull<span style="color: #808080;">&#40;</span>@containsLOB, <span style="color: #000;">0</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">!=</span> <span style="color: #000;">1</span> And @partitionCount <span style="color: #808080;">&lt;=</span> <span style="color: #000;">1</span>
        <span style="color: #0000FF;">BEGIN</span>
&nbsp;
            <span style="color: #008080;">/* Set online rebuild options; requires Enterprise Edition */</span>
            <span style="color: #0000FF;">IF</span> @onlineRebuild <span style="color: #808080;">=</span> <span style="color: #000;">1</span> And @editionCheck <span style="color: #808080;">=</span> <span style="color: #000;">1</span> 
                <span style="color: #0000FF;">SET</span> @rebuildCommand <span style="color: #808080;">=</span> N<span style="color: #FF0000;">' Rebuild With (Online = On'</span>;
            <span style="color: #0000FF;">ELSE</span>
                <span style="color: #0000FF;">SET</span> @rebuildCommand <span style="color: #808080;">=</span> N<span style="color: #FF0000;">' Rebuild With (Online = Off'</span>;
&nbsp;
            <span style="color: #008080;">/* Set processor restriction options; requires Enterprise Edition */</span>
            <span style="color: #0000FF;">IF</span> @maxDopRestriction <span style="color: #0000FF;">IS</span> Not Null And @editionCheck <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
                <span style="color: #0000FF;">SET</span> @rebuildCommand <span style="color: #808080;">=</span> @rebuildCommand <span style="color: #808080;">+</span> N<span style="color: #FF0000;">', MaxDop = '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@maxDopRestriction <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">2</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> N<span style="color: #FF0000;">')'</span>;
            <span style="color: #0000FF;">ELSE</span>
                <span style="color: #0000FF;">SET</span> @rebuildCommand <span style="color: #808080;">=</span> @rebuildCommand <span style="color: #808080;">+</span> N<span style="color: #FF0000;">')'</span>;
&nbsp;
            <span style="color: #0000FF;">SET</span> @sqlCommand <span style="color: #808080;">=</span> N<span style="color: #FF0000;">'Alter Index '</span> <span style="color: #808080;">+</span> @indexName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">' On '</span> <span style="color: #808080;">+</span> @databaseName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">'.'</span>
                            <span style="color: #808080;">+</span> @schemaName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">'.'</span> <span style="color: #808080;">+</span> @objectName <span style="color: #808080;">+</span> @rebuildCommand;
&nbsp;
        <span style="color: #0000FF;">END</span>;
&nbsp;
        <span style="color: #008080;">/* Are we executing the SQL?  If so, do it */</span>
        <span style="color: #0000FF;">IF</span> @executeSQL <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
        <span style="color: #0000FF;">BEGIN</span>
&nbsp;
            <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  Executing SQL statements...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
            <span style="color: #008080;">/* Grab the time for logging purposes */</span>
            <span style="color: #0000FF;">SET</span> @dateTimeStart  <span style="color: #808080;">=</span> <span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>;
            <span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">SP_EXECUTESQL</span> @sqlCommand;
            <span style="color: #0000FF;">SET</span> @dateTimeEnd  <span style="color: #808080;">=</span> <span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>;
&nbsp;
            <span style="color: #008080;">/* Log our actions */</span>
            <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> dbo.<span style="color: #202020;">dba_indexDefragLog</span>
            <span style="color: #808080;">&#40;</span>
                  databaseID
                , databaseName
                , objectID
                , objectName
                , indexID
                , indexName
                , partitionNumber
                , fragmentation
                , page_count
                , dateTimeStart
                , durationSeconds
            <span style="color: #808080;">&#41;</span>
            <span style="color: #0000FF;">SELECT</span>
                  @databaseID
                , @databaseName
                , @objectID
                , @objectName
                , @indexID
                , @indexName
                , @partitionNumber
                , @fragmentation
                , @pageCount
                , @dateTimeStart
                , <span style="color: #FF00FF;">DATEDIFF</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SECOND</span>, @dateTimeStart, @dateTimeEnd<span style="color: #808080;">&#41;</span>;
&nbsp;
            <span style="color: #008080;">/* Just a little breather for the server */</span>
            <span style="color: #0000FF;">WAITFOR</span> Delay @defragDelay;
&nbsp;
            <span style="color: #008080;">/* Print if specified to do so */</span>
            <span style="color: #0000FF;">IF</span> @printCommands <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
                <span style="color: #0000FF;">PRINT</span> N<span style="color: #FF0000;">'Executed: '</span> <span style="color: #808080;">+</span> @sqlCommand;
        <span style="color: #0000FF;">END</span>
        <span style="color: #0000FF;">ELSE</span>
        <span style="color: #008080;">/* Looks like we're not executing, just printing the commands */</span>
        <span style="color: #0000FF;">BEGIN</span>
            <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  Printing SQL statements...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
            <span style="color: #0000FF;">IF</span> @printCommands <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">PRINT</span> IsNull<span style="color: #808080;">&#40;</span>@sqlCommand, <span style="color: #FF0000;">'error!'</span><span style="color: #808080;">&#41;</span>;
        <span style="color: #0000FF;">END</span>
&nbsp;
        <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  Updating our index defrag status...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
        <span style="color: #008080;">/* Update our index defrag list so we know we've finished with that index */</span>
        <span style="color: #0000FF;">UPDATE</span> #indexDefragList
        <span style="color: #0000FF;">SET</span> defragStatus <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
        <span style="color: #0000FF;">WHERE</span> databaseID       <span style="color: #808080;">=</span> @databaseID
          And objectID         <span style="color: #808080;">=</span> @objectID
          And indexID          <span style="color: #808080;">=</span> @indexID
          And partitionNumber  <span style="color: #808080;">=</span> @partitionNumber;
&nbsp;
    <span style="color: #0000FF;">END</span>
&nbsp;
    <span style="color: #008080;">/* Do we want to output our fragmentation results? */</span>
    <span style="color: #0000FF;">IF</span> @printFragmentation <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
    <span style="color: #0000FF;">BEGIN</span>
&nbsp;
        <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'  Displaying fragmentation results...'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
        <span style="color: #0000FF;">SELECT</span> databaseID
            , databaseName
            , objectID
            , objectName
            , indexID
            , indexName
            , fragmentation
            , page_count
        <span style="color: #0000FF;">FROM</span> #indexDefragList;
&nbsp;
    <span style="color: #0000FF;">END</span>;
&nbsp;
    <span style="color: #008080;">/* When everything is said and done, make sure to get rid of our temp table */</span>
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">TABLE</span> #indexDefragList;
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">TABLE</span> #databaseList;
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">TABLE</span> #processor;
&nbsp;
    <span style="color: #0000FF;">IF</span> @debugMode <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'DONE!  Thank you for taking care of your indexes!  :)'</span>, <span style="color: #000;">0</span>, <span style="color: #000;">42</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">WITH</span> NoWait;
&nbsp;
    <span style="color: #0000FF;">SET</span> <span style="color: #0000FF;">NOCOUNT</span> <span style="color: #0000FF;">OFF</span>;
	<span style="color: #0000FF;">RETURN</span> <span style="color: #000;">0</span>
<span style="color: #0000FF;">END</span>
Go</pre></div></div>

<p>Thanks to my beta testers, @scoinva, @davidmtate, @jdanton, and @SuperCoolMoss!<br />
Special thanks to SCM for keeping on me to finish this.  </p>
<p>Happy Defragging!</p>
<p>Michelle</p>
<p>Source: <a href="http://sqlfool.com/2009/03/automated-index-defrag-script/">http://sqlfool.com/2009/03/automated-index-defrag-script/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/03/automated-index-defrag-script/feed/</wfw:commentRss>
		<slash:comments>41</slash:comments>
		</item>
		<item>
		<title>Creating a 60 GB Index</title>
		<link>http://sqlfool.com/2009/01/creating-a-60-gb-index/</link>
		<comments>http://sqlfool.com/2009/01/creating-a-60-gb-index/#comments</comments>
		<pubDate>Sat, 24 Jan 2009 19:43:09 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[SQL Tips]]></category>
		<category><![CDATA[indexes]]></category>
		<category><![CDATA[partitioning]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[tempdb]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=301</guid>
		<description><![CDATA[Recently, I needed to create an index on a 1.5 billion row table. I've created some large indexes before, but this was the largest, so I thought I'd share my experience in case anyone was interested. The plan was to create the following index: CREATE NONCLUSTERED INDEX IX_indexName_unpartitioned ON databaseName.dbo.tableName&#40;columnList&#41; Include &#40;includedColumnList&#41; WITH &#40;MaxDop = [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, I needed to create an index on a 1.5 billion row table.  I've created some large indexes before, but this was the largest, so I thought I'd share my experience in case anyone was interested.</p>
<p>The plan was to create the following index:</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_indexName_unpartitioned
    <span style="color: #0000FF;">ON</span> databaseName.<span style="color: #202020;">dbo</span>.<span style="color: #202020;">tableName</span><span style="color: #808080;">&#40;</span>columnList<span style="color: #808080;">&#41;</span>
    Include <span style="color: #808080;">&#40;</span>includedColumnList<span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">WITH</span> <span style="color: #808080;">&#40;</span>MaxDop <span style="color: #808080;">=</span> <span style="color: #000;">1</span>, Online <span style="color: #808080;">=</span> <span style="color: #0000FF;">ON</span>, Sort_In_TempDB <span style="color: #808080;">=</span> <span style="color: #0000FF;">ON</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>;</pre></div></div>

<p>This is an unpartitioned, non-clustered index being built on a partitioned table.  Normally, when you build an aligned partitioned index, the index creation process requires less memory and has less noticeable impact on the system, because each partition is handled individually, one at a time.  But as this is an unpartitioned (unaligned) index, each partition was built concurrently, requiring more memory and causing a greater impact on performance.  Because of this, I needed to restrict the process to MaxDop 1; otherwise, the server would suffer because of too much memory pressure.</p>
<p>I chose Sort_In_TempDB = On because:</p>
<ul>
<li>I'm building this index online on a very busy table and cannot afford to impact normal oeprations.  By using Sort_In_TempDB = On, index transactions are separated from user transactions, allowing the user transaction log to be truncated. *</li>
<li>TempDB is on a different volume and therefore should reduce the duration of the operation.</li>
<li>The recovery for the user database is full, and the recovery for the TempDB is simple.  Sorting in TempDB would minimize logging.</li>
</ul>
<p><em>* Note: the transaction log for the user database still grew at a much faster rate than normal and had to be closely monitored during this operation to ensure enough free space remained.</em></p>
<p>The size of the indexed columns is 25 bytes.  So I ran my calculations and came up with 36gb space requirement.  We increased TempDB to 50gb and gave it a go.  An hour later... ERROR.  The process terminated because there would not be enough space free in TempDB to complete the operation.  Obviously, my calculations were incorrect.  After speaking with <a href="http://twitter.com/databaseguy" target="_blank">Chris Leonard</a>, a man who is way too smart for his own good, I realized I had not included my clustered index in the size calculations.  Doh.</p>
<p>Re-running my estimates, here's what I came up with:</p>
<table style="border-collapse: collapse; height: 103px;" border="0" cellspacing="0" cellpadding="0" width="309">
<col style="width: 102pt;" width="136"></col>
<col style="width: 82pt;" width="109"></col>
<col style="width: 48pt;" width="64"></col>
<tbody>
<tr style="height: 12.75pt;" height="17">
<td style="height: 12.75pt; width: 102pt;" width="136" height="17">Index Size</td>
<td style="width: 82pt;" width="109" align="right">25</td>
<td style="width: 48pt;" width="64">&nbsp;&nbsp;bytes</td>
</tr>
<tr style="height: 12.75pt;" height="17">
<td style="height: 12.75pt;" height="17">Clustered Index Size</td>
<td align="right">16</td>
<td>&nbsp;&nbsp;bytes</td>
</tr>
<tr style="height: 12.75pt;" height="17">
<td style="height: 12.75pt;" height="17">Records per Page</td>
<td align="right">197</td>
<td></td>
</tr>
<tr style="height: 12.75pt;" height="17">
<td style="height: 12.75pt;" height="17">Est. Rows</td>
<td class="xl65" align="right">1,575,000,000</td>
<td></td>
</tr>
<tr style="height: 12.75pt;" height="17">
<td style="height: 12.75pt;" height="17">Est. Number of Pages</td>
<td class="xl66" align="right">7,995,000</td>
<td></td>
</tr>
<tr style="height: 12.75pt;" height="17">
<td style="height: 12.75pt;" height="17">Space Requirements</td>
<td class="xl66" align="right">59</td>
<td>&nbsp;&nbsp;GB</td>
</tr>
</tbody>
</table>
<p>&nbsp;</p>
<p>Obviously, 50gb of free space just wasn't going to cut it.  I decided to give TempDB a little wiggle room and bumped up the space in TempDB to 70gb (not as easy as you'd imagine, I had to requisition more space on the SAN), then re-ran the operation.  Success!  The process completed in 3 hours and 24 minutes.  There was a mild increase in CPU, but no applications or users experienced any issues.</p>
<p>For those interested in the particulars: this was used for a single-record look-up and could not be filtered by the partitioning key.  The non-partitioned version of this index has 80% less reads and 11% less CPU than its partitioned counterpart.   </p>
<p>If you're interested in learning more about indexes, here's some recommended reading:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ms188281.aspx" target="_blank">TempDB and Index Creation</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms184246.aspx" target="_blank">Transaction Log Disk Space for Index Operations</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms187526.aspx" target="_blank">Special Guidelines for Partitioned Indexes</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/01/creating-a-60-gb-index/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Indexing for Partitioned Tables</title>
		<link>http://sqlfool.com/2008/12/indexing-for-partitioned-tables/</link>
		<comments>http://sqlfool.com/2008/12/indexing-for-partitioned-tables/#comments</comments>
		<pubDate>Tue, 23 Dec 2008 15:15:36 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[SQL Tips]]></category>
		<category><![CDATA[indexes]]></category>
		<category><![CDATA[partitioning]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=281</guid>
		<description><![CDATA[So you've partitioned your table, and now you're ready to performance tune. As with any table, indexing is a great place to start. And if you're like most people new to partitioning, you probably created all of your indexes on the partitioned scheme, either by design or unintentionally. Let's take a step back here and [...]]]></description>
			<content:encoded><![CDATA[<p>So you've partitioned your table, and now you're ready to performance tune.  As with any table, indexing is a great place to start.  And if you're like most people new to partitioning, you probably created all of your indexes on the partitioned scheme, either by design or unintentionally.  </p>
<p>Let's take a step back here and discuss what a partitioned index is.  A partitioned index, like a partitioned table, separates data into different physical structures (partitions) under one logical name.  Specifically, each partition in a nonclustered index contains its own B-tree structure with a subset of rows, based upon the partitioning scheme.  By default, an unpartitioned nonclustered index has just one partition.  </p>
<p>Keep in mind, when you create an index on a partitioned table, i.e.</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_myIndex
    <span style="color: #0000FF;">ON</span> dbo.<span style="color: #202020;">myTable</span><span style="color: #808080;">&#40;</span>myColumn<span style="color: #808080;">&#41;</span>;</pre></div></div>

<p>... you are creating the index on the partitioned scheme by default.  In order to create a NON-partitioned index on that same table, you would need to explicitly declare "On [FileGroup]", i.e.</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_myIndex
    <span style="color: #0000FF;">ON</span> dbo.<span style="color: #202020;">myTable</span><span style="color: #808080;">&#40;</span>myColumn<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>;</pre></div></div>

<p>&nbsp;</p>
<p>But should you partition your index?  That depends on how you use it.  In fact, most environments will probably want to use a mix of partitioned and non-partitioned indexes.  I've found that that partitioned indexes perform better when aggregating data or scanning partitions. Conversely, you'll probably find that, if you need to locate a single, specific record, nothing performs better than a non-partitioned index on that column.</p>
<p>Let's walk through some examples and see how they perform.  I'll bring back my trusty ol' orders table for this.</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/* Create a partition function. */</span>
<span style="color: #0000FF;">CREATE</span> Partition <span style="color: #0000FF;">FUNCTION</span> 
    <span style="color: #808080;">&#91;</span>test_monthlyDateRange_pf<span style="color: #808080;">&#93;</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">DATETIME</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;">'2009-01-01'</span>, <span style="color: #FF0000;">'2009-01-08'</span>, <span style="color: #FF0000;">'2009-01-15'</span>
    , <span style="color: #FF0000;">'2009-01-22'</span>, <span style="color: #FF0000;">'2009-01-29'</span><span style="color: #808080;">&#41;</span>;
Go
&nbsp;
<span style="color: #008080;">/* Associate the partition function with a partition scheme. */</span>
<span style="color: #0000FF;">CREATE</span> Partition Scheme test_monthlyDateRange_ps
    <span style="color: #0000FF;">AS</span> Partition test_monthlyDateRange_pf
    All <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>;
Go
&nbsp;
<span style="color: #008080;">/* Create a partitioned table. */</span>
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">orders</span>
<span style="color: #808080;">&#40;</span>
      order_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
    , orderDate <span style="color: #0000FF;">DATETIME</span>            Not Null
    , orderData <span style="color: #0000FF;">SMALLDATETIME</span>       Not Null
&nbsp;
    <span style="color: #0000FF;">CONSTRAINT</span> PK_orders <span style="color: #0000FF;">PRIMARY</span> <span style="color: #0000FF;">KEY</span> <span style="color: #0000FF;">CLUSTERED</span>
    <span style="color: #808080;">&#40;</span>
        order_id
      , orderDate
    <span style="color: #808080;">&#41;</span>
<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">ON</span> test_monthlyDateRange_ps<span style="color: #808080;">&#40;</span>orderDate<span style="color: #808080;">&#41;</span>;
Go
&nbsp;
<span style="color: #008080;">/* Create some records to play with. */</span>
<span style="color: #0000FF;">SET</span> <span style="color: #0000FF;">NOCOUNT</span> <span style="color: #0000FF;">ON</span>;
&nbsp;
<span style="color: #0000FF;">DECLARE</span> @endDate <span style="color: #0000FF;">DATETIME</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'2009-01-01'</span>;
&nbsp;
<span style="color: #0000FF;">WHILE</span> @endDate <span style="color: #808080;">&lt;</span> <span style="color: #FF0000;">'2009-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;">orders</span>
    <span style="color: #0000FF;">SELECT</span> @endDate, @endDate;
&nbsp;
    <span style="color: #0000FF;">SET</span> @endDate <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>, @endDate<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">END</span>;
&nbsp;
<span style="color: #0000FF;">SET</span> <span style="color: #0000FF;">NOCOUNT</span> <span style="color: #0000FF;">OFF</span>;
&nbsp;
&nbsp;
<span style="color: #008080;">/* Let’s create an aligned, partitioned index. */</span>
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">NONCLUSTERED</span> <span style="color: #0000FF;">INDEX</span> IX_orders_aligned
    <span style="color: #0000FF;">ON</span> dbo.<span style="color: #202020;">orders</span><span style="color: #808080;">&#40;</span>order_id<span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">ON</span> test_monthlyDateRange_ps<span style="color: #808080;">&#40;</span>orderDate<span style="color: #808080;">&#41;</span>; 
    <span style="color: #008080;">/* you don't actually need to declare the last
       line of this unless you want to create the
       index on a different partitioning scheme.   */</span>
&nbsp;
<span style="color: #008080;">/* Now let’s create an unpartitioned index. */</span>
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">NONCLUSTERED</span> <span style="color: #0000FF;">INDEX</span> IX_orders_unpartitioned
    <span style="color: #0000FF;">ON</span> dbo.<span style="color: #202020;">orders</span><span style="color: #808080;">&#40;</span>order_id<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>;</pre></div></div>

<p>&nbsp;</p>
<p>Now that we have both a partitioned and an unpartitioned index, let's take a look at our <strong>sys.partitions</strong> table:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/* Let's take a look at our index partitions */</span>
<span style="color: #0000FF;">SELECT</span> i.<span style="color: #202020;">name</span>
    , i.<span style="color: #202020;">index_id</span>
    , p.<span style="color: #202020;">partition_number</span>
    , p.<span style="color: #0000FF;">ROWS</span>
<span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">partitions</span> <span style="color: #0000FF;">AS</span> p
Join sys.<span style="color: #202020;">indexes</span> <span style="color: #0000FF;">AS</span> i
    <span style="color: #0000FF;">ON</span> p.<span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> i.<span style="color: #FF00FF;">OBJECT_ID</span> 
   And p.<span style="color: #202020;">index_id</span> <span style="color: #808080;">=</span> i.<span style="color: #202020;">index_id</span>
<span style="color: #0000FF;">WHERE</span> p.<span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> <span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'orders'</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> i.<span style="color: #202020;">index_id</span>, p.<span style="color: #202020;">partition_number</span>;</pre></div></div>

<p>&nbsp;</p>
<div class="wp-caption alignnone" style="width: 410px"><a href="http://sqlfool.com/blogImages/20081222/query4.jpg" target="_blank"><img alt="sys.partitions" src="http://sqlfool.com/blogImages/20081222/query4_small.jpg" title="sys.partitions" width="400" height="374" /></a><p class="wp-caption-text">sys.partitions</p></div>
<p>As expected, both of our partitioned indexes, PK_orders and IX_orders_aligned, have 6 partitions, with a subset of rows on each partition.  Our unpartitioned non-clustered index, IX_orders_unpartitioned, on the other hand has just 1 partition containing all of the rows.</p>
<p>Now that we have our environment set up, let's run through some different queries and see the performance impact of each type of index.</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/* Query 1, specific record look-up, covered */</span>
<span style="color: #0000FF;">SELECT</span> order_id, orderDate
<span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">orders</span> <span style="color: #0000FF;">WITH</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">INDEX</span><span style="color: #808080;">&#40;</span>IX_orders_aligned<span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">WHERE</span> order_id <span style="color: #808080;">=</span> <span style="color: #000;">25000</span>;
&nbsp;
<span style="color: #0000FF;">SELECT</span> order_id, orderDate
<span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">orders</span> <span style="color: #0000FF;">WITH</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">INDEX</span><span style="color: #808080;">&#40;</span>IX_orders_unpartitioned<span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">WHERE</span> order_id <span style="color: #808080;">=</span> <span style="color: #000;">25000</span>;</pre></div></div>

<p>&nbsp;</p>
<div class="wp-caption alignnone" style="width: 751px"><a href="http://sqlfool.com/blogImages/20081222/query1.jpg" target="_blank"><img alt="Query 1" src="http://sqlfool.com/blogImages/20081222/query1_small.jpg" title="Query 1" /></a><p class="wp-caption-text">Query 1</p></div>
<p>The unpartitioned index performs significantly better when given a specific record to look-up.  Now let's try the same query, but utilizing a scan instead of a seek:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/* Query 2, specific record look-up, uncovered */</span>
<span style="color: #0000FF;">SELECT</span> order_id, orderDate, orderData
<span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">orders</span> <span style="color: #0000FF;">WITH</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">INDEX</span><span style="color: #808080;">&#40;</span>IX_orders_aligned<span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">WHERE</span> order_id <span style="color: #808080;">=</span> <span style="color: #000;">30000</span>;
&nbsp;
<span style="color: #0000FF;">SELECT</span> order_id, orderDate, orderData
<span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">orders</span> <span style="color: #0000FF;">WITH</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">INDEX</span><span style="color: #808080;">&#40;</span>IX_orders_unpartitioned<span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">WHERE</span> order_id <span style="color: #808080;">=</span> <span style="color: #000;">30000</span>;</pre></div></div>

<p>&nbsp;</p>
<div class="wp-caption alignnone" style="width: 410px"><a href="http://sqlfool.com/blogImages/20081222/query2.jpg" target="_blank"><img alt="Query 2" src="http://sqlfool.com/blogImages/20081222/query2_small.jpg" title="Query 2" width="400" height="346" /></a><p class="wp-caption-text">Query 2</p></div>
<p>Again we see that the non-partitioned index performs better with the single-record look-up.  This can lead to some pretty dramatic performance implications.  So when *would* we want to use a partitioned index?  Two instances immediately pop to mind.  First, partition switching can only be performed when all indexes on a table are aligned.  Secondly, partitioned indexes perform better when manipulating large data sets.  To see this in action, let's try some simple aggregation...</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/* Query 3, aggregation */</span>
<span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">ROUND</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>orderdate <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">FLOAT</span><span style="color: #808080;">&#41;</span>, <span style="color: #000;">0</span>, <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">SMALLDATETIME</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'order_date'</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;">orders</span> <span style="color: #0000FF;">WITH</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">INDEX</span><span style="color: #808080;">&#40;</span>IX_orders_aligned<span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">WHERE</span> orderDate Between <span style="color: #FF0000;">'2009-01-01'</span> And <span style="color: #FF0000;">'2009-01-07 23:59'</span>
<span style="color: #0000FF;">GROUP</span> <span style="color: #0000FF;">BY</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">ROUND</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>orderdate <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">FLOAT</span><span style="color: #808080;">&#41;</span>, <span style="color: #000;">0</span>, <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span> <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> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">ROUND</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>orderdate <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">FLOAT</span><span style="color: #808080;">&#41;</span>, <span style="color: #000;">0</span>, <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">SMALLDATETIME</span><span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">ROUND</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>orderdate <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">FLOAT</span><span style="color: #808080;">&#41;</span>, <span style="color: #000;">0</span>, <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">SMALLDATETIME</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'order_date'</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;">orders</span> <span style="color: #0000FF;">WITH</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">INDEX</span><span style="color: #808080;">&#40;</span>IX_orders_unpartitioned<span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">WHERE</span> orderDate Between <span style="color: #FF0000;">'2009-01-01'</span> And <span style="color: #FF0000;">'2009-01-07 23:59'</span>
<span style="color: #0000FF;">GROUP</span> <span style="color: #0000FF;">BY</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">ROUND</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>orderdate <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">FLOAT</span><span style="color: #808080;">&#41;</span>, <span style="color: #000;">0</span>, <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span> <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> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">ROUND</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>orderdate <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">FLOAT</span><span style="color: #808080;">&#41;</span>, <span style="color: #000;">0</span>, <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">SMALLDATETIME</span><span style="color: #808080;">&#41;</span>;</pre></div></div>

<p>&nbsp;</p>
<div class="wp-caption alignnone" style="width: 410px"><a href="http://sqlfool.com/blogImages/20081222/query3.jpg" target="_blank"><img alt="Query 3" src="http://sqlfool.com/blogImages/20081222/query3_small.jpg" title="Query 3" width="400" height="425" /></a><p class="wp-caption-text">Query 3</p></div>
<p>As you can see, partitioned indexes perform better when aggregating data.  This is just a simple example, but the results can be even more dramatic in a large production environment.  This is one of the reasons why partitioned tables and indexes are especially beneficial in data warehouses.</p>
<p>So now you have a general idea of what a partitioned index is and when to use a partitioned index vs a non-partitioned index.  Ultimately, your indexing needs will depend largely on the application and how the data is used.  When in doubt, test, test, test!  So to recap...</p>
<ul>
<li>Specify “On [FileGroup]“ to create an unpartitioned index on a partitioned table</li>
<li>Consider using non-partitioned indexes for single-record look-ups</li>
<li>Use partitioned indexes for multiple records and data aggregations</li>
<li>To enable partition switching, all indexes on the table must be aligned.</li>
</ul>
<p>For more information on partitioning, check out my other partitioning articles:</p>
<p><a href="http://sqlfool.com/2008/11/102/">Partitioning Example</a><br />
<a href="http://sqlfool.com/2008/11/partitioning-101/">Partitioning 101</a><br />
<a href="http://sqlfool.com/2008/10/tips-for-large-data-stores/">Tips for Large Data Stores</a></p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2008/12/indexing-for-partitioned-tables/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Updated Index Defrag Script (2005, 2008)</title>
		<link>http://sqlfool.com/2008/11/updated-index-defrag-script-2005-2008/</link>
		<comments>http://sqlfool.com/2008/11/updated-index-defrag-script-2005-2008/#comments</comments>
		<pubDate>Mon, 17 Nov 2008 17:48:33 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[T-SQL Scripts]]></category>
		<category><![CDATA[2008]]></category>
		<category><![CDATA[defrag]]></category>
		<category><![CDATA[indexes]]></category>
		<category><![CDATA[partitioning]]></category>
		<category><![CDATA[TSQL]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=183</guid>
		<description><![CDATA[Thanks to everyone who left a comment or sent me an e-mail regarding the Index Defrag Script. I've received some great feedback and requests for features. I've also had some questions regarding how to use it, which I will answer at the end of this post. Changes include: - separate version for both Enterprise and [...]]]></description>
			<content:encoded><![CDATA[<p>Thanks to everyone who left a comment or sent me an e-mail regarding the Index Defrag Script.  I've received some great feedback and requests for features.  I've also had some questions regarding how to use it, which I will answer at the end of this post.  </p>
<p><em>Changes include: </em><br />
 - separate version for both Enterprise and Standard editions<br />
&nbsp;&nbsp;&nbsp;&nbsp;- Standard edition removes partitioning and online options<br />
 - output option to see fragmentation levels<br />
 - page_count added to the log table</p>
<p>I've also verified that this script works well in SQL 2008.</p>
<p><strong>Enterprise Version:</strong></p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">IF</span> <span style="color: #808080;">EXISTS</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">tables</span>
                <span style="color: #0000FF;">WHERE</span> <span style="color: #808080;">&#91;</span>name<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> N<span style="color: #FF0000;">'dba_indexDefragLog'</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">BEGIN</span>
&nbsp;
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">dba_indexDefragLog</span>;
&nbsp;
    <span style="color: #0000FF;">PRINT</span> <span style="color: #FF0000;">'dba_indexDefragLog table dropped!'</span>;
&nbsp;
<span style="color: #0000FF;">END</span>
&nbsp;
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">dba_indexDefragLog</span>
<span style="color: #808080;">&#40;</span>
      indexDefrag_id    <span style="color: #0000FF;">INT</span> <span style="color: #0000FF;">IDENTITY</span><span style="color: #808080;">&#40;</span><span style="color: #000;">1</span>,<span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>   <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , objectID          <span style="color: #0000FF;">INT</span>                 <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , objectName        <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">130</span><span style="color: #808080;">&#41;</span>       <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , indexID           <span style="color: #0000FF;">INT</span>                 <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , indexName         <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">130</span><span style="color: #808080;">&#41;</span>       <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , partitionNumber   <span style="color: #0000FF;">SMALLINT</span>            not null
    , fragmentation     <span style="color: #0000FF;">FLOAT</span>               <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , page_count        <span style="color: #0000FF;">INT</span>                 <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , dateTimeStart     <span style="color: #0000FF;">DATETIME</span>            <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , durationSeconds   <span style="color: #0000FF;">INT</span>                 <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    <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;">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: #0000FF;">IS</span> Null
<span style="color: #0000FF;">BEGIN</span>
    <span style="color: #0000FF;">EXECUTE</span> <span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Create Procedure dbo.dba_indexDefrag_sp
        As Print '</span><span style="color: #FF0000;">'Hello World!'</span><span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>;
    <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Procedure dba_indexDefrag_sp created.'</span>
        , <span style="color: #000;">10</span>, <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>;
<span style="color: #0000FF;">END</span>;
Go
&nbsp;
<span style="color: #0000FF;">SET</span> ANSI_Nulls <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> <span style="color: #0000FF;">NOCOUNT</span> <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>;
Go
&nbsp;
<span style="color: #0000FF;">ALTER</span> <span style="color: #0000FF;">PROCEDURE</span> dbo.<span style="color: #202020;">dba_indexDefrag_sp</span>
&nbsp;
    <span style="color: #008080;">/* Declare Parameters */</span>
      @minFragmentation     <span style="color: #0000FF;">FLOAT</span>           <span style="color: #808080;">=</span> <span style="color: #000;">10.0</span>
        <span style="color: #008080;">/* in percent, will not defrag if fragmentation
           less than specified */</span>
    , @rebuildThreshold     <span style="color: #0000FF;">FLOAT</span>           <span style="color: #808080;">=</span> <span style="color: #000;">30.0</span>
        <span style="color: #008080;">/* in percent, greater than @rebuildThreshold
           will result in rebuild instead of reorg */</span>
    , @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 */</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>
    , @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;">/* Option to specify a table name */</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>
<span style="color: #0000FF;">AS</span>
<span style="color: #008080;">/********************************************************************
    Name:       dba_indexDefrag_sp
&nbsp;
    Author:     Michelle F. Ufford
&nbsp;
    Purpose:    Defrags all indexes for the current database
&nbsp;
    Notes:      This script was designed for SQL Server 2005
                Enterprise Edition.
&nbsp;
    CAUTION: Monitor transaction log if executing for the first time!
&nbsp;
      @minFragmentation     defaulted to 10%, will not defrag if
                            fragmentation if less than specified.
&nbsp;
      @rebuildThreshold     defaulted to 30% as recommended by
                            Microsoft in BOL;
                            &gt; than 30% will result in rebuild instead
&nbsp;
      @onlineRebuild        1 = online rebuild; 
                            0 = offline rebuild
&nbsp;
      @executeSQL           1 = execute the SQL generated by this proc;
                            0 = print command only
&nbsp;
      @tableName            Specify if you only want to defrag indexes
                            for a specific table
&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 some time to catch up
&nbsp;
    Called by:  SQL Agent Job or DBA
&nbsp;
    Date        Initials  Description
    ----------------------------------------------------------------
    2008-10-27  MFU       Initial Release
    2008-11-17  MFU       Added page_count to log table
                          , added @printFragmentation option
********************************************************************
    Exec dbo.dba_indexDefrag_sp
          @executeSQL         = 1
        , @printCommands      = 1
        , @minFragmentation   = 0
        , @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>;
&nbsp;
<span style="color: #0000FF;">BEGIN</span>
&nbsp;
    <span style="color: #008080;">/* Declare our variables */</span>
    <span style="color: #0000FF;">DECLARE</span>   @objectID         <span style="color: #0000FF;">INT</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;">130</span><span style="color: #808080;">&#41;</span>
            , @objectName       <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">130</span><span style="color: #808080;">&#41;</span>
            , @indexName        <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">130</span><span style="color: #808080;">&#41;</span>
            , @partitionNumber  <span style="color: #0000FF;">SMALLINT</span>
            , @partitions       <span style="color: #0000FF;">SMALLINT</span>
            , @fragmentation    <span style="color: #0000FF;">FLOAT</span>
            , @pageCount        <span style="color: #0000FF;">INT</span>
            , @sqlCommand       <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>
            , @rebuildCommand   <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">200</span><span style="color: #808080;">&#41;</span>
            , @dateTimeStart    <span style="color: #0000FF;">DATETIME</span>
            , @dateTimeEnd      <span style="color: #0000FF;">DATETIME</span>
            , @containsLOB      <span style="color: #0000FF;">BIT</span>;
&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: #008080;">/* Determine which indexes to defrag using our
       user-defined parameters */</span>
    <span style="color: #0000FF;">SELECT</span>
          <span style="color: #FF00FF;">OBJECT_ID</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>
    <span style="color: #0000FF;">INTO</span> #indexDefragList
    <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>@tableName<span style="color: #808080;">&#41;</span>, <span style="color: #808080;">NULL</span> , <span style="color: #808080;">NULL</span>, N<span style="color: #FF0000;">'Limited'</span><span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">WHERE</span> avg_fragmentation_in_percent <span style="color: #808080;">&gt;</span> @minFragmentation
        And index_id <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span>
    <span style="color: #0000FF;">OPTION</span> <span style="color: #808080;">&#40;</span>MaxDop <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #008080;">/* Create a clustered index to boost performance a little */</span>
    <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>objectID, indexID, partitionNumber<span style="color: #808080;">&#41;</span>;
&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: #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
            , @fragmentation    <span style="color: #808080;">=</span> fragmentation
            , @indexID          <span style="color: #808080;">=</span> indexID
            , @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: #008080;">/* Look up index information */</span>
        <span style="color: #0000FF;">SELECT</span> @objectName <span style="color: #808080;">=</span> <span style="color: #FF00FF;">QUOTENAME</span><span style="color: #808080;">&#40;</span>o.<span style="color: #202020;">name</span><span style="color: #808080;">&#41;</span>
             , @schemaName <span style="color: #808080;">=</span> <span style="color: #FF00FF;">QUOTENAME</span><span style="color: #808080;">&#40;</span>s.<span style="color: #202020;">name</span><span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">objects</span> <span style="color: #0000FF;">AS</span> o
        <span style="color: #0000FF;">INNER</span> Join sys.<span style="color: #202020;">schemas</span> <span style="color: #0000FF;">AS</span> s
            <span style="color: #0000FF;">ON</span> s.<span style="color: #202020;">schema_id</span> <span style="color: #808080;">=</span> o.<span style="color: #202020;">schema_id</span>
        <span style="color: #0000FF;">WHERE</span> o.<span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> @objectID;
&nbsp;
        <span style="color: #0000FF;">SELECT</span> @indexName <span style="color: #808080;">=</span> <span style="color: #FF00FF;">QUOTENAME</span><span style="color: #808080;">&#40;</span>name<span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">indexes</span>
        <span style="color: #0000FF;">WHERE</span> <span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> @objectID
            And index_id <span style="color: #808080;">=</span> @indexID
            And type <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span>;
&nbsp;
        <span style="color: #008080;">/* Determine if the index is partitioned */</span>
        <span style="color: #0000FF;">SELECT</span> @partitionCount <span style="color: #808080;">=</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> sys.<span style="color: #202020;">partitions</span>
        <span style="color: #0000FF;">WHERE</span> <span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> @objectID
            And index_id <span style="color: #808080;">=</span> @indexID;
&nbsp;
        <span style="color: #008080;">/* Look for LOBs */</span>
        <span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">TOP</span> <span style="color: #000;">1</span>
            @containsLOB <span style="color: #808080;">=</span> column_id
        <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">columns</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> 
            <span style="color: #808080;">&#91;</span><span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> @objectID
            And <span style="color: #808080;">&#40;</span>system_type_id In <span style="color: #808080;">&#40;</span><span style="color: #000;">34</span>, <span style="color: #000;">35</span>, <span style="color: #000;">99</span><span style="color: #808080;">&#41;</span>
            <span style="color: #008080;">-- 34 = image, 35 = text, 99 = ntext</span>
                    Or max_length <span style="color: #808080;">=</span> <span style="color: #808080;">-</span><span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>;
            <span style="color: #008080;">-- varbinary(max), varchar(max), nvarchar(max), xml</span>
&nbsp;
        <span style="color: #008080;">/* See if we should rebuild or reorganize; handle thusly */</span>
        <span style="color: #0000FF;">IF</span> @fragmentation <span style="color: #808080;">&lt;</span> @rebuildThreshold And @partitionCount <span style="color: #808080;">&lt;=</span> <span style="color: #000;">1</span>
            <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> @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: #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;">0</span>
                <span style="color: #008080;">-- Cannot rebuild if the table has one or more LOB</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;">/* We should always rebuild online if possible
                (SQL 2005 Enterprise) */</span>
            <span style="color: #0000FF;">IF</span> @onlineRebuild <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
                <span style="color: #0000FF;">SET</span> @rebuildCommand <span style="color: #808080;">=</span> N<span style="color: #FF0000;">' Rebuild With
                    (Online = Off, MaxDop = 1)'</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 = On, MaxDop = 1)'</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> @schemaName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">'.'</span> <span style="color: #808080;">+</span> @objectName <span style="color: #808080;">+</span> @rebuildCommand;
        <span style="color: #0000FF;">END</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> 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> @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>
                <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>;
                <span style="color: #008080;">-- no MaxDop needed, single threaded operation</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: #008080;">/* Grab the time for logging purposes */</span>
            <span style="color: #0000FF;">SET</span> @dateTimeStart  <span style="color: #808080;">=</span> <span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>;
            <span style="color: #0000FF;">EXECUTE</span> <span style="color: #808080;">&#40;</span>@sqlCommand<span style="color: #808080;">&#41;</span>;
            <span style="color: #0000FF;">SET</span> @dateTimeEnd  <span style="color: #808080;">=</span> <span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>;
&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>
                  objectID
                , objectName
                , indexID
                , indexName
                , partitionNumber
                , fragmentation
                , page_count
                , dateTimeStart
                , durationSeconds
            <span style="color: #808080;">&#41;</span>
            <span style="color: #0000FF;">SELECT</span>
                  @objectID
                , @objectName
                , @indexID
                , @indexName
                , @partitionNumber
                , @fragmentation
                , @pageCount
                , @dateTimeStart
                , <span style="color: #FF00FF;">DATEDIFF</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SECOND</span>, @dateTimeStart, @dateTimeEnd<span style="color: #808080;">&#41;</span>;
&nbsp;
            <span style="color: #008080;">/* Just a little breather for the server */</span>
            <span style="color: #0000FF;">WAITFOR</span> Delay @defragDelay;
&nbsp;
            <span style="color: #008080;">/* Print if specified to do so */</span>
            <span style="color: #0000FF;">IF</span> @printCommands <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
                <span style="color: #0000FF;">PRINT</span> N<span style="color: #FF0000;">'Executed: '</span> <span style="color: #808080;">+</span> @sqlCommand;
        <span style="color: #0000FF;">END</span>
        <span style="color: #0000FF;">ELSE</span>
        <span style="color: #008080;">/* Looks like we're not executing, just print
            the commands */</span>
        <span style="color: #0000FF;">BEGIN</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> @sqlCommand;
        <span style="color: #0000FF;">END</span>
&nbsp;
        <span style="color: #008080;">/* Update our index defrag list when 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> 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;">SELECT</span> idl.<span style="color: #202020;">objectID</span>
            , o.<span style="color: #202020;">name</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'tableName'</span>
            , idl.<span style="color: #202020;">indexID</span>
            , i.<span style="color: #202020;">name</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'indexName'</span>
            , idl.<span style="color: #202020;">fragmentation</span>
            , idl.<span style="color: #202020;">page_count</span>
        <span style="color: #0000FF;">FROM</span> #indexDefragList <span style="color: #0000FF;">AS</span> idl
        Join sys.<span style="color: #202020;">objects</span> <span style="color: #0000FF;">AS</span> o
            <span style="color: #0000FF;">ON</span> idl.<span style="color: #202020;">objectID</span> <span style="color: #808080;">=</span> o.<span style="color: #FF00FF;">OBJECT_ID</span>
        Join sys.<span style="color: #202020;">indexes</span> <span style="color: #0000FF;">AS</span> i
            <span style="color: #0000FF;">ON</span> idl.<span style="color: #202020;">objectID</span> <span style="color: #808080;">=</span> i.<span style="color: #FF00FF;">OBJECT_ID</span>
            And idl.<span style="color: #202020;">indexID</span> <span style="color: #808080;">=</span> i.<span style="color: #202020;">index_id</span>;
&nbsp;
    <span style="color: #008080;">/* When everything is done, make sure to get rid of
        our temp table */</span>
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">TABLE</span> #indexDefragList;
&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>&nbsp;</p>
<p><strong>Standard Version:</strong></p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">IF</span> <span style="color: #808080;">EXISTS</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">tables</span>
                <span style="color: #0000FF;">WHERE</span> <span style="color: #808080;">&#91;</span>name<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> N<span style="color: #FF0000;">'dba_indexDefragLog'</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">BEGIN</span>
&nbsp;
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">dba_indexDefragLog</span>;
&nbsp;
    <span style="color: #0000FF;">PRINT</span> <span style="color: #FF0000;">'dba_indexDefragLog table dropped!'</span>;
&nbsp;
<span style="color: #0000FF;">END</span>
&nbsp;
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">dba_indexDefragLog</span>
<span style="color: #808080;">&#40;</span>
      indexDefrag_id    <span style="color: #0000FF;">INT</span> <span style="color: #0000FF;">IDENTITY</span><span style="color: #808080;">&#40;</span><span style="color: #000;">1</span>,<span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>   <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , objectID          <span style="color: #0000FF;">INT</span>                 <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , objectName        <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">130</span><span style="color: #808080;">&#41;</span>       <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , indexID           <span style="color: #0000FF;">INT</span>                 <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , indexName         <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">130</span><span style="color: #808080;">&#41;</span>       <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , fragmentation     <span style="color: #0000FF;">FLOAT</span>               <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , page_count        <span style="color: #0000FF;">INT</span>                 <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , dateTimeStart     <span style="color: #0000FF;">DATETIME</span>            <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , durationSeconds   <span style="color: #0000FF;">INT</span>                 <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    <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;">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_indexDefragStandard_sp'</span><span style="color: #808080;">&#41;</span>,
        N<span style="color: #FF0000;">'IsProcedure'</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">IS</span> Null
<span style="color: #0000FF;">BEGIN</span>
    <span style="color: #0000FF;">EXECUTE</span> <span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Create Procedure dbo.dba_indexDefragStandard_sp
        As Print '</span><span style="color: #FF0000;">'Hello World!'</span><span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>;
    <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Procedure dba_indexDefragStandard_sp created.'</span>
        , <span style="color: #000;">10</span>, <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>;
<span style="color: #0000FF;">END</span>;
Go
&nbsp;
<span style="color: #0000FF;">SET</span> ANSI_Nulls <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> <span style="color: #0000FF;">NOCOUNT</span> <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>;
Go
&nbsp;
<span style="color: #0000FF;">ALTER</span> <span style="color: #0000FF;">PROCEDURE</span> dbo.<span style="color: #202020;">dba_indexDefragStandard_sp</span>
&nbsp;
    <span style="color: #008080;">/* Declare Parameters */</span>
      @minFragmentation     <span style="color: #0000FF;">FLOAT</span>           <span style="color: #808080;">=</span> <span style="color: #000;">10.0</span>
        <span style="color: #008080;">/* in percent, will not defrag if fragmentation
           less than specified */</span>
    , @rebuildThreshold     <span style="color: #0000FF;">FLOAT</span>           <span style="color: #808080;">=</span> <span style="color: #000;">30.0</span>
        <span style="color: #008080;">/* in percent, greater than @rebuildThreshold
           will result in rebuild instead of reorg */</span>
    , @executeSQL           <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
        <span style="color: #008080;">/* 1 = execute; 0 = print command only */</span>
    , @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;">/* Option to specify a table name */</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>
<span style="color: #0000FF;">AS</span>
<span style="color: #008080;">/********************************************************************
    Name:       dba_indexDefragStandard_sp
&nbsp;
    Author:     Michelle F. Ufford
&nbsp;
    Purpose:    Defrags all indexes for the current database
&nbsp;
    Notes:      This script was designed for SQL Server 2005
                Standard edition.
&nbsp;
    CAUTION: Monitor transaction log if executing for the first time!
&nbsp;
      @minFragmentation     defaulted to 10%, will not defrag if
                            fragmentation if less than specified.
&nbsp;
      @rebuildThreshold     defaulted to 30% as recommended by
                            Microsoft in BOL;
                            &gt; than 30% will result in rebuild instead
&nbsp;
      @executeSQL           1 = execute the SQL generated by this proc;
                            0 = print command only
&nbsp;
      @tableName            Specify if you only want to defrag indexes
                            for a specific table
&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 some time to catch up
&nbsp;
    Called by:  SQL Agent Job or DBA
&nbsp;
    Date        Initials  Description
    ----------------------------------------------------------------
    2008-10-27  MFU       Initial Release
    2008-11-17  MFU       Added page_count to log table
                          , added @printFragmentation option
********************************************************************
    Exec dbo.dba_indexDefragStandard_sp
          @executeSQL         = 1
        , @printCommands      = 1
        , @minFragmentation   = 0
        , @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>;
&nbsp;
<span style="color: #0000FF;">BEGIN</span>
&nbsp;
    <span style="color: #008080;">/* Declare our variables */</span>
    <span style="color: #0000FF;">DECLARE</span>   @objectID         <span style="color: #0000FF;">INT</span>
            , @indexID          <span style="color: #0000FF;">INT</span>
            , @schemaName       <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">130</span><span style="color: #808080;">&#41;</span>
            , @objectName       <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">130</span><span style="color: #808080;">&#41;</span>
            , @indexName        <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">130</span><span style="color: #808080;">&#41;</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>;
&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: #008080;">/* Determine which indexes to defrag using our
       user-defined parameters */</span>
    <span style="color: #0000FF;">SELECT</span>
          <span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #0000FF;">AS</span> objectID
        , index_id <span style="color: #0000FF;">AS</span> indexID
        , 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>
    <span style="color: #0000FF;">INTO</span> #indexDefragList
    <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>@tableName<span style="color: #808080;">&#41;</span>, <span style="color: #808080;">NULL</span> , <span style="color: #808080;">NULL</span>, N<span style="color: #FF0000;">'Limited'</span><span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">WHERE</span> avg_fragmentation_in_percent <span style="color: #808080;">&gt;</span> @minFragmentation
        And index_id <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span>
    <span style="color: #0000FF;">OPTION</span> <span style="color: #808080;">&#40;</span>MaxDop <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #008080;">/* Create a clustered index to boost performance a little */</span>
    <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>objectID, indexID<span style="color: #808080;">&#41;</span>;
&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: #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
            , @fragmentation    <span style="color: #808080;">=</span> fragmentation
            , @indexID          <span style="color: #808080;">=</span> indexID
            , @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: #008080;">/* Look up index information */</span>
        <span style="color: #0000FF;">SELECT</span> @objectName <span style="color: #808080;">=</span> <span style="color: #FF00FF;">QUOTENAME</span><span style="color: #808080;">&#40;</span>o.<span style="color: #202020;">name</span><span style="color: #808080;">&#41;</span>
             , @schemaName <span style="color: #808080;">=</span> <span style="color: #FF00FF;">QUOTENAME</span><span style="color: #808080;">&#40;</span>s.<span style="color: #202020;">name</span><span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">objects</span> <span style="color: #0000FF;">AS</span> o
        <span style="color: #0000FF;">INNER</span> Join sys.<span style="color: #202020;">schemas</span> <span style="color: #0000FF;">AS</span> s
            <span style="color: #0000FF;">ON</span> s.<span style="color: #202020;">schema_id</span> <span style="color: #808080;">=</span> o.<span style="color: #202020;">schema_id</span>
        <span style="color: #0000FF;">WHERE</span> o.<span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> @objectID;
&nbsp;
        <span style="color: #0000FF;">SELECT</span> @indexName <span style="color: #808080;">=</span> <span style="color: #FF00FF;">QUOTENAME</span><span style="color: #808080;">&#40;</span>name<span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">indexes</span>
        <span style="color: #0000FF;">WHERE</span> <span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> @objectID
            And index_id <span style="color: #808080;">=</span> @indexID
            And type <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span>;
&nbsp;
        <span style="color: #008080;">/* Look for LOBs */</span>
        <span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">TOP</span> <span style="color: #000;">1</span>
            @containsLOB <span style="color: #808080;">=</span> column_id
        <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">columns</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> 
            <span style="color: #808080;">&#91;</span><span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> @objectID
            And <span style="color: #808080;">&#40;</span>system_type_id In <span style="color: #808080;">&#40;</span><span style="color: #000;">34</span>, <span style="color: #000;">35</span>, <span style="color: #000;">99</span><span style="color: #808080;">&#41;</span>
            <span style="color: #008080;">-- 34 = image, 35 = text, 99 = ntext</span>
                    Or max_length <span style="color: #808080;">=</span> <span style="color: #808080;">-</span><span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>;
            <span style="color: #008080;">-- varbinary(max), varchar(max), nvarchar(max), xml</span>
&nbsp;
        <span style="color: #008080;">/* See if we should rebuild or reorganize; handle thusly */</span>
        <span style="color: #0000FF;">IF</span> @fragmentation <span style="color: #808080;">&lt;</span> @rebuildThreshold 
            Or IsNull<span style="color: #808080;">&#40;</span>@containsLOB, <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: #008080;">-- Cannot rebuild if the table has one or more LOB</span>
            <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> @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>
        <span style="color: #0000FF;">ELSE</span>
            <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> @schemaName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">'.'</span> <span style="color: #808080;">+</span> @objectName <span style="color: #808080;">+</span>  <span style="color: #FF0000;">' Rebuild '</span>
                <span style="color: #808080;">+</span> <span style="color: #FF0000;">'With (MaxDop = 1)'</span>; <span style="color: #008080;">-- minimize impact on server</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: #008080;">/* Grab the time for logging purposes */</span>
            <span style="color: #0000FF;">SET</span> @dateTimeStart  <span style="color: #808080;">=</span> <span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>;
            <span style="color: #0000FF;">EXECUTE</span> <span style="color: #808080;">&#40;</span>@sqlCommand<span style="color: #808080;">&#41;</span>;
            <span style="color: #0000FF;">SET</span> @dateTimeEnd  <span style="color: #808080;">=</span> <span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>;
&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>
                  objectID
                , objectName
                , indexID
                , indexName
                , fragmentation
                , page_count
                , dateTimeStart
                , durationSeconds
            <span style="color: #808080;">&#41;</span>
            <span style="color: #0000FF;">SELECT</span>
                  @objectID
                , @objectName
                , @indexID
                , @indexName
                , @fragmentation
                , @pageCount
                , @dateTimeStart
                , <span style="color: #FF00FF;">DATEDIFF</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SECOND</span>, @dateTimeStart, @dateTimeEnd<span style="color: #808080;">&#41;</span>;
&nbsp;
            <span style="color: #008080;">/* Just a little breather for the server */</span>
            <span style="color: #0000FF;">WAITFOR</span> Delay @defragDelay;
&nbsp;
            <span style="color: #008080;">/* Print if specified to do so */</span>
            <span style="color: #0000FF;">IF</span> @printCommands <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
                <span style="color: #0000FF;">PRINT</span> N<span style="color: #FF0000;">'Executed: '</span> <span style="color: #808080;">+</span> @sqlCommand;
        <span style="color: #0000FF;">END</span>
        <span style="color: #0000FF;">ELSE</span>
        <span style="color: #008080;">/* Looks like we're not executing, just print
            the commands */</span>
        <span style="color: #0000FF;">BEGIN</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> @sqlCommand;
        <span style="color: #0000FF;">END</span>
&nbsp;
        <span style="color: #008080;">/* Update our index defrag list when 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> objectID  <span style="color: #808080;">=</span> @objectID
          And indexID   <span style="color: #808080;">=</span> @indexID;
&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;">SELECT</span> idl.<span style="color: #202020;">objectID</span>
            , o.<span style="color: #202020;">name</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'tableName'</span>
            , idl.<span style="color: #202020;">indexID</span>
            , i.<span style="color: #202020;">name</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'indexName'</span>
            , idl.<span style="color: #202020;">fragmentation</span>
            , idl.<span style="color: #202020;">page_count</span>
        <span style="color: #0000FF;">FROM</span> #indexDefragList <span style="color: #0000FF;">AS</span> idl
        <span style="color: #808080;">JOIN</span> sys.<span style="color: #202020;">objects</span> <span style="color: #0000FF;">AS</span> o
            <span style="color: #0000FF;">ON</span> idl.<span style="color: #202020;">objectID</span> <span style="color: #808080;">=</span> o.<span style="color: #FF00FF;">OBJECT_ID</span>
        <span style="color: #808080;">JOIN</span> sys.<span style="color: #202020;">indexes</span> <span style="color: #0000FF;">AS</span> i
            <span style="color: #0000FF;">ON</span> idl.<span style="color: #202020;">objectID</span> <span style="color: #808080;">=</span> i.<span style="color: #FF00FF;">OBJECT_ID</span>
            <span style="color: #808080;">AND</span> idl.<span style="color: #202020;">indexID</span> <span style="color: #808080;">=</span> i.<span style="color: #202020;">index_id</span>;
&nbsp;
    <span style="color: #008080;">/* When everything is done, make sure to get rid of
        our temp table */</span>
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">TABLE</span> #indexDefragList;
&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>&nbsp;</p>
<p>For those who are having troubles with this script...</p>
<p>1) "Not all of my indexes were defragged!" or "Nothing happened when I executed this script." </p>
<p>This script will only defrag those indexes that surpass the specified threshold.  If you're not seeing your index in the output, try executing this:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;">    <span style="color: #0000FF;">EXEC</span> dbo.<span style="color: #202020;">dba_indexDefrag_sp</span>
          @executeSQL    <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
        , @printCommands <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
        , @minFragmentation <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
        , @printFragmentation <span style="color: #808080;">=</span> <span style="color: #000;">1</span>;</pre></div></div>

<p>Check to see what your index's fragmentation level is.  Maybe it's not as fragmented as you feared.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>2) "My indexes are still fragmented after running this script."</p>
<p>  To quote The Powers That Be (aka Microsoft)...</p>
<blockquote><p>"In general, fragmentation on small indexes is often not controllable. The pages of small indexes are stored on mixed extents. Mixed extents are shared by up to eight objects, so the fragmentation in a small index might not be reduced after reorganizing or rebuilding the index."  -- <a href="http://msdn.microsoft.com/en-us/library/ms189858.aspx" target="_blank">Reorganizing and Rebuilding Indexes</a></p></blockquote>
<p>3) "Can I use this in my production environment?"</p>
<p>That really depends on your environment.  I've successfully used this in some very large production environments.  However, I wouldn't exactly recommend executing the script in the middle of a business day on a billion+ row, heavily fragmented, unpartitioned table, either.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </p>
<p>If you're not sure what the impact will be, execute the commands-only version of the script...</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;">    <span style="color: #0000FF;">EXEC</span> dbo.<span style="color: #202020;">dba_indexDefrag_sp</span>
	      @executeSQL    <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
        , @printCommands <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
        , @printFragmentation <span style="color: #808080;">=</span> <span style="color: #000;">1</span>;</pre></div></div>

<p>... then execute the statements one at a time.  Make sure you monitor tempdb and the transaction log to ensure you don't have any space issues.</p>
<p>If you have any additional questions or suggestions for this script, leave me a comment and I'll be happy to help.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2008/11/updated-index-defrag-script-2005-2008/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>Partitioning Example</title>
		<link>http://sqlfool.com/2008/11/102/</link>
		<comments>http://sqlfool.com/2008/11/102/#comments</comments>
		<pubDate>Mon, 03 Nov 2008 22:29:11 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[T-SQL Scripts]]></category>
		<category><![CDATA[partitioning]]></category>
		<category><![CDATA[TSQL]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=102</guid>
		<description><![CDATA[The following code will walk you through the process of creating a partitioned table: -------------------------------- -- Create A Partitioned Table -- -------------------------------- &#160; /* Create a partition function. */ CREATE Partition FUNCTION &#91;test_monthlyDateRange_pf&#93; &#40;SMALLDATETIME&#41; AS Range RIGHT FOR VALUES &#40;'2008-01-01', '2008-02-01', '2008-03-01'&#41;; Go &#160; /* Associate the partition function with a partition scheme. */ CREATE [...]]]></description>
			<content:encoded><![CDATA[<p>The following code will walk you through the process of creating a partitioned table:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">--------------------------------</span>
<span style="color: #008080;">-- Create A Partitioned Table --</span>
<span style="color: #008080;">--------------------------------</span>
&nbsp;
<span style="color: #008080;">/* Create a partition function. */</span>
<span style="color: #0000FF;">CREATE</span> Partition <span style="color: #0000FF;">FUNCTION</span> <span style="color: #808080;">&#91;</span>test_monthlyDateRange_pf<span style="color: #808080;">&#93;</span> <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;">'2008-01-01'</span>, <span style="color: #FF0000;">'2008-02-01'</span>, <span style="color: #FF0000;">'2008-03-01'</span><span style="color: #808080;">&#41;</span>;
Go
&nbsp;
<span style="color: #008080;">/* Associate the partition function with a partition scheme. */</span>
<span style="color: #0000FF;">CREATE</span> Partition Scheme test_monthlyDateRange_ps 
    <span style="color: #0000FF;">AS</span> Partition test_monthlyDateRange_pf 
    All <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>;
Go
&nbsp;
<span style="color: #008080;">/* Create your first partitioned table! 
   Make sure the data types match.  */</span>
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">orders</span>
<span style="color: #808080;">&#40;</span>
      order_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
    , orderDate <span style="color: #0000FF;">SMALLDATETIME</span>       Not Null
&nbsp;
    <span style="color: #0000FF;">CONSTRAINT</span> PK_orders <span style="color: #0000FF;">PRIMARY</span> <span style="color: #0000FF;">KEY</span> <span style="color: #0000FF;">CLUSTERED</span>
    <span style="color: #808080;">&#40;</span>
        orderDate
      , order_id
    <span style="color: #808080;">&#41;</span>
<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">ON</span> test_monthlyDateRange_ps<span style="color: #808080;">&#40;</span>orderDate<span style="color: #808080;">&#41;</span>;
Go
&nbsp;
<span style="color: #008080;">/* Create some records to play with. */</span>
<span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> dbo.<span style="color: #202020;">orders</span>
<span style="color: #0000FF;">SELECT</span> <span style="color: #FF0000;">'2007-12-31'</span> <span style="color: #0000FF;">UNION</span> All
<span style="color: #0000FF;">SELECT</span> <span style="color: #FF0000;">'2008-01-02'</span> <span style="color: #0000FF;">UNION</span> All
<span style="color: #0000FF;">SELECT</span> <span style="color: #FF0000;">'2008-01-03'</span> <span style="color: #0000FF;">UNION</span> All
<span style="color: #0000FF;">SELECT</span> <span style="color: #FF0000;">'2008-01-04'</span> <span style="color: #0000FF;">UNION</span> All
<span style="color: #0000FF;">SELECT</span> <span style="color: #FF0000;">'2008-02-01'</span> <span style="color: #0000FF;">UNION</span> All
<span style="color: #0000FF;">SELECT</span> <span style="color: #FF0000;">'2008-02-02'</span> <span style="color: #0000FF;">UNION</span> All
<span style="color: #0000FF;">SELECT</span> <span style="color: #FF0000;">'2008-03-01'</span> <span style="color: #0000FF;">UNION</span> All
<span style="color: #0000FF;">SELECT</span> <span style="color: #FF0000;">'2008-03-02'</span>;
&nbsp;
<span style="color: #008080;">/* The $partition function can be used to interrogate partition data.
   Let's use it to see where those records are physically located. */</span>
<span style="color: #0000FF;">SELECT</span> $partition.<span style="color: #202020;">test_monthlyDateRange_pf</span><span style="color: #808080;">&#40;</span>orderDate<span style="color: #808080;">&#41;</span> 
    <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'partition_number'</span>
    , <span style="color: #808080;">*</span>
<span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">orders</span>;
&nbsp;
<span style="color: #008080;">/* By default, all new indexes are created on the partition.
   Let's create an aligned index */</span>
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">NONCLUSTERED</span> <span style="color: #0000FF;">INDEX</span> IX_orders_aligned
    <span style="color: #0000FF;">ON</span> dbo.<span style="color: #202020;">orders</span><span style="color: #808080;">&#40;</span>order_id<span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">ON</span> test_monthlyDateRange_ps<span style="color: #808080;">&#40;</span>orderDate<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #008080;">/* Now let's create an un-aligned index.
   We'll need to specify the filegroup. */</span>
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">NONCLUSTERED</span> <span style="color: #0000FF;">INDEX</span> IX_orders_nonaligned
    <span style="color: #0000FF;">ON</span> dbo.<span style="color: #202020;">orders</span><span style="color: #808080;">&#40;</span>order_id<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>; <span style="color: #008080;">-- can be any filegroup</span>
&nbsp;
<span style="color: #008080;">/* Review your indexes */</span>
<span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">SP_HELPINDEX</span> orders;</pre></div></div>

<p>Using the previous code as a building block, let's try swapping partitions:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">--------------------------</span>
<span style="color: #008080;">-- Swap Out A Partition --</span>
<span style="color: #008080;">--------------------------</span>
&nbsp;
<span style="color: #008080;">/* We need to drop our un-aligned index; otherwise we'll 
   get an error when we attempt to do the switch. */</span>
<span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">INDEX</span> IX_orders_nonaligned <span style="color: #0000FF;">ON</span> dbo.<span style="color: #202020;">orders</span>;
&nbsp;
<span style="color: #008080;">/* Create the table to hold the data you're swapping out.
   The table structures must match identically; however, 
   DO NOT partition this table. */</span>
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">orders_stage_swapOut</span>
<span style="color: #808080;">&#40;</span>
      order_id  <span style="color: #0000FF;">INT</span>             Not Null
    , orderDate <span style="color: #0000FF;">SMALLDATETIME</span>   Not Null
&nbsp;
    <span style="color: #0000FF;">CONSTRAINT</span> PK_orders_stage_swapOut <span style="color: #0000FF;">PRIMARY</span> <span style="color: #0000FF;">KEY</span> <span style="color: #0000FF;">CLUSTERED</span>
    <span style="color: #808080;">&#40;</span>
        orderDate
      , order_id
    <span style="color: #808080;">&#41;</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>;
Go
&nbsp;
<span style="color: #008080;">/* Create the table to hold the data you're swapping in.
   The table structures must match identically; however,
   DO NOT partition this table. */</span>
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">orders_stage_swapIn</span>
<span style="color: #808080;">&#40;</span>
      order_id  <span style="color: #0000FF;">INT</span>             Not Null
    , orderDate <span style="color: #0000FF;">SMALLDATETIME</span>   Not Null
&nbsp;
    <span style="color: #0000FF;">CONSTRAINT</span> PK_orders_stage_swapIn <span style="color: #0000FF;">PRIMARY</span> <span style="color: #0000FF;">KEY</span> <span style="color: #0000FF;">CLUSTERED</span>
    <span style="color: #808080;">&#40;</span>
        orderDate
      , order_id
    <span style="color: #808080;">&#41;</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>;
Go
&nbsp;
<span style="color: #008080;">/* Populate the table you're swapping in. */</span>
<span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> dbo.<span style="color: #202020;">orders_stage_swapIn</span>
<span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">-</span><span style="color: #000;">5</span>, <span style="color: #FF0000;">'2008-02-02'</span> <span style="color: #0000FF;">UNION</span> All
<span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">-</span><span style="color: #000;">4</span>, <span style="color: #FF0000;">'2008-02-03'</span> <span style="color: #0000FF;">UNION</span> All
<span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">-</span><span style="color: #000;">3</span>, <span style="color: #FF0000;">'2008-02-04'</span> <span style="color: #0000FF;">UNION</span> All
<span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">-</span><span style="color: #000;">2</span>, <span style="color: #FF0000;">'2008-02-05'</span> <span style="color: #0000FF;">UNION</span> All
<span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">-</span><span style="color: #000;">1</span>, <span style="color: #FF0000;">'2008-02-06'</span>;
&nbsp;
<span style="color: #008080;">/* Create any indexes on your table to match the 
   indexes on your partitioned table. */</span>
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">NONCLUSTERED</span> <span style="color: #0000FF;">INDEX</span> IX_orders_stage_swapIn
    <span style="color: #0000FF;">ON</span> dbo.<span style="color: #202020;">orders_stage_swapIn</span><span style="color: #808080;">&#40;</span>order_id<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #008080;">/* Add a check constraint for the 
   partition to be swapped in. 
   This step is required. */</span>
<span style="color: #0000FF;">ALTER</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">orders_stage_swapIn</span>
<span style="color: #0000FF;">WITH</span> <span style="color: #0000FF;">CHECK</span>
<span style="color: #0000FF;">ADD</span> <span style="color: #0000FF;">CONSTRAINT</span> orders_stage_swapIn_orderDateCK
	<span style="color: #0000FF;">CHECK</span> <span style="color: #808080;">&#40;</span>orderDate <span style="color: #808080;">&gt;=</span> <span style="color: #FF0000;">'2008-02-01'</span> 
		And orderDate <span style="color: #808080;">&lt;</span> <span style="color: #FF0000;">'2008-03-01'</span><span style="color: #808080;">&#41;</span>;
Go
&nbsp;
<span style="color: #008080;">/* Swap out the old partition. */</span>
<span style="color: #0000FF;">ALTER</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">orders</span> 
    Switch Partition <span style="color: #000;">3</span> <span style="color: #0000FF;">TO</span> dbo.<span style="color: #202020;">orders_stage_swapOut</span>;
Go
&nbsp;
<span style="color: #008080;">/* Swap in the new partition. */</span>
<span style="color: #0000FF;">ALTER</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">orders_stage_swapIn</span>
    Switch <span style="color: #0000FF;">TO</span> dbo.<span style="color: #202020;">orders</span> Partition <span style="color: #000;">3</span>;
Go
&nbsp;
<span style="color: #008080;">---------------------</span>
<span style="color: #008080;">-- Check your data --</span>
<span style="color: #008080;">---------------------</span>
&nbsp;
<span style="color: #008080;">/* You should have 2 records in here. */</span>
<span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">*</span> <span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">orders_stage_swapOut</span>;
&nbsp;
<span style="color: #008080;">/* You should have 5 records here. */</span>
<span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">*</span> 
<span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">orders</span>
<span style="color: #0000FF;">WHERE</span> orderDate <span style="color: #808080;">&gt;=</span> <span style="color: #FF0000;">'2008-02-01'</span> 
And orderDate <span style="color: #808080;">&lt;</span> <span style="color: #FF0000;">'2008-03-01'</span>;
&nbsp;
<span style="color: #008080;">/* There should be no records in this table. */</span>
<span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">*</span> <span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">orders_stage_swapIn</span>;
&nbsp;
<span style="color: #0000FF;">SELECT</span> $partition.<span style="color: #202020;">test_monthlyDateRange_pf</span><span style="color: #808080;">&#40;</span>orderDate<span style="color: #808080;">&#41;</span> 
    <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'partition_number'</span>
    , <span style="color: #808080;">*</span>
<span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">orders</span>;
&nbsp;
<span style="color: #008080;">/* Clean-up time!
Drop Table dbo.orders
Drop Table dbo.orders_stage_swapOut
Drop Table dbo.orders_stage_swapIn
Drop Partition Scheme test_monthlyDateRange_ps
Drop Partition Function [test_monthlyDateRange_pf]
*/</span></pre></div></div>

<p>Pretty easy, huh? <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2008/11/102/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
