<?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; SQL 2008</title>
	<atom:link href="http://sqlfool.com/category/sql-2008/feed/" rel="self" type="application/rss+xml" />
	<link>http://sqlfool.com</link>
	<description>Self-Professed SQL Scripting Junkie!</description>
	<lastBuildDate>Wed, 02 May 2012 21:25:28 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	
		<item>
		<title>Are You Approaching Your Partition Range Limits?</title>
		<link>http://sqlfool.com/2011/11/are-you-approaching-your-partition-range-limits/</link>
		<comments>http://sqlfool.com/2011/11/are-you-approaching-your-partition-range-limits/#comments</comments>
		<pubDate>Wed, 02 Nov 2011 20:32:01 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Miscellaneous]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[SQL Tips]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[T-SQL Scripts]]></category>
		<category><![CDATA[maintenace]]></category>
		<category><![CDATA[partitioning]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[TSQL]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1586</guid>
		<description><![CDATA[In my post last week, How To Estimate Data Utilization, I said that it may be my last post for a while. Well&#8230; apparently I lied. For those of you who use table partitioning, you know that you need to define a partitioning scheme and function prior to applying partitioning to an index. Personally, I [...]]]></description>
			<content:encoded><![CDATA[<p>In my post last week, <a href="http://sqlfool.com/2011/10/how-to-estimate-data-utilization/" target="_blank">How To Estimate Data Utilization</a>, I said that it may be my last post for a while.  Well&#8230; apparently I lied.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>For those of you who use <a href="http://sqlfool.com/2008/11/102/" target="_blank">table partitioning</a>, you know that you need to define a partitioning scheme and function prior to applying partitioning to an index.  Personally, I tend to build the function for a couple of years out, and I tend to create them through the end of a calendar year.  Now, if I failed to expand a partition range at the end of the year, then come January 1st, all of my data would be written to the same partition.  Not the end of the world, no, but it causes all kinds of nasty performance and maintenance issues.  Thus, as part of my end-of-year / maternity-leave preparations, I&#8217;m in the process of examining all partitioned functions to identify those that need to have their partition ranges expanded. For those interested, here&#8217;s the script I used:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">IF</span> <span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'tempdb..#Results'</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">IS</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">TABLE</span> #Results;
&nbsp;
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> #Results
<span style="color: #808080;">&#40;</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>
    , 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>
    , functionName  <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span>
    , data_space_id <span style="color: #0000FF;">INT</span>
    , maxRangeValue <span style="color: #0000FF;">SQL_VARIANT</span>
<span style="color: #808080;">&#41;</span>
&nbsp;
<span style="color: #008080;">/* Grab results for each database and store in our temp table.  
   And no, I don't *need* to select from sys.indexes and perform 
   left joins, but I'm overly cautious and want to make sure 
   I'm not accidentally missing any databases. :) */</span>
&nbsp;
<span style="color: #008080;">--EXECUTE master.dbo.sp_msforeachdb</span>
<span style="color: #0000FF;">EXECUTE</span> sp_foreachdb <span style="color: #FF0000;">'USE ?;
INSERT INTO #Results
SELECT DB_NAME() AS databaseName
    , sps.name AS schemaName
    , spf.name AS functionName
    , sps.data_space_id 
    , MAX(prv.value) AS maxRangeValue
FROM sys.indexes AS i
LEFT JOIN sys.partition_schemes AS sps WITH (NOLOCK)
    ON i.data_space_id = sps.data_space_id
LEFT JOIN sys.partition_functions AS spf WITH (NOLOCK)
    ON sps.function_id = spf.function_id
LEFT JOIN sys.partition_range_values AS prv WITH (NOLOCK)
    ON spf.function_id = prv.function_id
GROUP BY sps.name
    , spf.name
    , sps.data_space_id;'</span>;
<span style="color: #008080;">/*  
    sp_foreachdb was written by SQL MVP Aaron Bertrand and can be downloaded 
    at http://www.mssqltips.com/sqlservertip/2201/making-a-more-reliable-and-flexible-spmsforeachdb/
    Alternatively, you can also use sys.sp_MSforeachdb
*/</span>
&nbsp;
<span style="color: #008080;">/* Make sure we're not missing any major databases */</span>
<span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">*</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;">NOT</span> <span style="color: #808080;">IN</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> databaseName <span style="color: #0000FF;">FROM</span> #Results<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #008080;">/* Retrieve our results */</span>
<span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">*</span> 
<span style="color: #0000FF;">FROM</span> #Results
<span style="color: #0000FF;">WHERE</span> schemaName <span style="color: #0000FF;">IS</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
<span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> maxRangeValue;</pre></div></div>

<p>Example Results:</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">databaseName        schemaName                      functionName                          data_space_id   maxRangeValue
------------------- ------------------------------- ------------------------------------- --------------- -------------------------
HistoricalMart      dailyRangeDate_ps               dailyRangeDate_pf                     65609           2011-12-31 00:00:00.000
AdventureWorks      yearlyRangeSmallDateTime_ps     yearlyRangeSmallDateTime_pf           65605           2012-01-01 00:00:00.000
dbaTools            monthlyRangeDateTime_ps         monthlyRangeDateTime_pf               65604           2012-12-01 00:00:00.000</pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2011/11/are-you-approaching-your-partition-range-limits/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>How To Estimate Data Utilization</title>
		<link>http://sqlfool.com/2011/10/how-to-estimate-data-utilization/</link>
		<comments>http://sqlfool.com/2011/10/how-to-estimate-data-utilization/#comments</comments>
		<pubDate>Fri, 28 Oct 2011 19:11:12 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Business Intelligence]]></category>
		<category><![CDATA[Miscellaneous]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[SQL Tips]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[T-SQL Scripts]]></category>
		<category><![CDATA[DMV]]></category>
		<category><![CDATA[indexes]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[TSQL]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1578</guid>
		<description><![CDATA[Recently, on a conference call presenting data growth rates and database capacity projections, I had a top-line executive ask, &#8220;But how much of that data are we actually using today?&#8221; The question was met with silence; unless you have rigorous auditing in place &#8212; and kudos to you if you do &#8212; it&#8217;s a difficult [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, on a conference call presenting data growth rates and database capacity projections, I had a top-line executive ask, &#8220;But how much of that data are we actually <em>using</em> today?&#8221;  The question was met with silence; unless you have rigorous auditing in place &#8212; and kudos to you if you do &#8212; it&#8217;s a difficult question to answer.  But it begs the question, is there some way to gleam this information from SQL Server?  I think the answer is &#8220;yes,&#8221; if you make some assumptions and understand what you&#8217;re looking at.  </p>
<p>SQL Server collects stats about every time an index is used and how it is used (i.e. whether a user seeked or scanned the index, etc.).  It also provides a DMV to view these stats: <a href="http://msdn.microsoft.com/en-us/library/ms188755.aspx" target="_blank">sys.dm_db_index_usage_stats</a>.</p>
<p>This DMV provides a wealth of great information, but to answer our question of &#8220;What data is actually being used?&#8221;, we have to refine our criteria.  Are we talking in terms of table counts or data size?  I&#8217;d argue that data size is more important than table counts; one unqueried millow-row table is more wasteful than a hundred ten-row tables.  </p>
<p>Also, are we looking at indexes or content?  From a database perspective, I&#8217;m more interested in indexes: how much space are we wasting on unused indexes?  To identify this, I need to look at the activity on each individual index.</p>
<p>From a business perspective, I would be more interested in content (i.e. tables): how much business information is being stored that no one is even looking at?  To answer this question, I need to roll up all index usage to see if *any* of the indexes on a table were used.  Since both were of interest to me, I decided to write queries to answer both questions.  </p>
<p>Lastly, we need to understand the flaws with this data.  Chiefly, I cannot tell whether a user requested one row from a million-row table, or if [s]he needed all of the data in the table.  This is a pretty important issue, especially with large historical data stores, and it&#8217;s where I have to make the biggest assumption: if even one person looked at one row in the table, I count all pages in the table as having been accessed.  </p>
<p>Now, you may make different decisions than I did above, and that&#8217;s fine&#8230; each environment and project has different needs.  But these assumptions are very important to understanding the output of the query below:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">USE</span> master;
GO
&nbsp;
<span style="color: #008080;">/* 
    This will give you an approximation of how much data is being utilized on a server.
    Since the data is only valid as of the last server reboot, we should start off with
    an idea of how much data we've accrued.  
*/</span>
&nbsp;
<span style="color: #008080;">/* Find out when the server was last rebooted */</span>
<span style="color: #008080;">-- 2008</span>
<span style="color: #0000FF;">SELECT</span> sqlserver_start_time <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">dm_os_sys_info</span>;
<span style="color: #008080;">-- 2005</span>
<span style="color: #0000FF;">SELECT</span> create_date <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> <span style="color: #FF0000;">'tempdb'</span>;
&nbsp;
&nbsp;
<span style="color: #008080;">/* Create a temporary table to hold our data, since we're going to iterate through databases */</span>
<span style="color: #0000FF;">IF</span> <span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'tempdb..#Results'</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">IS</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">TABLE</span> #Results;
&nbsp;
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> #Results
<span style="color: #808080;">&#40;</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>
    , tableName     <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>
    , records       <span style="color: #0000FF;">BIGINT</span>
    , activity      <span style="color: #0000FF;">BIGINT</span>
    , totalPages    <span style="color: #0000FF;">BIGINT</span>
<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #008080;">/*  
    sp_foreachdb was written by SQL MVP Aaron Bertrand and can be downloaded 
    at http://www.mssqltips.com/sqlservertip/2201/making-a-more-reliable-and-flexible-spmsforeachdb/
    Alternatively, you can also use sys.sp_MSforeachdb
*/</span>
<span style="color: #008080;">--EXECUTE master.dbo.sp_foreachdb</span>
<span style="color: #0000FF;">EXECUTE</span> sys.<span style="color: #202020;">sp_MSforeachdb</span>
<span style="color: #FF0000;">'   USE ?; 
&nbsp;
    -- You can gleam a lot of information about historical data usage from partitions
    -- but for now, we will just roll up any partitions we may have
    WITH myCTE AS
    (
        SELECT p.[object_id] AS objectID
            , p.index_id
            , SUM(p.[rows]) AS records
            , SUM(au.total_pages) AS totalPages
        FROM sys.partitions AS p WITH (NOLOCK)
        JOIN sys.allocation_units AS au WITH (NOLOCK)
            ON p.hobt_id = au.container_id
        GROUP BY p.[object_id] 
            , p.index_id
    )
&nbsp;
    -- Grab all tables and join to our usage stats DMV
    INSERT INTO #Results
    SELECT DB_NAME() AS databaseName
        , t.name
        , x.index_id
        , MAX(x.records) AS records
        , ISNULL(SUM(us.user_lookups + us.user_scans + us.user_seeks), 0) AS activity
        , SUM(x.totalPages) AS totalPages
    FROM sys.tables AS t WITH (NOLOCK)
    JOIN myCTE AS x
        ON t.[object_id] = x.objectID
    LEFT JOIN sys.dm_db_index_usage_stats AS us WITH (NOLOCK)
        ON us.[object_id] = x.objectID
        AND us.index_id = x.index_id
        AND us.database_id = DB_ID()
    GROUP BY t.name
    , x.index_id;'</span>
&nbsp;
<span style="color: #008080;">/* Because we're looping through databases, make sure we're not missing any major ones */</span>
<span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">*</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;">NOT</span> <span style="color: #808080;">IN</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> databaseName <span style="color: #0000FF;">FROM</span> #Results<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #008080;">/* Retrieve actual % data utilization, which is performed at the index level */</span>
<span style="color: #0000FF;">SELECT</span> databaseName
    , <span style="color: #FF00FF;">SUM</span><span style="color: #808080;">&#40;</span>queriedPages<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> TotalQueriedPages
    , <span style="color: #FF00FF;">SUM</span><span style="color: #808080;">&#40;</span>totalPages<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> TotalPages
    , <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">SUM</span><span style="color: #808080;">&#40;</span>queriedPages<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">FLOAT</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">/</span> <span style="color: #FF00FF;">REPLACE</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">SUM</span><span style="color: #808080;">&#40;</span>totalPages<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: #FF0000;">'%DataUtil'</span>
<span style="color: #0000FF;">FROM</span> <span style="color: #808080;">&#40;</span>
    <span style="color: #0000FF;">SELECT</span> databaseName
        , tableName
        , indexID
        , <span style="color: #0000FF;">CASE</span> <span style="color: #008080;">-- If we have any activity at all on an index, count it as activity</span>
            <span style="color: #0000FF;">WHEN</span> activity <span style="color: #808080;">=</span> <span style="color: #000;">0</span> <span style="color: #0000FF;">THEN</span> <span style="color: #000;">0.0</span>
            <span style="color: #0000FF;">ELSE</span> totalPages
          <span style="color: #0000FF;">END</span> <span style="color: #0000FF;">AS</span> queriedPages
        , totalPages
    <span style="color: #0000FF;">FROM</span> #Results
    <span style="color: #0000FF;">WHERE</span> databaseName <span style="color: #808080;">NOT</span> <span style="color: #808080;">IN</span> <span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'master'</span>, <span style="color: #FF0000;">'tempdb'</span>, <span style="color: #FF0000;">'msdb'</span>, <span style="color: #FF0000;">'model'</span><span style="color: #808080;">&#41;</span>
<span style="color: #808080;">&#41;</span> x
<span style="color: #0000FF;">GROUP</span> <span style="color: #0000FF;">BY</span> databaseName
<span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> databaseName;
&nbsp;
<span style="color: #008080;">/* Retrieve % content utilization, which is performed at the table level */</span>
<span style="color: #0000FF;">SELECT</span> databaseName
    , <span style="color: #FF00FF;">SUM</span><span style="color: #808080;">&#40;</span>queriedPages<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> TotalQueriedPages
    , <span style="color: #FF00FF;">SUM</span><span style="color: #808080;">&#40;</span>totalPages<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> TotalPages
    , <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">SUM</span><span style="color: #808080;">&#40;</span>queriedPages<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">FLOAT</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">/</span> <span style="color: #FF00FF;">REPLACE</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">SUM</span><span style="color: #808080;">&#40;</span>totalPages<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: #FF0000;">'%ContentUtil'</span>
<span style="color: #0000FF;">FROM</span> <span style="color: #808080;">&#40;</span>
    <span style="color: #0000FF;">SELECT</span> databaseName
        , tableName
        , <span style="color: #FF00FF;">MAX</span><span style="color: #808080;">&#40;</span>records<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> records
        , <span style="color: #0000FF;">CASE</span> <span style="color: #0000FF;">WHEN</span> <span style="color: #FF00FF;">SUM</span><span style="color: #808080;">&#40;</span>activity<span style="color: #808080;">&#41;</span> <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span> <span style="color: #0000FF;">THEN</span> <span style="color: #FF00FF;">SUM</span><span style="color: #808080;">&#40;</span>totalPages<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">ELSE</span> <span style="color: #000;">0</span> <span style="color: #0000FF;">END</span> <span style="color: #0000FF;">AS</span> queriedPages
        , <span style="color: #FF00FF;">SUM</span><span style="color: #808080;">&#40;</span>totalPages<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> totalPages
    <span style="color: #0000FF;">FROM</span> #Results
    <span style="color: #0000FF;">WHERE</span> databaseName <span style="color: #808080;">NOT</span> <span style="color: #808080;">IN</span> <span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'master'</span>, <span style="color: #FF0000;">'tempdb'</span>, <span style="color: #FF0000;">'msdb'</span>, <span style="color: #FF0000;">'model'</span><span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">GROUP</span> <span style="color: #0000FF;">BY</span> databaseName
        , tableName
<span style="color: #808080;">&#41;</span> x
<span style="color: #0000FF;">GROUP</span> <span style="color: #0000FF;">BY</span> databaseName
<span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> databaseName;</pre></div></div>

<p>Results:</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">databaseName               TotalQueriedPages   TotalPages           %DataUtil
-------------------------- ------------------- -------------------- ----------------------
Database1 		   127618701           130607247            0.969619893356378
Database2 		   567188              1614958              0.351209133612143
Database3 		   34269036            34579469             0.991022620966216
Database4 		   137970594           170733391            0.803399928206158
Database5 		   74632930            101543575            0.66909214627557
Database6 		   55809933            72884205             0.765734157938039
Database7 		   560810026           620609815            0.902175272517656
&nbsp;
databaseName               TotalQueriedPages   TotalPages           %ContentUtil
-------------------------- ------------------- -------------------- ----------------------
Database1 		   127763715           130607247            0.970721679051682
Database2 		   571125              1614958              0.353646967908763
Database3 		   34269036            34579469             0.991022620966216
Database4 		   137970921           170733391            0.803399928206158
Database5 		   96144726            101543575            0.861947682777784
Database6 		   72269666            72884205             0.991568146820268
Database7 		   620525938           620609815            0.998240279711804</pre></div></div>

<p>The first result set examines the utilization of indexes, and the second result set examines the utilization of data at the content (table) level.  For example, if we look at Database6, we&#8217;ll see that we are only utilizing 77% of our indexes, but we&#8217;re looking at 99% of our table data.  So this is a good indicator that we have some unused indexes to clean up in that database.  </p>
<p>Know a better way to answer this question using SQL Server DMV&#8217;s?  Please leave me a comment so I can learn from your experience.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>In unrelated news, this may be my last blog post for a little while.  I&#8217;m due with my second child a week from today and expect all of my free time to be consumed by him for a little while.  That and, quite frankly, I do not trust myself near a computer, especially a database, in such a sleep-deprived state.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2011/10/how-to-estimate-data-utilization/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Index Defrag Script, v4.1</title>
		<link>http://sqlfool.com/2011/06/index-defrag-script-v4-1/</link>
		<comments>http://sqlfool.com/2011/06/index-defrag-script-v4-1/#comments</comments>
		<pubDate>Thu, 16 Jun 2011 18:44:11 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[T-SQL Scripts]]></category>
		<category><![CDATA[defrag]]></category>
		<category><![CDATA[defragment]]></category>
		<category><![CDATA[indexes]]></category>
		<category><![CDATA[partitioning]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[TSQL]]></category>
		<category><![CDATA[tuning]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1544</guid>
		<description><![CDATA[It&#8217;s been quite some time since my last index defrag script update. A big part of the reason for that is because I wanted to implement many of the suggestions I&#8217;ve received, but I just haven&#8217;t had the time. I still have those changes planned, but I&#8217;m not sure quite when I&#8217;ll get to it. [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been quite some time since my last index defrag script update.  A big part of the reason for that is because I wanted to implement many of the suggestions I&#8217;ve received, but I just haven&#8217;t had the time.  I still have those changes planned, but I&#8217;m not sure quite when I&#8217;ll get to it.  Rather than continue to wait for a major release, I&#8217;m releasing a small update to my defrag that will take care of the most common complaints I receive.  </p>
<p><strong>Change Log:</strong></p>
<ul>
<li>Bug fix for databases containing spaces or special characters</li>
<li>Support for case-sensitive databases</li>
<li>Re-executable CREATE script (for those who want to re-run the whole script)</li>
<li>Comma-delimited list of databases is now supported for the @database parameter</li>
</ul>
<p><strong>Feature List:</strong></p>
<ul>
<li>Defrag a single database, a list of databases, or all databases (@database)</li>
<li>Time Limitations: stop defragging after the specified amount of time has elapsed (@timeLimit).  Please note, it will not kill a defrag that is currently in process, even if it exceeds the threshold.</li>
<li>Optional stop-and-resume functionality: pick up where your defrag last left off without having to rescan sys.dm_db_index_physical_stats. (@forceRescan) </li>
<li>Defrag scheduling: choose which days to defrag certain indexes, or exclude certain indexes altogether, by using the dbo.dba_indexDefragExclusion table.</li>
<li>Defrag priority: choose whether to defrag indexes in ascending or descending order by range_scan_count (default), fragmentation, or page_count.</li>
<li>Current partition exclusion: choose whether or not to exclude the right-most populated partition from the defrag process, common for sliding-window tables (@excludeMaxPartition)</li>
<li>Commands-only mode: Choose to just log the current defrag status and print the defrag commands, rather than executing them, by using @executeSQL.</li>
<li>&#8230; and tons more!  Please read the parameter list and notes section for details of all the options available.</li>
</ul>
<p><strong>FAQ:</strong></p>
<p>I often receive the same questions about this script, so allow me to answer them here:</p>
<p><em>&#8220;I keep running the script, but my index is still fragmented. Why?&#8221;</em><br />
This is most likely a very small index. Here&#8217;s what Microsoft has to say:</p>
<blockquote><p>&#8220;In general, fragmentation on small indexes is often not controllable. The pages of small indexes are stored on mixed extents. Mixed extents are shared by up to eight objects, so the fragmentation in a small index might not be reduced after reorganizing or rebuilding the index. For more information about mixed extents, see Understanding Pages and Extents.&#8221; </p></blockquote>
<p><em>&#8220;What database should I create it in?&#8221; or &#8220;Can I create this in the MASTER database?&#8221;</em><br />
It&#8217;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>&#8220;Can I run this againt a SharePoint database?&#8221;</em><br />
Yes, you can.  </p>
<p><em>&#8220;What are the minimum requirements to run this script?&#8221; or &#8220;Will this run on SQL Server 2000 instances?&#8221;</em><br />
You need to be on SQL Server 2005 SP2 or higher.</p>
<p>Special thanks to <a href="http://twitter.com/SQL_ME_RICH" target="_blank">Richard Yanger</a> for his assistance with beta testing.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>You can download a text file of this script here:  <a href="http://sqlfool.com/wp-content/uploads/2011/06/dba_indexDefrag_sp_v41.txt" target="_blank">dba_indexDefrag_sp_v41</a></p>

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

]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2011/06/index-defrag-script-v4-1/feed/</wfw:commentRss>
		<slash:comments>65</slash:comments>
		</item>
		<item>
		<title>T-SQL Script for Estimating Compression Savings</title>
		<link>http://sqlfool.com/2011/06/estimate-compression-savings/</link>
		<comments>http://sqlfool.com/2011/06/estimate-compression-savings/#comments</comments>
		<pubDate>Fri, 10 Jun 2011 14:51:40 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[SQL Tips]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[T-SQL Scripts]]></category>
		<category><![CDATA[2008]]></category>
		<category><![CDATA[compression]]></category>
		<category><![CDATA[partitioning]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[TSQL]]></category>
		<category><![CDATA[tuning]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1539</guid>
		<description><![CDATA[A couple of weeks ago, I was working on a Microsoft PDW proof-of-concept (POC) and had to measure compression ratios. In order to do this, I fired up SSMS and wrote a little script. The script will iterate through all tables in a database and run the sp_estimate_data_compression_savings stored procedure. This will only work in [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of weeks ago, I was working on a <a href="http://www.microsoft.com/sqlserver/en/us/editions/data-warehouse.aspx" target="_blank">Microsoft PDW</a> proof-of-concept (POC) and had to measure compression ratios.  In order to do this, I fired up SSMS and wrote a little script.  The script will iterate through all tables in a database and run the <a href="http://msdn.microsoft.com/en-us/library/cc280574.aspx" target="_blank">sp_estimate_data_compression_savings</a> stored procedure.  <strong>This will only work in SQL Server 2008+ versions running Enterprise edition</strong>.</p>
<p>If you&#8217;re not familiar with this stored procedure, it basically will tell you what effect PAGE or ROW compression will have on your table/index/partition, etc.  There are pro&#8217;s and con&#8217;s with compression.  What I&#8217;ve tended to see is that compression has very positive results on space, IO, and query duration, with a negative impact on CPU and write speed.  Like most things, it&#8217;s a trade-off and the results will vary by environment, so I recommend you do some testing before you apply compression to all tables.  I tend to use compression mostly for my historical tables and partitions and leave my recent data uncompressed.  And, back to the script, I use this stored procedure to estimate the impact of compression and to determine whether to use PAGE or ROW compression.  PAGE is a higher level of compression, which means it&#8217;s also more expensive in terms of CPU, so if the difference between the two results is negligible, I&#8217;m more apt to just use ROW compression.  </p>
<p>Now that my impromptu compression discussion is done, let&#8217;s get to the actual script.  One final word of caution, however. <strong>This is an IO intensive process</strong>, so you may want to run it after peak business hours.</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><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> @printOnly  <span style="color: #0000FF;">BIT</span> <span style="color: #808080;">=</span> <span style="color: #000;">0</span> <span style="color: #008080;">-- change to 1 if you don't want to execute, just print commands</span>
    , @tableName    <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">256</span><span style="color: #808080;">&#41;</span>
    , @schemaName   <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">100</span><span style="color: #808080;">&#41;</span>
    , @sqlStatement <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">1000</span><span style="color: #808080;">&#41;</span>
    , @tableCount   <span style="color: #0000FF;">INT</span>
    , @statusMsg    <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">1000</span><span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">IF</span> <span style="color: #808080;">EXISTS</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">*</span> <span style="color: #0000FF;">FROM</span> tempdb.<span style="color: #202020;">sys</span>.<span style="color: #202020;">tables</span> <span style="color: #0000FF;">WHERE</span> name <span style="color: #808080;">LIKE</span> <span style="color: #FF0000;">'%#tables%'</span><span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">TABLE</span> #tables; 
&nbsp;
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> #tables
<span style="color: #808080;">&#40;</span>
      database_name     sysname
    , schemaName        sysname <span style="color: #808080;">NULL</span>
    , tableName         sysname <span style="color: #808080;">NULL</span>
    , processed         <span style="color: #0000FF;">bit</span>
<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">IF</span> <span style="color: #808080;">EXISTS</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">*</span> <span style="color: #0000FF;">FROM</span> tempdb.<span style="color: #202020;">sys</span>.<span style="color: #202020;">tables</span> <span style="color: #0000FF;">WHERE</span> name <span style="color: #808080;">LIKE</span> <span style="color: #FF0000;">'%#compression%'</span><span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">TABLE</span> #compressionResults;
&nbsp;
<span style="color: #0000FF;">IF</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">EXISTS</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">*</span> <span style="color: #0000FF;">FROM</span> tempdb.<span style="color: #202020;">sys</span>.<span style="color: #202020;">tables</span> <span style="color: #0000FF;">WHERE</span> name <span style="color: #808080;">LIKE</span> <span style="color: #FF0000;">'%#compression%'</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">BEGIN</span> 
&nbsp;
    <span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> #compressionResults
    <span style="color: #808080;">&#40;</span>
          objectName                    <span style="color: #0000FF;">varchar</span><span style="color: #808080;">&#40;</span><span style="color: #000;">100</span><span style="color: #808080;">&#41;</span>
        , schemaName                    <span style="color: #0000FF;">varchar</span><span style="color: #808080;">&#40;</span><span style="color: #000;">50</span><span style="color: #808080;">&#41;</span>
        , index_id                      <span style="color: #0000FF;">int</span>
        , partition_number              <span style="color: #0000FF;">int</span>
        , size_current_compression      <span style="color: #0000FF;">bigint</span>
        , size_requested_compression    <span style="color: #0000FF;">bigint</span>
        , sample_current_compression    <span style="color: #0000FF;">bigint</span>
        , sample_requested_compression  <span style="color: #0000FF;">bigint</span>
    <span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">END</span>;
&nbsp;
<span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> #tables
<span style="color: #0000FF;">SELECT</span> <span style="color: #FF00FF;">DB_NAME</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>
    , SCHEMA_NAME<span style="color: #808080;">&#40;</span><span style="color: #808080;">&#91;</span>schema_id<span style="color: #808080;">&#93;</span><span style="color: #808080;">&#41;</span>
    , name
    , <span style="color: #000;">0</span> <span style="color: #008080;">-- unprocessed</span>
<span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">tables</span>;
&nbsp;
<span style="color: #0000FF;">SELECT</span> @tableCount <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> #tables;
&nbsp;
<span style="color: #0000FF;">WHILE</span> <span style="color: #808080;">EXISTS</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">*</span> <span style="color: #0000FF;">FROM</span> #tables <span style="color: #0000FF;">WHERE</span> processed <span style="color: #808080;">=</span> <span style="color: #000;">0</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">BEGIN</span>
&nbsp;
    <span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">TOP</span> <span style="color: #000;">1</span> @tableName <span style="color: #808080;">=</span> tableName
        , @schemaName <span style="color: #808080;">=</span> schemaName
    <span style="color: #0000FF;">FROM</span> #tables <span style="color: #0000FF;">WHERE</span> processed <span style="color: #808080;">=</span> <span style="color: #000;">0</span>;
&nbsp;
    <span style="color: #0000FF;">SELECT</span> @statusMsg <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Working on '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#40;</span>@tableCount <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: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #000;">1</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;">' of '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@tableCount <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;">FROM</span> #tables
    <span style="color: #0000FF;">WHERE</span> processed <span style="color: #808080;">=</span> <span style="color: #000;">0</span>;
&nbsp;
    <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span>@statusMsg, <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> @sqlStatement <span style="color: #808080;">=</span> <span style="color: #FF0000;">'EXECUTE sp_estimate_data_compression_savings '</span><span style="color: #FF0000;">''</span> 
                        <span style="color: #808080;">+</span> @schemaName <span style="color: #808080;">+</span> <span style="color: #FF0000;">''</span><span style="color: #FF0000;">', '</span><span style="color: #FF0000;">''</span> <span style="color: #808080;">+</span> @tableName <span style="color: #808080;">+</span> <span style="color: #FF0000;">''</span><span style="color: #FF0000;">', NULL, NULL, '</span><span style="color: #FF0000;">'PAGE'</span><span style="color: #FF0000;">';'</span> <span style="color: #008080;">-- ROW, PAGE, or NONE</span>
&nbsp;
    <span style="color: #0000FF;">IF</span> @printOnly <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
    <span style="color: #0000FF;">BEGIN</span> 
&nbsp;
        <span style="color: #0000FF;">SELECT</span> @sqlStatement;
&nbsp;
    <span style="color: #0000FF;">END</span>
    <span style="color: #0000FF;">ELSE</span>
    <span style="color: #0000FF;">BEGIN</span>
&nbsp;
        <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> #compressionResults
        <span style="color: #0000FF;">EXECUTE</span> <span style="color: #AF0000;">sp_executesql</span> @sqlStatement;
&nbsp;
    <span style="color: #0000FF;">END</span>;
&nbsp;
    <span style="color: #0000FF;">UPDATE</span> #tables
    <span style="color: #0000FF;">SET</span> processed <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
    <span style="color: #0000FF;">WHERE</span> tableName <span style="color: #808080;">=</span> @tableName
        <span style="color: #808080;">AND</span> schemaName <span style="color: #808080;">=</span> @schemaName;
&nbsp;
<span style="color: #0000FF;">END</span>;
&nbsp;
<span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">*</span> 
<span style="color: #0000FF;">FROM</span> #compressionResults;</pre></div></div>

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

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

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

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

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


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

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

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


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

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

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


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

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

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


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

<p>Okay, SalesOrderDetailID 75000 takes us back to 12/27/2007.  That&#8217;s close enough to 1/1/2008 for my purposes.  Of course, depending on the size of the table, in real life it may make sense to try to get closer to the value you&#8217;re looking for.  But for now, this will do.  And because we&#8217;re looking for data through the &#8220;current date&#8221; (7/31/2008 in the AdventureWorks2008R2 database), we already know our outer limit is 121317.</p>
<p>Now let&#8217;s take these ranges and create a filtered index that will cover our query:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">Create</span> <span style="color: #0000FF;">Nonclustered</span> <span style="color: #0000FF;">Index</span> IX_SalesOrderDetail_filtered
    <span style="color: #0000FF;">On</span> Sales.<span style="color: #202020;">SalesOrderDetail</span><span style="color: #808080;">&#40;</span>ModifiedDate, ProductID<span style="color: #808080;">&#41;</span>
    Include <span style="color: #808080;">&#40;</span>SalesOrderID<span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">Where</span> SalesOrderDetailID <span style="color: #808080;">&gt;=</span> <span style="color: #000;">75000</span>
      And SalesOrderDetailID <span style="color: #808080;">&lt;</span>  <span style="color: #000;">121317</span>;</pre></div></div>

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

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

<p>That&#8217;s all there is to it.  Using this method, I was able to complete my ad hoc request in 40 seconds: 10 seconds to create the filtered index and 30 seconds to actually execute the ad hoc.  Of course, it also took a couple of minutes to write the query, look at existing indexes, and search for the correct identity values.  All in all, from the time I received the request to the time I send the e-mail was about 5 minutes.  All because of disposable filtered indexes.  How&#8217;s that for some SQL #awesomesauce?  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2010/12/disposable-indexes/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Yet Another PASS Summit Recap &amp; Thoughts on PDW</title>
		<link>http://sqlfool.com/2010/11/yet-another-pass-summit-recap/</link>
		<comments>http://sqlfool.com/2010/11/yet-another-pass-summit-recap/#comments</comments>
		<pubDate>Mon, 22 Nov 2010 15:43:10 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Business Intelligence]]></category>
		<category><![CDATA[Miscellaneous]]></category>
		<category><![CDATA[PASS]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[2008]]></category>
		<category><![CDATA[bi]]></category>
		<category><![CDATA[data warehouse]]></category>
		<category><![CDATA[parallel data warehouse]]></category>
		<category><![CDATA[pdw]]></category>
		<category><![CDATA[Summit]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1427</guid>
		<description><![CDATA[The SQL blogosphere has been lit up with PASS Summit recaps. I debated about whether or not to write my own post, until I remembered that this blog serves as a mini-journal for me too. I have a notoriously poor memory&#8211;my husband likes to say that my CPU and memory are good, but I must [...]]]></description>
			<content:encoded><![CDATA[<p>The SQL blogosphere has been <a href="http://www.sqlmusings.com/2010/11/10/pass-summit-day-1-keynote-mcm-sqlpasstv-servicebroker-bi-power-hour-mdx-who-dunnit/" target="_blank">lit</a> <a href="http://cwebbbi.wordpress.com/2010/11/10/pass-summit-2010-day-1/" target="_blank">up</a> <a href="http://www.sqlservercentral.com/blogs/kathi_kellenberger/archive/2010/11/15/pass-report-1-why-you-should-have-been-there.aspx" target="_blank">with</a> <a href="http://blogs.lessthandot.com/index.php/ITProfessionals/ProfessionalDevelopment/sql-pass-2010" target="_blank">PASS</a> <a href="http://www.sqlservercentral.com/blogs/stratesql/archive/2010/11/15/david-dewitt-at-the-pass-summit.aspx" target="_blank">Summit</a> <a href="http://www.sqlservercentral.com/blogs/sqlchicken/archive/2010/11/15/pass-summit-magic_3A00_-the-turn.aspx" target="_blank">recaps</a>.</p>
<p>I debated about whether or not to write my own post, until I remembered that this blog serves as a mini-journal for me too.  I have a notoriously poor memory&#8211;my husband likes to say that my CPU and memory are good, but I must have an unusual clustering strategy&#8211;so maybe this blog post will be a good pointer for me when I start prepping for next year&#8217;s Summit.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>This was definitely the best PASS Summit conference ever.  While there will always be opportunities to do things better&#8211;improvement is a never-ending process&#8211;it was clear that the organizers of this event listened to the feedback they had received the previous year.  One of the best changes?  Backpacks.  These were very useful, as evidenced by their presence everywhere.  Nice job, organizers!</p>
<p>My absolute favorite thing about Summit is the chance to meet and reconnect with so many amazing SQL folks.  There were entirely too many people to list out, but some highlights include meeting <a href="http://twitter.com/crysmanson">Crys Manson</a>, <a href="http://twitter.com/sqlchicken">Jorge Segarra</a>, and <a href="http://twitter.com/datachick">Karen Lopez</a> for the first time.  I also had a chance encounter with <a href="http://ola.hallengren.com/" target="_blank">Ola Hallengren</a> in the Sheraton elevator.  Apparently we were only staying a few rooms apart this year.  We ended up having a couple of really great discussions about index fragmentation, the differences between our scripts, and things we&#8217;d like to see changed in future releases of SQL Server.  </p>
<p>I had the opportunity to sit on the panel at the WIT luncheon.  All of the women on the panel were amazing, and I was honored just to be sitting at the same table as them.  I was especially pleased to meet Nora Denzel, a Senior Vice President at Intuit.  Intelligent, confident, and witty, she is a great role model for young technical women, myself included.  I can only hope that some of her gumption rubbed off on me due to our close proximity.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />   After the event, I was pleasantly surprised by how many folks&#8211;men and women both&#8211;came up to me to tell me how much they enjoyed it.  Thanks to the WIT VC for organizing another great event!</p>
<p>The lightning talk sessions were a new feature this year, and I think I like it.  The format of the lightning session is 7 speakers presenting on a topic for 5 quick minutes.  Watching these sessions is kind of like skipping right to the center of a tootsie pop: all content and no fluff.  The standout lightning talk presentation for me was <a href="http://sqlblog.com/blogs/adam_machanic/" target="_blank">Adam Machanic&#8217;s</a>.  It was beautifully rehearsed and choreographed.  Nice job, Adam!</p>
<p>Another of the many highlights of the week was meeting the Microsoft execs.  In addition to meeting Ted Kummert, Mark Souza, and Donald Farmer&#8211;all very nice gentlemen&#8211;I had the opportunity to speak at length with Jose Blakely about Parallel Data Warehouse (PDW).  PDW, formerly codenamed Madison, was officially launched at Summit.  Jose was kind enough to explain the PDW architecture, both where it came from and the vision for where it&#8217;s going.  I&#8217;d attempt to regurgitate it here, but I think the probability of me misquoting would be high.  </p>
<p>Suffice it to say, this technology has me excited.  Why?  Quite frankly, I think PDW will do for data warehousing what SQL Server did for databases, and what Analysis Services did for BI: make it affordable.  With a compelling cost-per-terabyte, an attractive scale-out approach, and an entry point at under $1 million, we&#8217;ll see more small-to-midsized companies implementing data warehousing and business intelligence.  This is good news for those of us looking for an affordable data warehouse solution and for those of us who make our living with SQL Server.  And for those of you who might suggest that few companies need a datawarehouse that can support multi-terabyte data, I&#8217;d like to point out that just 3 or 4 years ago, 100 GB was considered a lot of data.  </p>
<p>I spent most of my week digging into the PDW architecture.  It&#8217;s not all roses&#8211;it&#8217;s a first release and, as such, is immature compared to the much older and more established data warehouse systems&#8211;but again, it has a lot going for it, not least of all it&#8217;s easy integration within a SQL Server environment and the relatively low cost.  We&#8217;re currently investigating this as a possible data warehouse solution for our business intelligence environment, so expect to see more from me about PDW as I learn more about it.</p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2010/11/yet-another-pass-summit-recap/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Metadata for Table Valued Parameters</title>
		<link>http://sqlfool.com/2010/10/metadata-for-table-valued-parameters/</link>
		<comments>http://sqlfool.com/2010/10/metadata-for-table-valued-parameters/#comments</comments>
		<pubDate>Thu, 28 Oct 2010 15:10:27 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Miscellaneous]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[SQL Tips]]></category>
		<category><![CDATA[Syndication]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1390</guid>
		<description><![CDATA[Table-valued parameters (TVP) are a great feature that was new in SQL Server 2008 that allow you to insert a dataset into a table. Previously, the most common way of doing this was by passing and parsing XML. As I&#8217;ve previously posted, TVP&#8217;s perform an astounding 94% faster than singleton inserts and 75% faster than [...]]]></description>
			<content:encoded><![CDATA[<p>Table-valued parameters (TVP) are a great feature that was new in SQL Server 2008 that allow you to insert a dataset into a table.  Previously, the most common way of doing this was by passing and parsing XML.  As I&#8217;ve <a href="http://sqlfool.com/2008/11/performance-comparison-of-singleton-xml-and-tvp-inserts/" target="_blank">previously posted, </a> TVP&#8217;s perform an astounding 94% faster than singleton inserts and 75% faster than XML inserts.  But for some reason, TVP&#8217;s still aren&#8217;t widely used and understood.  In this post, I&#8217;ll walk you through how to use these and how to query the metadata for TVP&#8217;s.  </p>
<p>I&#8217;ve <a href="http://sqlfool.com/2008/11/one-to-many-inserts-with-table-valued-parameters/" target="_blank">previously posted about what TVP&#8217;s are</a> and how to use them.  But in honor of <a href="http://sears.com/zombies" target="_blank">Halloween this week</a>, I&#8217;ve updated my demo script:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/* Create some tables to work with */</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;">DATE</span>                Not Null
    , customer      <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">20</span><span style="color: #808080;">&#41;</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<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> dbo.<span style="color: #202020;">orderDetails</span>
<span style="color: #808080;">&#40;</span>
      orderDetail_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
    , order_id          <span style="color: #0000FF;">INT</span>                 Not Null
    , lineItem          <span style="color: #0000FF;">INT</span>                 Not Null
    , product           <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">20</span><span style="color: #808080;">&#41;</span>         Not Null
&nbsp;
    <span style="color: #0000FF;">CONSTRAINT</span> PK_orderDetails
        <span style="color: #0000FF;">PRIMARY</span> <span style="color: #0000FF;">KEY</span> <span style="color: #0000FF;">CLUSTERED</span><span style="color: #808080;">&#40;</span>orderDetail_id<span style="color: #808080;">&#41;</span>
&nbsp;
    <span style="color: #0000FF;">CONSTRAINT</span> FK_orderDetails_orderID
        <span style="color: #0000FF;">FOREIGN</span> <span style="color: #0000FF;">KEY</span><span style="color: #808080;">&#40;</span>order_id<span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">REFERENCES</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: #808080;">&#41;</span>;
&nbsp;
&nbsp;
<span style="color: #008080;">/* Create our new table types */</span>
<span style="color: #0000FF;">CREATE</span> TYPE dbo.<span style="color: #202020;">orderTable</span> <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">TABLE</span> 
<span style="color: #808080;">&#40;</span> 
      orderDate     <span style="color: #0000FF;">DATE</span>
    , customer      <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">20</span><span style="color: #808080;">&#41;</span>
<span style="color: #808080;">&#41;</span>;
GO
&nbsp;
<span style="color: #0000FF;">CREATE</span> TYPE dbo.<span style="color: #202020;">orderDetailTable</span> <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">TABLE</span> 
<span style="color: #808080;">&#40;</span> 
      lineItem      <span style="color: #0000FF;">INT</span>
    , product       <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">20</span><span style="color: #808080;">&#41;</span>
<span style="color: #808080;">&#41;</span>;
GO
&nbsp;
&nbsp;
<span style="color: #008080;">/* Create a new procedure using a table-valued parameter */</span>
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">PROCEDURE</span> dbo.<span style="color: #202020;">insert_orderTVP_sp</span>
      @myOrderTable orderTable READONLY
    , @myOrderDetailTable orderDetailTable READONLY
<span style="color: #0000FF;">AS</span>
<span style="color: #0000FF;">BEGIN</span>
&nbsp;
    <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> @myOrderID <span style="color: #0000FF;">INT</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> orderDate
        , customer
    <span style="color: #0000FF;">FROM</span> @myOrderTable;
&nbsp;
    <span style="color: #0000FF;">SET</span> @myOrderID <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: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> dbo.<span style="color: #202020;">orderDetails</span>
    <span style="color: #0000FF;">SELECT</span> @myOrderID
        , lineItem
        , product
    <span style="color: #0000FF;">FROM</span> @myOrderDetailTable;
&nbsp;
    <span style="color: #0000FF;">SET</span> <span style="color: #0000FF;">NOCOUNT</span> <span style="color: #0000FF;">OFF</span>;
&nbsp;
<span style="color: #0000FF;">END</span>
GO
&nbsp;
&nbsp;
<span style="color: #008080;">/* Call our new proc! */</span>
<span style="color: #0000FF;">DECLARE</span> @myTableHeaderData <span style="color: #0000FF;">AS</span> orderTable
    , @myTableDetailData <span style="color: #0000FF;">AS</span> orderDetailTable;
&nbsp;
<span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> @myTableHeaderData
<span style="color: #808080;">&#40;</span>orderDate, customer<span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">VALUES</span> <span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>, <span style="color: #FF0000;">'Zombie'</span><span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> @myTableDetailData
<span style="color: #808080;">&#40;</span>lineItem, product<span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">SELECT</span> <span style="color: #000;">10</span>, <span style="color: #FF0000;">'Brains'</span> <span style="color: #0000FF;">UNION</span> <span style="color: #808080;">ALL</span>
<span style="color: #0000FF;">SELECT</span> <span style="color: #000;">20</span>, <span style="color: #FF0000;">'More Brains'</span>;
&nbsp;
<span style="color: #0000FF;">EXECUTE</span> dbo.<span style="color: #202020;">insert_orderTVP_sp</span> 
      @myTableHeaderData
    , @myTableDetailData;
&nbsp;
<span style="color: #0000FF;">DELETE</span> <span style="color: #0000FF;">FROM</span> @myTableHeaderData;
<span style="color: #0000FF;">DELETE</span> <span style="color: #0000FF;">FROM</span> @myTableDetailData;
&nbsp;
<span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> @myTableHeaderData
<span style="color: #808080;">&#40;</span>orderDate, customer<span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">VALUES</span> <span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>, <span style="color: #FF0000;">'Vampire'</span><span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> @myTableDetailData
<span style="color: #808080;">&#40;</span>lineItem, product<span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">SELECT</span> <span style="color: #000;">10</span>, <span style="color: #FF0000;">'Blood Type O+'</span> <span style="color: #0000FF;">UNION</span> <span style="color: #808080;">ALL</span>
<span style="color: #0000FF;">SELECT</span> <span style="color: #000;">20</span>, <span style="color: #FF0000;">'Blood Type B-'</span> <span style="color: #0000FF;">UNION</span> <span style="color: #808080;">ALL</span>
<span style="color: #0000FF;">SELECT</span> <span style="color: #000;">30</span>, <span style="color: #FF0000;">'Blood Type AB+'</span> <span style="color: #0000FF;">UNION</span> <span style="color: #808080;">ALL</span>
<span style="color: #0000FF;">SELECT</span> <span style="color: #000;">40</span>, <span style="color: #FF0000;">'Blood Type A+'</span>;
&nbsp;
<span style="color: #0000FF;">EXECUTE</span> dbo.<span style="color: #202020;">insert_orderTVP_sp</span> 
      @myTableHeaderData
    , @myTableDetailData;
&nbsp;
&nbsp;
<span style="color: #008080;">/* Check our data */</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;">SELECT</span> <span style="color: #808080;">*</span> <span style="color: #0000FF;">FROM</span> dbo.<span style="color: #202020;">orderDetails</span>;</pre></div></div>

<p>Once you&#8217;ve run this, you should see the following data:</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">order_id    orderDate  customer
----------- ---------- --------------------
1           2010-10-28 Zombie
2           2010-10-28 Vampire
&nbsp;
(2 row(s) affected)
&nbsp;
orderDetail_id order_id    lineItem    product
-------------- ----------- ----------- --------------------
1              1           10          Brains
2              1           20          More Brains
3              2           10          Blood Type O+
4              2           20          Blood Type B-
5              2           30          Blood Type AB+
6              2           40          Blood Type A+
&nbsp;
(6 row(s) affected)</pre></div></div>

<p>Now that we&#8217;ve successfully created a couple of table types to support our TVP&#8217;s, how do we go back and find out which objects we&#8217;ve created?  You can query the sys.types catalog view to find out.  Just search for system_type_id 243, which identifies the record as a table type.</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/* Let's check out our new data types */</span>
<span style="color: #0000FF;">SELECT</span> name
    , system_type_id
    , is_table_type
<span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">types</span>
<span style="color: #0000FF;">WHERE</span> system_type_id <span style="color: #808080;">=</span> <span style="color: #000;">243</span>;
GO</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">name                 system_type_id is_table_type
-------------------- -------------- -------------
orderTable           243            1
orderDetailTable     243            1
&nbsp;
(2 row(s) affected)</pre></div></div>

<p>Even better yet, you can use the sys.table_types catalog view.  This gives us the same information as sys.types but also gives us the type_table_object_id, which we&#8217;ll need shortly.</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">SELECT</span> name
    , system_type_id
    , is_table_type
    , type_table_object_id
<span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">table_types</span>;</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">name                 system_type_id is_table_type type_table_object_id
-------------------- -------------- ------------- --------------------
orderTable           243            1             917578307
orderDetailTable     243            1             933578364
&nbsp;
(2 row(s) affected)</pre></div></div>

<p>What if you need to look up the table type definition?  You can do this using the type_table_object_id and joining to sys.columns.</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">SELECT</span> tt.<span style="color: #202020;">name</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'table_type_name'</span>
    , c.<span style="color: #202020;">name</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'column_name'</span>
    , t.<span style="color: #202020;">name</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'data_type'</span>
<span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">table_types</span> <span style="color: #0000FF;">AS</span> tt
<span style="color: #808080;">JOIN</span> sys.<span style="color: #202020;">columns</span> <span style="color: #0000FF;">AS</span> c
    <span style="color: #0000FF;">ON</span> tt.<span style="color: #202020;">type_table_object_id</span> <span style="color: #808080;">=</span> c.<span style="color: #FF00FF;">object_id</span>
<span style="color: #808080;">JOIN</span> sys.<span style="color: #202020;">types</span> <span style="color: #0000FF;">As</span> t
    <span style="color: #0000FF;">ON</span> c.<span style="color: #202020;">system_type_id</span> <span style="color: #808080;">=</span> t.<span style="color: #202020;">system_type_id</span>;</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">table_type_name      column_name     data_type
-------------------- --------------- ---------------
orderTable           orderDate       date
orderDetailTable     lineItem        int
orderTable           customer        varchar
orderDetailTable     product         varchar
&nbsp;
(4 row(s) affected)</pre></div></div>

<p>And last, but certainly not least, how do we see if any procs are currently using the table types?  SQL Server 2008 makes this easy for us with the sys.dm_sql_referencing_entities DMV.</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">SELECT</span> referencing_schema_name, referencing_entity_name, referencing_id
<span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">dm_sql_referencing_entities</span> <span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'dbo.orderTable'</span>, <span style="color: #FF0000;">'TYPE'</span><span style="color: #808080;">&#41;</span>;</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">referencing_schema_name referencing_entity_name referencing_id
----------------------- ----------------------- --------------
dbo                     insert_orderTVP_sp      949578421
&nbsp;
(1 row(s) affected)</pre></div></div>

<p>If you&#8217;re wondering how to implement SQL Server TVP&#8217;s in your .NET code, well&#8230; I can&#8217;t tell you how to do it, but I can point you to a place that can.  Stephen Forte has <a href="http://www.stephenforte.net/PermaLink,guid,07dfeb00-d0b0-47dd-9761-3b4c9f160277.aspx" target="_blank">a post that explains how easy it is to do</a>.</p>
<p>So now that you have a better understanding of how to work with TVP&#8217;s, why don&#8217;t you go implement one in your environment and see how for yourself just how awesome it is?  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Oh, and Happy Halloween!</p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2010/10/metadata-for-table-valued-parameters/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Index Interrogation for SQL Server 2008</title>
		<link>http://sqlfool.com/2010/06/index-interrogation-for-sql-server-2008/</link>
		<comments>http://sqlfool.com/2010/06/index-interrogation-for-sql-server-2008/#comments</comments>
		<pubDate>Fri, 04 Jun 2010 19:55:17 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Internals]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[T-SQL Scripts]]></category>
		<category><![CDATA[indexes]]></category>
		<category><![CDATA[partitioning]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[TSQL]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=1344</guid>
		<description><![CDATA[I had previously posted an index interrogation script for SQL Server 2005. I&#8217;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&#8217;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>Filtered Indexes Work-Around</title>
		<link>http://sqlfool.com/2010/02/filtered-indexes-work-around/</link>
		<comments>http://sqlfool.com/2010/02/filtered-indexes-work-around/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 16:00:14 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[SQL Tips]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[2008]]></category>
		<category><![CDATA[filtered indexes]]></category>
		<category><![CDATA[performance]]></category>

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

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">Create</span> <span style="color: #0000FF;">Table</span> dbo.<span style="color: #202020;">filteredIndexTest</span>
<span style="color: #808080;">&#40;</span>
      myID   <span style="color: #0000FF;">int</span> <span style="color: #0000FF;">Identity</span><span style="color: #808080;">&#40;</span><span style="color: #000;">1</span>,<span style="color: #000;">3</span><span style="color: #808080;">&#41;</span>
    , myDate <span style="color: #0000FF;">smalldatetime</span> 
    , myData <span style="color: #0000FF;">char</span><span style="color: #808080;">&#40;</span><span style="color: #000;">100</span><span style="color: #808080;">&#41;</span>
&nbsp;
    <span style="color: #0000FF;">Constraint</span> PK_filteredIndexTest
        <span style="color: #0000FF;">Primary</span> <span style="color: #0000FF;">Key</span> <span style="color: #0000FF;">Clustered</span><span style="color: #808080;">&#40;</span>myID<span style="color: #808080;">&#41;</span>
<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">Set</span> <span style="color: #0000FF;">NoCount</span> <span style="color: #0000FF;">On</span>;
<span style="color: #0000FF;">Declare</span> @<span style="color: #0000FF;">date</span> <span style="color: #0000FF;">smalldatetime</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'2010-01-01'</span>;
&nbsp;
<span style="color: #0000FF;">While</span> @<span style="color: #0000FF;">date</span> <span style="color: #808080;">&lt;</span> <span style="color: #FF0000;">'2010-02-01'</span>
<span style="color: #0000FF;">Begin</span>
&nbsp;
    <span style="color: #0000FF;">Insert</span> <span style="color: #0000FF;">Into</span> dbo.<span style="color: #202020;">filteredIndexTest</span>
    <span style="color: #808080;">&#40;</span>
          myDate
        , myData
    <span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">Select</span> @<span style="color: #0000FF;">date</span>
        , <span style="color: #FF0000;">'Date: '</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">Convert</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">varchar</span><span style="color: #808080;">&#40;</span><span style="color: #000;">20</span><span style="color: #808080;">&#41;</span>, @<span style="color: #0000FF;">date</span>, <span style="color: #000;">102</span><span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #0000FF;">Set</span> @<span style="color: #0000FF;">date</span> <span style="color: #808080;">=</span> <span style="color: #FF00FF;">DateAdd</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">minute</span>, <span style="color: #000;">1</span>, @<span style="color: #0000FF;">date</span><span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">End</span>;
&nbsp;
<span style="color: #0000FF;">Select</span> <span style="color: #FF00FF;">Count</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">*</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">From</span> dbo.<span style="color: #202020;">filteredIndexTest</span>;</pre></div></div>

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

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">Create</span> <span style="color: #0000FF;">NonClustered</span> <span style="color: #0000FF;">Index</span> IX_filteredIndexTest_1
    <span style="color: #0000FF;">On</span> dbo.<span style="color: #202020;">filteredIndexTest</span><span style="color: #808080;">&#40;</span>myDate<span style="color: #808080;">&#41;</span>
    Include <span style="color: #808080;">&#40;</span>myData<span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">Where</span> myDate <span style="color: #808080;">&gt;=</span> <span style="color: #FF0000;">'2010-01-27'</span>;
&nbsp;
<span style="color: #0000FF;">Select</span> <span style="color: #0000FF;">Distinct</span> myData
<span style="color: #0000FF;">From</span> dbo.<span style="color: #202020;">filteredIndexTest</span>
<span style="color: #0000FF;">Where</span> myDate <span style="color: #808080;">&gt;=</span> <span style="color: #FF0000;">'2010-01-28'</span>;</pre></div></div>

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

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">Declare</span> @myDate1 <span style="color: #0000FF;">smalldatetime</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'2010-01-28'</span>;
&nbsp;
<span style="color: #0000FF;">Select</span> <span style="color: #0000FF;">Distinct</span> myData
<span style="color: #0000FF;">From</span> dbo.<span style="color: #202020;">filteredIndexTest</span>
<span style="color: #0000FF;">Where</span> myDate <span style="color: #808080;">&gt;=</span> @myDate1;</pre></div></div>

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

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

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

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">Declare</span> @mySQL2 <span style="color: #0000FF;">nvarchar</span><span style="color: #808080;">&#40;</span><span style="color: #000;">2000</span><span style="color: #808080;">&#41;</span>
    , @myDate3 <span style="color: #0000FF;">smalldatetime</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'2010-01-28'</span>;
&nbsp;
<span style="color: #0000FF;">Set</span> @mySQL2 <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Select Distinct myData
              From dbo.filteredIndexTest
              Where myDate &gt;= '</span><span style="color: #FF0000;">''</span> <span style="color: #808080;">+</span> <span style="color: #0000FF;">Cast</span><span style="color: #808080;">&#40;</span>@myDate3 <span style="color: #0000FF;">As</span> <span style="color: #0000FF;">varchar</span><span style="color: #808080;">&#40;</span><span style="color: #000;">20</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">+</span> <span style="color: #FF0000;">''</span><span style="color: #FF0000;">''</span>;
&nbsp;
<span style="color: #0000FF;">Execute</span> <span style="color: #AF0000;">sp_executeSQL</span> @mySQL2;
&nbsp;
<span style="color: #008080;">-- Drop Table dbo.filteredIndexTest;</span></pre></div></div>

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

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

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

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

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

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

