<?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; 2008</title>
	<atom:link href="http://sqlfool.com/tag/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>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>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>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>Partitioning Tricks</title>
		<link>http://sqlfool.com/2009/10/partitioning-tricks/</link>
		<comments>http://sqlfool.com/2009/10/partitioning-tricks/#comments</comments>
		<pubDate>Fri, 09 Oct 2009 19:12:35 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Miscellaneous]]></category>
		<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[SQL Tips]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[2008]]></category>
		<category><![CDATA[compression]]></category>
		<category><![CDATA[partitioning]]></category>
		<category><![CDATA[performance]]></category>

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

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

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

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

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

		<guid isPermaLink="false">http://sqlfool.com/?p=1154</guid>
		<description><![CDATA[If you&#8217;ve been following my blog for a little while, you&#8217;ll know that I&#8217;m a fan of SQL Server internals. There&#8217;s a lot that can be learned or better understood by rolling up your sleeves and getting into the nitty-gritty of data pages (i.e. see my post on Overhead in Non-Unique Clustered Indexes). So imagine [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve been following my blog for a little while, you&#8217;ll know that I&#8217;m a fan of SQL Server internals.  There&#8217;s a lot that can be learned or better understood by rolling up your sleeves and getting into the nitty-gritty of data pages (i.e. see my post on <a href="http://sqlfool.com/2009/05/overhead-i-non-unique-clustered-indexes/" target="_blank">Overhead in Non-Unique Clustered Indexes</a>).  So imagine how happy I was when my co-worker Jeff shared an undocumented function with me today that retrieves the file number, page number, and slot number of a single record.  Very cool!  Well, at least to me.  So now let&#8217;s see how you can use it.</p>
<p>The fn_physLocCracker function can be called in the following way:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">Select</span> <span style="color: #0000FF;">Top</span> <span style="color: #000;">100</span> plc.<span style="color: #808080;">*</span>, soh.<span style="color: #202020;">SalesOrderID</span>
<span style="color: #0000FF;">From</span> Sales.<span style="color: #202020;">SalesOrderHeader</span> <span style="color: #0000FF;">As</span> soh
Cross Apply sys.<span style="color: #202020;">fn_physLocCracker</span> <span style="color: #808080;">&#40;</span><span style="color: #808080;">%%</span>physloc<span style="color: #808080;">%%</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">As</span> plc;</pre></div></div>

<p>Results (just a sample):</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">file_id     page_id     slot_id     SalesOrderID
----------- ----------- ----------- ------------
1           14032       0           43659
1           14032       1           43660
1           14032       2           43661
1           14032       3           43662
1           14032       4           43663</pre></div></div>

<p>If you look at the <a href="http://msdn.microsoft.com/en-us/library/ms176112.aspx" target="_blank">sp_helptext</a> for sys.fn_physLocCracker, %%physloc%% is apparently a virtual column that contains information on where the record is stored.  In fact, you can even append %%physloc%% to your column list if you want to see how the information is stored.  But for our purposes, we now have a file number, page number, and slot number.  What do we do with it?</p>
<p>Well, you can use the <a href="http://sqlfool.com/2009/05/page-internals-investigation-proc/" target="_blank">investigation proc I wrote</a> to retrieve the actual data page:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">Execute</span> dba_viewPageData_sp 
      @databaseName <span style="color: #808080;">=</span> <span style="color: #FF0000;">'AdventureWorks'</span>
    , @fileNumber <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
    , @pageNumber <span style="color: #808080;">=</span> <span style="color: #000;">14032</span>;</pre></div></div>

<p>Results (just a sample):</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">Slot 0 Column 1 Offset 0x4 Length 4 Length (physical) 4
&nbsp;
SalesOrderID = 43659                 
&nbsp;
Slot 0 Column 2 Offset 0x8 Length 1 Length (physical) 1
&nbsp;
RevisionNumber = 1                   
&nbsp;
Slot 0 Column 3 Offset 0x9 Length 8 Length (physical) 8
&nbsp;
OrderDate = 2001-07-01 00:00:00.000  
&nbsp;
Slot 0 Column 4 Offset 0x11 Length 8 Length (physical) 8
&nbsp;
DueDate = 2001-07-13 00:00:00.000</pre></div></div>

<p>Neat, huh?  So why would you use it to look up the data page and file number when you can just pass the table name and index name to my proc and retrieve data pages?  Well, my investigation proc will retrieve data pages for any index type &#8212; the fn_physLocCracker function will only retrieve data for the clustered index &#8212; but it will not retrieve the data page for a specific record.  So just something to be aware of.</p>
<p>That&#8217;s all for now.  Back to the #24HoursOfPASS!  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/09/undocumented-function-in-sql-2008/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>BOL 2008 Update Released</title>
		<link>http://sqlfool.com/2009/05/bol-2008update-released/</link>
		<comments>http://sqlfool.com/2009/05/bol-2008update-released/#comments</comments>
		<pubDate>Fri, 22 May 2009 21:39:22 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[2008]]></category>
		<category><![CDATA[BOL]]></category>
		<category><![CDATA[books online]]></category>
		<category><![CDATA[SSMS]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=975</guid>
		<description><![CDATA[If you haven&#8217;t heard, Microsoft released an update to Books Online for SQL Server 2008 yesterday. You can find the download here: http://www.microsoft.com/downloads/details.aspx?FamilyID=765433f7-0983-4d7a-b628-0a98145bcb97&#038;displaylang=en]]></description>
			<content:encoded><![CDATA[<p>If you haven&#8217;t heard, Microsoft released an update to Books Online for SQL Server 2008 yesterday.  You can find the download here:</p>
<p><a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=765433f7-0983-4d7a-b628-0a98145bcb97&#038;displaylang=en" target="_blank">http://www.microsoft.com/downloads/details.aspx?FamilyID=765433f7-0983-4d7a-b628-0a98145bcb97&#038;displaylang=en</a></p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/05/bol-2008update-released/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Filtered Indexes: What You Need To Know</title>
		<link>http://sqlfool.com/2009/04/filtered-indexes-what-you-need-to-know/</link>
		<comments>http://sqlfool.com/2009/04/filtered-indexes-what-you-need-to-know/#comments</comments>
		<pubDate>Mon, 20 Apr 2009 17:32:56 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[Syndication]]></category>
		<category><![CDATA[2008]]></category>
		<category><![CDATA[filtered indexes]]></category>
		<category><![CDATA[indexes]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=831</guid>
		<description><![CDATA[Filtered indexes are probably my favorite feature in 2008. That&#8217;s saying a lot, since there are so many great new features to choose from. In this post, I want to explore a little about how filtered indexes work, how they can be applied, and some of the &#8220;gotchas&#8221; to be aware of. First, for those [...]]]></description>
			<content:encoded><![CDATA[<p>Filtered indexes are probably my favorite feature in 2008.  That&#8217;s saying a lot, since there are so many great new features to choose from.  In this post, I want to explore a little about how filtered indexes work, how they can be applied, and some of the &#8220;gotchas&#8221; to be aware of.</p>
<p>First, for those of you who may not yet know about filtered indexes, allow me enlighten you.  In short, filtered indexes allow you to create an index on a subset of data using a filtering predicate.  Filters can only be applied to non-clustered indexes.  The general syntax of a filtered index is:</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> <span style="color: #808080;">&#91;</span>index_name<span style="color: #808080;">&#93;</span>
<span style="color: #0000FF;">On</span> <span style="color: #808080;">&#91;</span>table_name<span style="color: #808080;">&#93;</span> <span style="color: #808080;">&#40;</span><span style="color: #808080;">&#91;</span>column_list<span style="color: #808080;">&#93;</span><span style="color: #808080;">&#41;</span>
Include <span style="color: #808080;">&#40;</span><span style="color: #808080;">&#91;</span>column_list<span style="color: #808080;">&#93;</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">Where</span> <span style="color: #808080;">&#91;</span>filtered_criteria<span style="color: #808080;">&#93;</span>;</pre></div></div>

<p>For our purposes, we&#8217;re going to be working with the Sales.SalesOrderDetail table in the AdventureWorks database.  Let&#8217;s look at a specific example.  Suppose we have a query that regularly searches on the [SpecialOfferID] column.</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">Select</span> SalesOrderID
    , <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: #FF0000;">'CountOfLineItem'</span>
    , <span style="color: #FF00FF;">Sum</span><span style="color: #808080;">&#40;</span>LineTotal<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">As</span> <span style="color: #FF0000;">'SumOfLineTotal'</span>
<span style="color: #0000FF;">From</span> Sales.<span style="color: #202020;">SalesOrderDetail</span>
<span style="color: #0000FF;">Where</span> SpecialOfferID <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">1</span>
<span style="color: #0000FF;">Group</span> <span style="color: #0000FF;">By</span> SalesOrderID;</pre></div></div>

<p>We notice that there&#8217;s no covering index for this query by looking at the actual execution plan:</p>
<div id="attachment_842" class="wp-caption alignnone" style="width: 310px"><a href="http://sqlfool.com/wp-content/uploads/2009/04/queryplan1.jpg"><img src="http://sqlfool.com/wp-content/uploads/2009/04/queryplan1-300x133.jpg" alt="Query Plan - Clustered Scan" title="queryplan1" width="300" height="133" class="size-medium wp-image-842" /></a><p class="wp-caption-text">Query Plan - Clustered Scan</p></div>
<p>If this is a commonly executed query, then we&#8217;d probably want to toss an index on it.  Before we get started, let&#8217;s take a look at what the distribution of values are on that column:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">Select</span> SpecialOfferID
    , <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: #FF0000;">'rows'</span>
<span style="color: #0000FF;">From</span> Sales.<span style="color: #202020;">SalesOrderDetail</span>
<span style="color: #0000FF;">Group</span> <span style="color: #0000FF;">By</span> SpecialOfferID
<span style="color: #0000FF;">Order</span> <span style="color: #0000FF;">By</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;">Desc</span>;</pre></div></div>

<p>Our distribution of values is:</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">SpecialOfferID rows
-------------- -----------
1              115884
2              3428
3              606
13             524
14             244
16             169
7              137
8              98
11             84
4              80
9              61
5              2</pre></div></div>

<p>As you can see, [SpecialOfferID] = 1 accounts for 96% of our values.  In 2005, we&#8217;d create an index that may look something like this:</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_SalesOrderDetail_SpecialOfferID
    <span style="color: #0000FF;">On</span> Sales.<span style="color: #202020;">SalesOrderDetail</span><span style="color: #808080;">&#40;</span>SpecialOfferID<span style="color: #808080;">&#41;</span>
    Include <span style="color: #808080;">&#40;</span>SalesOrderID, LineTotal<span style="color: #808080;">&#41;</span>;</pre></div></div>

<p>Now if we re-run our original query, this is what we see:</p>
<div id="attachment_836" class="wp-caption alignnone" style="width: 310px"><a href="http://sqlfool.com/wp-content/uploads/2009/04/queryplan2.jpg"><img src="http://sqlfool.com/wp-content/uploads/2009/04/queryplan2-300x160.jpg" alt="Indexed Query Plan" title="queryplan2" width="300" height="160" class="size-medium wp-image-836" /></a><p class="wp-caption-text">Indexed Query Plan</p></div>
<p>So we&#8217;re now performing a non-clustered index seek instead of a clustered index scan.  Already this results in some pretty significant performance improvements.  To see this, we&#8217;re going to use the <a href="http://msdn.microsoft.com/en-us/library/ms181714.aspx" target="_blank">INDEX query hint</a> to force an index scan.  We&#8217;re also going to use the DBCC command <a href="http://msdn.microsoft.com/en-us/library/ms187762.aspx" target="_blank">DROPCLEANBUFFERS</a>, which will allow us to clear the buffer cache and better examine what&#8217;s happening with our IO.</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;">Statistics</span> IO <span style="color: #0000FF;">On</span>;
&nbsp;
<span style="color: #0000FF;">DBCC</span> DropCleanBuffers;
&nbsp;
<span style="color: #0000FF;">Select</span> SalesOrderID
    , <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: #FF0000;">'CountOfLineItem'</span>
    , <span style="color: #FF00FF;">Sum</span><span style="color: #808080;">&#40;</span>LineTotal<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">As</span> <span style="color: #FF0000;">'SumOfLineTotal'</span>
<span style="color: #0000FF;">From</span> Sales.<span style="color: #202020;">SalesOrderDetail</span> <span style="color: #0000FF;">With</span> 
    <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">Index</span><span style="color: #808080;">&#40;</span>PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailID<span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">Where</span> SpecialOfferID <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">1</span>
<span style="color: #0000FF;">Group</span> <span style="color: #0000FF;">By</span> SalesOrderID;
&nbsp;
<span style="color: #0000FF;">DBCC</span> DropCleanBuffers;
&nbsp;
<span style="color: #0000FF;">Select</span> SalesOrderID
    , <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: #FF0000;">'CountOfLineItem'</span>
    , <span style="color: #FF00FF;">Sum</span><span style="color: #808080;">&#40;</span>LineTotal<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">As</span> <span style="color: #FF0000;">'SumOfLineTotal'</span>
<span style="color: #0000FF;">From</span> Sales.<span style="color: #202020;">SalesOrderDetail</span>
<span style="color: #0000FF;">Where</span> SpecialOfferID <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">1</span>
<span style="color: #0000FF;">Group</span> <span style="color: #0000FF;">By</span> SalesOrderID;
&nbsp;
<span style="color: #0000FF;">Set</span> <span style="color: #0000FF;">Statistics</span> IO <span style="color: #0000FF;">Off</span>;</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">Clustered Index Scan:
Table 'SalesOrderDetail'. Scan count 1, logical reads 1240, physical reads 17, read-ahead reads 1242...
&nbsp;
NonClustered Index Seek:
Table 'SalesOrderDetail'. Scan count 2, logical reads 30, physical reads 4, read-ahead reads 480...</pre></div></div>

<p>As you can see, the non-clustered (NC) index seek performs quite a bit better.  Now let&#8217;s create a filtered index and explore what happens:</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> FIX_Sales_SalesOrderDetail_SpecialOfferID_Filtered
    <span style="color: #0000FF;">On</span> Sales.<span style="color: #202020;">SalesOrderDetail</span><span style="color: #808080;">&#40;</span>SalesOrderID<span style="color: #808080;">&#41;</span>
    Include <span style="color: #808080;">&#40;</span>LineTotal<span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">Where</span> SpecialOfferID <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">1</span>;</pre></div></div>

<p>First, let&#8217;s look at the pages consumed by each index:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">SELECT</span> i.<span style="color: #202020;">name</span>, ddips.<span style="color: #202020;">index_depth</span>, ddips.<span style="color: #202020;">index_level</span>
    , ddips.<span style="color: #202020;">page_count</span>, ddips.<span style="color: #202020;">record_count</span>
<span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">indexes</span> <span style="color: #0000FF;">AS</span> i
Join sys.<span style="color: #202020;">dm_db_index_physical_stats</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">DB_ID</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>, 
    <span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#40;</span>N<span style="color: #FF0000;">'Sales.SalesOrderDetail'</span><span style="color: #808080;">&#41;</span>, Null, Null, N<span style="color: #FF0000;">'Detailed'</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> ddips
    <span style="color: #0000FF;">ON</span> i.<span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> ddips.<span style="color: #FF00FF;">OBJECT_ID</span>
    And i.<span style="color: #202020;">index_id</span> <span style="color: #808080;">=</span> ddips.<span style="color: #202020;">index_id</span>
<span style="color: #0000FF;">WHERE</span> i.<span style="color: #202020;">name</span> In <span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'IX_Sales_SalesOrderDetail_SpecialOfferID'</span>
    , <span style="color: #FF0000;">'FIX_Sales_SalesOrderDetail_SpecialOfferID_Filtered'</span>
    , <span style="color: #FF0000;">'PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailID'</span><span style="color: #808080;">&#41;</span>
    <span style="color: #808080;">AND</span> ddips.<span style="color: #202020;">index_level</span> <span style="color: #808080;">=</span> <span style="color: #000;">0</span>;</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">name                                                       index_depth index_level page_count  record_count
---------------------------------------------------------- ----------- ----------- ----------- --------------------
PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailID        3           0           1234        121317
IX_Sales_SalesOrderDetail_SpecialOfferID                   3           0           480         121317
FIX_Sales_SalesOrderDetail_SpecialOfferID_Filtered         2           0           19          5433</pre></div></div>

<p>If you scroll over, you&#8217;ll see that the clustered index consumes the most pages, naturally.  The non-filtered NC index consumes less pages than the clustered index because it&#8217;s narrower; however, it still consumes more pages than the filtered index because it&#8217;s storing every data row.  The filtered index, with only 5433 rows stored, is by far our smallest index, consuming 96% less space than our non-filtered NC index.  </p>
<p>Because we&#8217;re using less space to store this index, we should also see an equivalent performance boost.  Let&#8217;s verify that this is the case:</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;">Statistics</span> IO <span style="color: #0000FF;">On</span>;
&nbsp;
<span style="color: #0000FF;">DBCC</span> DropCleanBuffers;
&nbsp;
<span style="color: #0000FF;">Select</span> SalesOrderID
    , <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: #FF0000;">'CountOfLineItem'</span>
    , <span style="color: #FF00FF;">Sum</span><span style="color: #808080;">&#40;</span>LineTotal<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">As</span> <span style="color: #FF0000;">'SumOfLineTotal'</span>
<span style="color: #0000FF;">From</span> Sales.<span style="color: #202020;">SalesOrderDetail</span> <span style="color: #0000FF;">With</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">Index</span><span style="color: #808080;">&#40;</span>IX_Sales_SalesOrderDetail_SpecialOfferID<span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">Where</span> SpecialOfferID <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">1</span>
<span style="color: #0000FF;">Group</span> <span style="color: #0000FF;">By</span> SalesOrderID;
&nbsp;
<span style="color: #0000FF;">DBCC</span> DropCleanBuffers;
&nbsp;
<span style="color: #0000FF;">Select</span> SalesOrderID
    , <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: #FF0000;">'CountOfLineItem'</span>
    , <span style="color: #FF00FF;">Sum</span><span style="color: #808080;">&#40;</span>LineTotal<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">As</span> <span style="color: #FF0000;">'SumOfLineTotal'</span>
<span style="color: #0000FF;">From</span> Sales.<span style="color: #202020;">SalesOrderDetail</span>
<span style="color: #0000FF;">Where</span> SpecialOfferID <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">1</span>
<span style="color: #0000FF;">Group</span> <span style="color: #0000FF;">By</span> SalesOrderID;
&nbsp;
<span style="color: #0000FF;">Set</span> <span style="color: #0000FF;">Statistics</span> IO <span style="color: #0000FF;">Off</span>;</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">NonClustered Index Seek:
Table 'SalesOrderDetail'. Scan count 2, logical reads 30, physical reads 4, read-ahead reads 480
&nbsp;
Filtered Index Scan:
Table 'SalesOrderDetail'. Scan count 1, logical reads 24, physical reads 2, read-ahead reads 22</pre></div></div>

<div id="attachment_846" class="wp-caption alignnone" style="width: 310px"><a href="http://sqlfool.com/wp-content/uploads/2009/04/queryplan3.jpg"><img src="http://sqlfool.com/wp-content/uploads/2009/04/queryplan3-300x273.jpg" alt="Filtered Query Plan" title="queryplan3" width="300" height="273" class="size-medium wp-image-846" /></a><p class="wp-caption-text">Filtered Query Plan</p></div>
<p>As expected, we get the best results with our filtered index scan.  </p>
<p>You&#8217;ll notice that I did *not* create the index on the [SpecialOfferID] column like I did in [IX_Sales_SalesOrderDetail_SpecialOfferID].  This is because my query doesn&#8217;t care what my [SpecialOfferID] value is, just as long as it&#8217;s not equal to 1.  My non-filtered NC index was created on [SpecialOfferID] because it needed to navigate the B-TREE to find the records where [SpecialOfferID] <> 1.  With my filtered index, the query optimizer knows that all of my records already meet the criteria, so doesn&#8217;t need to navigate through the index to find the matching results.  </p>
<p>We could choose to include the [SpecialOfferID] data in our filtered index, but we&#8217;d most likely want to make it an included column rather than part of the index key.  In fact, it&#8217;s important to note that, if I don&#8217;t add [SpecialOfferID] as an included column and I want to return it in the results, i.e.</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">Select</span> SalesOrderID
    , SpecialOfferID
    , <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: #FF0000;">'CountOfLineItem'</span>
    , <span style="color: #FF00FF;">Sum</span><span style="color: #808080;">&#40;</span>LineTotal<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">As</span> <span style="color: #FF0000;">'SumOfLineTotal'</span>
<span style="color: #0000FF;">From</span> Sales.<span style="color: #202020;">SalesOrderDetail</span>
<span style="color: #0000FF;">Where</span> SpecialOfferID <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">1</span>
<span style="color: #0000FF;">Group</span> <span style="color: #0000FF;">By</span> SalesOrderID
    , SpecialOfferID;</pre></div></div>

<p><strong>my filtered index will not be used</strong> and I will instead scan on the clustered index once more (assuming [IX_Sales_SalesOrderDetail_SpecialOfferID] does not exist).  This is because the <strong>filtering criteria is not included anywhere on the actual index page</strong>.  This is actually good news, in my opinion, since it allows you to create even leaner indexes.  And like I already mentioned, if you do need the data returned, you can always add the filtering criteria as included columns.</p>
<p>What if you&#8217;re trying to find out whether or not an index is filtered, and what it&#8217;s filtered on?  The sys.indexes catalog view has been updated in 2008 to include this information:</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> name In <span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'IX_Sales_SalesOrderDetail_SpecialOfferID'</span>
    , <span style="color: #FF0000;">'FIX_Sales_SalesOrderDetail_SpecialOfferID_Filtered'</span>
    , <span style="color: #FF0000;">'PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailID'</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
------------------------------------------------------ ---------- -------------------------
FIX_Sales_SalesOrderDetail_SpecialOfferID_Filtered     1          ([SpecialOfferID]&lt;&gt;(1))
IX_Sales_SalesOrderDetail_SpecialOfferID               0          NULL
PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailID    0          NULL</pre></div></div>

<p>I personally recommend Kimberly Tripp&#8217;s system stored proc, <a href="http://www.sqlskills.com/blogs/kimberly/post/sp_helpindex2-to-show-included-columns-(20052b)-and-filtered-indexes-(2008)-which-are-not-shown-by-sp_helpindex.aspx" target="_blank">sp_helpindex2</a>.  It returns a lot of good information about your indexes, such as included columns and filtering criteria.</p>
<p>That&#8217;s all I have for today.  Hopefully, you now understand how powerful filtered indexes can be.  When used properly, filtered indexes can use less space, consume less IO, and improve overall query performance.  </p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2009/04/filtered-indexes-what-you-need-to-know/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>SQL Tweaks and Tools That Make My Life Easier</title>
		<link>http://sqlfool.com/2008/12/sql-tweaks-and-tools-that-make-my-life-easier/</link>
		<comments>http://sqlfool.com/2008/12/sql-tweaks-and-tools-that-make-my-life-easier/#comments</comments>
		<pubDate>Thu, 04 Dec 2008 14:27:27 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[SQL Tips]]></category>
		<category><![CDATA[2008]]></category>
		<category><![CDATA[indexes]]></category>
		<category><![CDATA[SSMS]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=226</guid>
		<description><![CDATA[It still surprises me how many people don&#8217;t know about some of the very things that make my job so much easier. So this next post is dedicated to sharing some of the tweaks and tools I&#8217;ve run across that will help anyone who works with SQL: &#160; Indexes Anyone who uses included columns is [...]]]></description>
			<content:encoded><![CDATA[<p>It still surprises me how many people don&#8217;t know about some of the very things that make my job so much easier.  So this next post is dedicated to sharing some of the tweaks and tools I&#8217;ve run across that will help anyone who works with SQL:</p>
<p>&nbsp;</p>
<p><span style="color: #ff6600;"><strong>Indexes</strong></span><br />
Anyone who uses included columns is probably well aware of the frustrations that can come from having to look up information on which columns are included.  I wrote a stored procedure, <a href="http://sqlfool.com/2008/10/index-interrogation-script/" target="_blank">dba_indexLookup_sp</a>, to help me with this, before discovering sp_helpindex2.  If you haven&#8217;t heard of sp_helpindex2, it&#8217;s a re-write of sp_helpindex by Kimberly Tripp.  You can find it on <a href="http://www.sqlskills.com/BLOGS/KIMBERLY/post/Updates-(fixes)-to-sp_helpindex2.aspx" target="_blank">Kimberly&#8217;s blog</a>.  The main difference is Kimberly&#8217;s is a system stored procedure (mine is not) and my version returns partitioning information (Kimberly&#8217;s does not).  Check both out and use whichever one meets your needs best.  </p>
<p>&nbsp;</p>
<p><span style="color: #ff6600;"><strong>KeyBoard ShortCuts</strong></span></p>
<p>In SQL Server Management Studio (SSMS), click on:<br />
&nbsp;&nbsp;&nbsp;&nbsp;Tools &#8211;> Options&#8230; &#8211;> Environment &#8211;> Keyboard</p>
<div class="wp-caption alignnone" style="width: 654px"><a href="http://sqlfool.com/blogImages/20081203/tweaks_1.jpg"><img alt="Keyboard Shortcuts" src="http://sqlfool.com/blogImages/20081203/tweaks_1_small.jpg" title="Keyboard Shortcuts" /></a><p class="wp-caption-text">Keyboard Shortcuts</p></div>
<p>For your copying convenience:</p>
<p>Ctrl+3&nbsp;&nbsp;&nbsp;Select Top 100 * From<br />
Ctrl+4&nbsp;&nbsp;&nbsp;sp_tables @table_owner = &#8216;dbo&#8217;<br />
Ctrl+5&nbsp;&nbsp;&nbsp;sp_columns<br />
Ctrl+6&nbsp;&nbsp;&nbsp;sp_stored_procedures @sp_owner = &#8216;dbo&#8217;<br />
Ctrl+7&nbsp;&nbsp;&nbsp;sp_spaceused<br />
Ctrl+8&nbsp;&nbsp;&nbsp;sp_helptext<br />
Ctrl+9&nbsp;&nbsp;&nbsp;<a href="http://sqlfool.com/2008/10/index-interrogation-script/" target="_blank">dba_indexLookup_sp</a> or <a href="http://www.sqlskills.com/BLOGS/KIMBERLY/post/Updates-(fixes)-to-sp_helpindex2.aspx" target="_blank">sp_helpindex2</a></p>
<p>Please note that these settings will not take effect until you open a new query window.  Here&#8217;s an example of how you could use this:  use Ctrl+4 to find a list of tables, then copy one into your query window; to view a sample of that table&#8217;s data, highlight the table name (I usually double-click on it) and press Ctrl+3.  It&#8217;s a thing of beauty.  Oh, and you may want to remove/change the schema filters if you use schemas other than dbo.</p>
<p>&nbsp;</p>
<p><span style="color: #ff6600;"><strong>Query Execution Settings</strong></span></p>
<p>After having one too many issues arise from non-DBA&#8217;s connecting to the production environment to run a devastating ad hoc, I&#8217;ve had all of our developers and analysts adopt the following settings.  The only thing difference between my setting and theirs is that I have &#8220;Set Statistics IO&#8221; selected.  FYI &#8211; you can also make these same setting changes in Visual Studio.</p>
<p>In SQL Server Management Studio (SSMS), click on:<br />
&nbsp;&nbsp;&nbsp;&nbsp;Tools &#8211;> Options&#8230; &#8211;> Query Execution &#8211;> SQL Server &#8211;> Advanced</p>
<div class="wp-caption alignnone" style="width: 654px"><a href="http://sqlfool.com/blogImages/20081203/tweaks_2.jpg"><img alt="Query Execution Settings" src="http://sqlfool.com/blogImages/20081203/tweaks_2_small.jpg" title="Query Execution Settings"/></a><p class="wp-caption-text">Query Execution Settings</p></div>
<p>&nbsp;</p>
<p><span style="color: #ff6600;"><strong>Copy Behavior</strong></span><br />
This next tip actually has nothing to do with SQL Server, and can be done with any Microsoft product.  However, I just learned about it a few weeks ago and already I use it quite frequently.  </p>
<p>Holding down &#8220;Alt&#8221; while you drag your mouse will change your selection behavior to block selection.</p>
<div class="wp-caption alignnone" style="width: 826px"><a href="http://sqlfool.com/blogImages/20081203/tweaks_5.jpg"><img alt="Block Selection" src="http://sqlfool.com/blogImages/20081203/tweaks_5_small.jpg" title="Block Selection"/></a><p class="wp-caption-text">Block Selection</p></div>
<p>&nbsp;</p>
<p><strong>Please note:</strong> The following tools requires SQL 2008 Management Studio.  These tools will also work when you connect SQL 2008 SSMS to a 2005 instance.</p>
<p>&nbsp;</p>
<p><span style="color: #ff6600;"><strong>Object Detail Explorer</strong></span></p>
<p>Finally, there&#8217;s a reason to use the Object Detail Explorer!  My favorite use is to quickly find the table size and row counts of all the tables in a database.  If these options are not currently available, you may just need to right click on the column headers and add it to the display.</p>
<div class="wp-caption alignnone" style="width: 839px"><a href="http://sqlfool.com/blogImages/20081203/tweaks_3.jpg"><img alt="Object Detail Explorer" src="http://sqlfool.com/blogImages/20081203/tweaks_3_small.jpg" title="Object Detail Explorer"/></a><p class="wp-caption-text">Object Detail Explorer</p></div>
<p>&nbsp;</p>
<p><span style="color: #ff6600;"><strong>Missing Indexes</strong></span></p>
<p>And lastly, when using SSMS 2008 to execute Display Estimated Query Plan (Ctrl+L), it will show you if you&#8217;re missing any indexes.  This will even work if you connect SSMS 2008 to SQL 2005!</p>
<div class="wp-caption alignnone" style="width: 806px"><a href="http://sqlfool.com/blogImages/20081203/tweaks_4.jpg"><img alt="Missing Index" src="http://sqlfool.com/blogImages/20081203/tweaks_4_small.jpg" title="Missing Index"/></a><p class="wp-caption-text">Missing Index</p></div>
<p>That pretty much covers it for now.  HTH!  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Michelle</p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2008/12/sql-tweaks-and-tools-that-make-my-life-easier/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Updated Index Defrag Script (2005, 2008)</title>
		<link>http://sqlfool.com/2008/11/updated-index-defrag-script-2005-2008/</link>
		<comments>http://sqlfool.com/2008/11/updated-index-defrag-script-2005-2008/#comments</comments>
		<pubDate>Mon, 17 Nov 2008 17:48:33 +0000</pubDate>
		<dc:creator>Michelle Ufford</dc:creator>
				<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[SQL 2008]]></category>
		<category><![CDATA[T-SQL Scripts]]></category>
		<category><![CDATA[2008]]></category>
		<category><![CDATA[defrag]]></category>
		<category><![CDATA[indexes]]></category>
		<category><![CDATA[partitioning]]></category>
		<category><![CDATA[TSQL]]></category>

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

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">IF</span> <span style="color: #808080;">EXISTS</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">tables</span>
                <span style="color: #0000FF;">WHERE</span> <span style="color: #808080;">&#91;</span>name<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> N<span style="color: #FF0000;">'dba_indexDefragLog'</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">BEGIN</span>
&nbsp;
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">dba_indexDefragLog</span>;
&nbsp;
    <span style="color: #0000FF;">PRINT</span> <span style="color: #FF0000;">'dba_indexDefragLog table dropped!'</span>;
&nbsp;
<span style="color: #0000FF;">END</span>
&nbsp;
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">dba_indexDefragLog</span>
<span style="color: #808080;">&#40;</span>
      indexDefrag_id    <span style="color: #0000FF;">INT</span> <span style="color: #0000FF;">IDENTITY</span><span style="color: #808080;">&#40;</span><span style="color: #000;">1</span>,<span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>   <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , objectID          <span style="color: #0000FF;">INT</span>                 <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , objectName        <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">130</span><span style="color: #808080;">&#41;</span>       <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , indexID           <span style="color: #0000FF;">INT</span>                 <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , indexName         <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">130</span><span style="color: #808080;">&#41;</span>       <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , partitionNumber   <span style="color: #0000FF;">smallint</span>            not null
    , fragmentation     <span style="color: #0000FF;">FLOAT</span>               <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , page_count        <span style="color: #0000FF;">INT</span>                 <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , dateTimeStart     <span style="color: #0000FF;">DATETIME</span>            <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , durationSeconds   <span style="color: #0000FF;">INT</span>                 <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    <span style="color: #0000FF;">CONSTRAINT</span> PK_indexDefragLog
        <span style="color: #0000FF;">PRIMARY</span> <span style="color: #0000FF;">KEY</span> <span style="color: #0000FF;">CLUSTERED</span> <span style="color: #808080;">&#40;</span>indexDefrag_id<span style="color: #808080;">&#41;</span>
<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">PRINT</span> <span style="color: #FF0000;">'dba_indexDefragLog Table Created'</span>;
&nbsp;
<span style="color: #0000FF;">IF</span> <span style="color: #FF00FF;">OBJECTPROPERTY</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'dbo.dba_indexDefrag_sp'</span><span style="color: #808080;">&#41;</span>,
        N<span style="color: #FF0000;">'IsProcedure'</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">IS</span> Null
<span style="color: #0000FF;">BEGIN</span>
    <span style="color: #0000FF;">EXECUTE</span> <span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Create Procedure dbo.dba_indexDefrag_sp
        As Print '</span><span style="color: #FF0000;">'Hello World!'</span><span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>;
    <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Procedure dba_indexDefrag_sp created.'</span>
        , <span style="color: #000;">10</span>, <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>;
<span style="color: #0000FF;">END</span>;
Go
&nbsp;
<span style="color: #0000FF;">SET</span> ANSI_Nulls <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">SET</span> Ansi_Padding <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">SET</span> Ansi_Warnings <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">SET</span> ArithAbort <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">SET</span> Concat_Null_Yields_Null <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">SET</span> <span style="color: #0000FF;">NOCOUNT</span> <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">SET</span> Numeric_RoundAbort <span style="color: #0000FF;">OFF</span>;
<span style="color: #0000FF;">SET</span> Quoted_Identifier <span style="color: #0000FF;">ON</span>;
Go
&nbsp;
<span style="color: #0000FF;">ALTER</span> <span style="color: #0000FF;">PROCEDURE</span> dbo.<span style="color: #202020;">dba_indexDefrag_sp</span>
&nbsp;
    <span style="color: #008080;">/* Declare Parameters */</span>
      @minFragmentation     <span style="color: #0000FF;">FLOAT</span>           <span style="color: #808080;">=</span> <span style="color: #000;">10.0</span>
        <span style="color: #008080;">/* in percent, will not defrag if fragmentation
           less than specified */</span>
    , @rebuildThreshold     <span style="color: #0000FF;">FLOAT</span>           <span style="color: #808080;">=</span> <span style="color: #000;">30.0</span>
        <span style="color: #008080;">/* in percent, greater than @rebuildThreshold
           will result in rebuild instead of reorg */</span>
    , @onlineRebuild        <span style="color: #0000FF;">bit</span>             <span style="color: #808080;">=</span> <span style="color: #000;">1</span>     
        <span style="color: #008080;">/* 1 = online rebuild; 0 = offline rebuild */</span>
    , @executeSQL           <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
        <span style="color: #008080;">/* 1 = execute; 0 = print command only */</span>
    , @tableName            <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>   <span style="color: #808080;">=</span> Null 
        <span style="color: #008080;">/* Option to specify a table name */</span>
    , @printCommands        <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
        <span style="color: #008080;">/* 1 = print commands; 0 = do not print commands */</span>
    , @printFragmentation   <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
        <span style="color: #008080;">/* 1 = print fragmentation prior to defrag; 
           0 = do not print */</span>
    , @defragDelay          <span style="color: #0000FF;">CHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">8</span><span style="color: #808080;">&#41;</span>         <span style="color: #808080;">=</span> <span style="color: #FF0000;">'00:00:05'</span>
        <span style="color: #008080;">/* time to wait between defrag commands */</span>
<span style="color: #0000FF;">AS</span>
<span style="color: #008080;">/********************************************************************
    Name:       dba_indexDefrag_sp
&nbsp;
    Author:     Michelle F. Ufford
&nbsp;
    Purpose:    Defrags all indexes for the current database
&nbsp;
    Notes:      This script was designed for SQL Server 2005
                Enterprise Edition.
&nbsp;
    CAUTION: Monitor transaction log if executing for the first time!
&nbsp;
      @minFragmentation     defaulted to 10%, will not defrag if
                            fragmentation if less than specified.
&nbsp;
      @rebuildThreshold     defaulted to 30% as recommended by
                            Microsoft in BOL;
                            &gt; than 30% will result in rebuild instead
&nbsp;
      @onlineRebuild        1 = online rebuild; 
                            0 = offline rebuild
&nbsp;
      @executeSQL           1 = execute the SQL generated by this proc;
                            0 = print command only
&nbsp;
      @tableName            Specify if you only want to defrag indexes
                            for a specific table
&nbsp;
      @printCommands        1 = print commands to screen;
                            0 = do not print commands
&nbsp;
      @printFragmentation   1 = print fragmentation to screen;
                            0 = do not print fragmentation
&nbsp;
      @defragDelay          time to wait between defrag commands;
                            gives the server some time to catch up
&nbsp;
    Called by:  SQL Agent Job or DBA
&nbsp;
    Date        Initials  Description
    ----------------------------------------------------------------
    2008-10-27  MFU       Initial Release
    2008-11-17  MFU       Added page_count to log table
                          , added @printFragmentation option
********************************************************************
    Exec dbo.dba_indexDefrag_sp
          @executeSQL         = 1
        , @printCommands      = 1
        , @minFragmentation   = 0
        , @printFragmentation = 1;
********************************************************************/</span>
&nbsp;
<span style="color: #0000FF;">SET</span> <span style="color: #0000FF;">NOCOUNT</span> <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">SET</span> XACT_Abort <span style="color: #0000FF;">ON</span>;
&nbsp;
<span style="color: #0000FF;">BEGIN</span>
&nbsp;
    <span style="color: #008080;">/* Declare our variables */</span>
    <span style="color: #0000FF;">DECLARE</span>   @objectID         <span style="color: #0000FF;">INT</span>
            , @indexID          <span style="color: #0000FF;">INT</span>
            , @partitionCount   <span style="color: #0000FF;">BIGINT</span>
            , @schemaName       <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">130</span><span style="color: #808080;">&#41;</span>
            , @objectName       <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">130</span><span style="color: #808080;">&#41;</span>
            , @indexName        <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">130</span><span style="color: #808080;">&#41;</span>
            , @partitionNumber  <span style="color: #0000FF;">SMALLINT</span>
            , @partitions       <span style="color: #0000FF;">SMALLINT</span>
            , @fragmentation    <span style="color: #0000FF;">FLOAT</span>
            , @pageCount        <span style="color: #0000FF;">INT</span>
            , @sqlCommand       <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>
            , @rebuildCommand   <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">200</span><span style="color: #808080;">&#41;</span>
            , @dateTimeStart    <span style="color: #0000FF;">DATETIME</span>
            , @dateTimeEnd      <span style="color: #0000FF;">DATETIME</span>
            , @containsLOB      <span style="color: #0000FF;">BIT</span>;
&nbsp;
    <span style="color: #008080;">/* Just a little validation... */</span>
    <span style="color: #0000FF;">IF</span> @minFragmentation Not Between <span style="color: #000;">0.00</span> And <span style="color: #000;">100.0</span>
        <span style="color: #0000FF;">SET</span> @minFragmentation <span style="color: #808080;">=</span> <span style="color: #000;">10.0</span>;
&nbsp;
    <span style="color: #0000FF;">IF</span> @rebuildThreshold Not Between <span style="color: #000;">0.00</span> And <span style="color: #000;">100.0</span>
        <span style="color: #0000FF;">SET</span> @rebuildThreshold <span style="color: #808080;">=</span> <span style="color: #000;">30.0</span>;
&nbsp;
    <span style="color: #0000FF;">IF</span> @defragDelay Not Like <span style="color: #FF0000;">'00:[0-5][0-9]:[0-5][0-9]'</span>
        <span style="color: #0000FF;">SET</span> @defragDelay <span style="color: #808080;">=</span> <span style="color: #FF0000;">'00:00:05'</span>;
&nbsp;
    <span style="color: #008080;">/* Determine which indexes to defrag using our
       user-defined parameters */</span>
    <span style="color: #0000FF;">SELECT</span>
          <span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #0000FF;">AS</span> objectID
        , index_id <span style="color: #0000FF;">AS</span> indexID
        , partition_number <span style="color: #0000FF;">AS</span> partitionNumber
        , avg_fragmentation_in_percent <span style="color: #0000FF;">AS</span> fragmentation
        , page_count 
        , <span style="color: #000;">0</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'defragStatus'</span>
            <span style="color: #008080;">/* 0 = unprocessed, 1 = processed */</span>
    <span style="color: #0000FF;">INTO</span> #indexDefragList
    <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">dm_db_index_physical_stats</span>
        <span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">DB_ID</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>, <span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#40;</span>@tableName<span style="color: #808080;">&#41;</span>, <span style="color: #808080;">NULL</span> , <span style="color: #808080;">NULL</span>, N<span style="color: #FF0000;">'Limited'</span><span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">WHERE</span> avg_fragmentation_in_percent <span style="color: #808080;">&gt;</span> @minFragmentation
        And index_id <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span>
    <span style="color: #0000FF;">OPTION</span> <span style="color: #808080;">&#40;</span>MaxDop <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #008080;">/* Create a clustered index to boost performance a little */</span>
    <span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">CLUSTERED</span> <span style="color: #0000FF;">INDEX</span> CIX_temp_indexDefragList
        <span style="color: #0000FF;">ON</span> #indexDefragList<span style="color: #808080;">&#40;</span>objectID, indexID, partitionNumber<span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #008080;">/* Begin our loop for defragging */</span>
    <span style="color: #0000FF;">WHILE</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #FF00FF;">COUNT</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">*</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">FROM</span> #indexDefragList
            <span style="color: #0000FF;">WHERE</span> defragStatus <span style="color: #808080;">=</span> <span style="color: #000;">0</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span>
    <span style="color: #0000FF;">BEGIN</span>
&nbsp;
        <span style="color: #008080;">/* Grab the most fragmented index first to defrag */</span>
        <span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">TOP</span> <span style="color: #000;">1</span>
              @objectID         <span style="color: #808080;">=</span> objectID
            , @fragmentation    <span style="color: #808080;">=</span> fragmentation
            , @indexID          <span style="color: #808080;">=</span> indexID
            , @partitionNumber  <span style="color: #808080;">=</span> partitionNumber
            , @pageCount        <span style="color: #808080;">=</span> page_count
        <span style="color: #0000FF;">FROM</span> #indexDefragList
        <span style="color: #0000FF;">WHERE</span> defragStatus <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
        <span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> fragmentation <span style="color: #0000FF;">DESC</span>;
&nbsp;
        <span style="color: #008080;">/* Look up index information */</span>
        <span style="color: #0000FF;">SELECT</span> @objectName <span style="color: #808080;">=</span> <span style="color: #FF00FF;">QUOTENAME</span><span style="color: #808080;">&#40;</span>o.<span style="color: #202020;">name</span><span style="color: #808080;">&#41;</span>
             , @schemaName <span style="color: #808080;">=</span> <span style="color: #FF00FF;">QUOTENAME</span><span style="color: #808080;">&#40;</span>s.<span style="color: #202020;">name</span><span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">objects</span> <span style="color: #0000FF;">AS</span> o
        <span style="color: #0000FF;">Inner</span> Join sys.<span style="color: #202020;">schemas</span> <span style="color: #0000FF;">AS</span> s
            <span style="color: #0000FF;">ON</span> s.<span style="color: #202020;">schema_id</span> <span style="color: #808080;">=</span> o.<span style="color: #202020;">schema_id</span>
        <span style="color: #0000FF;">WHERE</span> o.<span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> @objectID;
&nbsp;
        <span style="color: #0000FF;">SELECT</span> @indexName <span style="color: #808080;">=</span> <span style="color: #FF00FF;">QUOTENAME</span><span style="color: #808080;">&#40;</span>name<span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">indexes</span>
        <span style="color: #0000FF;">WHERE</span> <span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> @objectID
            And index_id <span style="color: #808080;">=</span> @indexID
            And type <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span>;
&nbsp;
        <span style="color: #008080;">/* Determine if the index is partitioned */</span>
        <span style="color: #0000FF;">SELECT</span> @partitionCount <span style="color: #808080;">=</span> <span style="color: #FF00FF;">COUNT</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">*</span><span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">partitions</span>
        <span style="color: #0000FF;">WHERE</span> <span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> @objectID
            And index_id <span style="color: #808080;">=</span> @indexID;
&nbsp;
        <span style="color: #008080;">/* Look for LOBs */</span>
        <span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">TOP</span> <span style="color: #000;">1</span>
            @containsLOB <span style="color: #808080;">=</span> column_id
        <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">columns</span> <span style="color: #0000FF;">WITH</span> <span style="color: #808080;">&#40;</span>NOLOCK<span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">WHERE</span> 
            <span style="color: #808080;">&#91;</span><span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> @objectID
            And <span style="color: #808080;">&#40;</span>system_type_id In <span style="color: #808080;">&#40;</span><span style="color: #000;">34</span>, <span style="color: #000;">35</span>, <span style="color: #000;">99</span><span style="color: #808080;">&#41;</span>
            <span style="color: #008080;">-- 34 = image, 35 = text, 99 = ntext</span>
                    Or max_length <span style="color: #808080;">=</span> <span style="color: #808080;">-</span><span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>;
            <span style="color: #008080;">-- varbinary(max), varchar(max), nvarchar(max), xml</span>
&nbsp;
        <span style="color: #008080;">/* See if we should rebuild or reorganize; handle thusly */</span>
        <span style="color: #0000FF;">IF</span> @fragmentation <span style="color: #808080;">&lt;</span> @rebuildThreshold And @partitionCount <span style="color: #808080;">&lt;=</span> <span style="color: #000;">1</span>
            <span style="color: #0000FF;">SET</span> @sqlCommand <span style="color: #808080;">=</span> N<span style="color: #FF0000;">'Alter Index '</span> <span style="color: #808080;">+</span> @indexName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">' On '</span>
                <span style="color: #808080;">+</span> @schemaName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">'.'</span> <span style="color: #808080;">+</span> @objectName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">' ReOrganize'</span>;
&nbsp;
        <span style="color: #0000FF;">IF</span> @fragmentation <span style="color: #808080;">&gt;=</span> @rebuildThreshold
            And IsNull<span style="color: #808080;">&#40;</span>@containsLOB, <span style="color: #000;">0</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
                <span style="color: #008080;">-- Cannot rebuild if the table has one or more LOB</span>
            And @partitionCount <span style="color: #808080;">&lt;=</span> <span style="color: #000;">1</span>
        <span style="color: #0000FF;">BEGIN</span>
&nbsp;
            <span style="color: #008080;">/* We should always rebuild online if possible
                (SQL 2005 Enterprise) */</span>
            <span style="color: #0000FF;">IF</span> @onlineRebuild <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
                <span style="color: #0000FF;">SET</span> @rebuildCommand <span style="color: #808080;">=</span> N<span style="color: #FF0000;">' Rebuild With
                    (Online = Off, MaxDop = 1)'</span>;
            <span style="color: #0000FF;">ELSE</span>
                <span style="color: #0000FF;">SET</span> @rebuildCommand <span style="color: #808080;">=</span> N<span style="color: #FF0000;">' Rebuild With
                    (Online = On, MaxDop = 1)'</span>;
&nbsp;
            <span style="color: #0000FF;">SET</span> @sqlCommand <span style="color: #808080;">=</span> N<span style="color: #FF0000;">'Alter Index '</span> <span style="color: #808080;">+</span> @indexName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">' On '</span>
                <span style="color: #808080;">+</span> @schemaName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">'.'</span> <span style="color: #808080;">+</span> @objectName <span style="color: #808080;">+</span> @rebuildCommand;
        <span style="color: #0000FF;">END</span>;
&nbsp;
        <span style="color: #008080;">/* If our index is partitioned, we should always reorganize */</span>
        <span style="color: #0000FF;">IF</span> @partitionCount <span style="color: #808080;">&gt;</span> <span style="color: #000;">1</span>
            <span style="color: #0000FF;">SET</span> @sqlCommand <span style="color: #808080;">=</span> N<span style="color: #FF0000;">'Alter Index '</span> <span style="color: #808080;">+</span> @indexName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">' On '</span>
                <span style="color: #808080;">+</span> @schemaName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">'.'</span> <span style="color: #808080;">+</span> @objectName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">' ReOrganize'</span>
                <span style="color: #808080;">+</span> N<span style="color: #FF0000;">' Partition = '</span>
                <span style="color: #808080;">+</span> <span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span>@partitionNumber <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">10</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>;
                <span style="color: #008080;">-- no MaxDop needed, single threaded operation</span>
&nbsp;
        <span style="color: #008080;">/* Are we executing the SQL?  If so, do it */</span>
        <span style="color: #0000FF;">IF</span> @executeSQL <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
        <span style="color: #0000FF;">BEGIN</span>
&nbsp;
            <span style="color: #008080;">/* Grab the time for logging purposes */</span>
            <span style="color: #0000FF;">SET</span> @dateTimeStart  <span style="color: #808080;">=</span> <span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>;
            <span style="color: #0000FF;">EXECUTE</span> <span style="color: #808080;">&#40;</span>@sqlCommand<span style="color: #808080;">&#41;</span>;
            <span style="color: #0000FF;">SET</span> @dateTimeEnd  <span style="color: #808080;">=</span> <span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>;
&nbsp;
            <span style="color: #008080;">/* Log our actions */</span>
            <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> dbo.<span style="color: #202020;">dba_indexDefragLog</span>
            <span style="color: #808080;">&#40;</span>
                  objectID
                , objectName
                , indexID
                , indexName
                , partitionNumber
                , fragmentation
                , page_count
                , dateTimeStart
                , durationSeconds
            <span style="color: #808080;">&#41;</span>
            <span style="color: #0000FF;">SELECT</span>
                  @objectID
                , @objectName
                , @indexID
                , @indexName
                , @partitionNumber
                , @fragmentation
                , @pageCount
                , @dateTimeStart
                , <span style="color: #FF00FF;">DATEDIFF</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SECOND</span>, @dateTimeStart, @dateTimeEnd<span style="color: #808080;">&#41;</span>;
&nbsp;
            <span style="color: #008080;">/* Just a little breather for the server */</span>
            <span style="color: #0000FF;">WAITFOR</span> Delay @defragDelay;
&nbsp;
            <span style="color: #008080;">/* Print if specified to do so */</span>
            <span style="color: #0000FF;">IF</span> @printCommands <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
                <span style="color: #0000FF;">PRINT</span> N<span style="color: #FF0000;">'Executed: '</span> <span style="color: #808080;">+</span> @sqlCommand;
        <span style="color: #0000FF;">END</span>
        <span style="color: #0000FF;">ELSE</span>
        <span style="color: #008080;">/* Looks like we're not executing, just print
            the commands */</span>
        <span style="color: #0000FF;">BEGIN</span>
            <span style="color: #0000FF;">IF</span> @printCommands <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
                <span style="color: #0000FF;">PRINT</span> @sqlCommand;
        <span style="color: #0000FF;">END</span>
&nbsp;
        <span style="color: #008080;">/* Update our index defrag list when we've
            finished with that index */</span>
        <span style="color: #0000FF;">UPDATE</span> #indexDefragList
        <span style="color: #0000FF;">SET</span> defragStatus <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
        <span style="color: #0000FF;">WHERE</span> objectID         <span style="color: #808080;">=</span> @objectID
          And indexID          <span style="color: #808080;">=</span> @indexID
          And partitionNumber  <span style="color: #808080;">=</span> @partitionNumber;
&nbsp;
    <span style="color: #0000FF;">END</span>
&nbsp;
    <span style="color: #008080;">/* Do we want to output our fragmentation results? */</span>
    <span style="color: #0000FF;">If</span> @printFragmentation <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
        <span style="color: #0000FF;">Select</span> idl.<span style="color: #202020;">objectID</span>
            , o.<span style="color: #202020;">name</span> <span style="color: #0000FF;">As</span> <span style="color: #FF0000;">'tableName'</span>
            , idl.<span style="color: #202020;">indexID</span>
            , i.<span style="color: #202020;">name</span> <span style="color: #0000FF;">As</span> <span style="color: #FF0000;">'indexName'</span>
            , idl.<span style="color: #202020;">fragmentation</span>
            , idl.<span style="color: #202020;">page_count</span>
        <span style="color: #0000FF;">From</span> #indexDefragList <span style="color: #0000FF;">As</span> idl
        Join sys.<span style="color: #202020;">objects</span> <span style="color: #0000FF;">AS</span> o
            <span style="color: #0000FF;">On</span> idl.<span style="color: #202020;">objectID</span> <span style="color: #808080;">=</span> o.<span style="color: #FF00FF;">object_id</span>
        Join sys.<span style="color: #202020;">indexes</span> <span style="color: #0000FF;">As</span> i
            <span style="color: #0000FF;">On</span> idl.<span style="color: #202020;">objectID</span> <span style="color: #808080;">=</span> i.<span style="color: #FF00FF;">object_id</span>
            And idl.<span style="color: #202020;">indexID</span> <span style="color: #808080;">=</span> i.<span style="color: #202020;">index_id</span>;
&nbsp;
    <span style="color: #008080;">/* When everything is done, make sure to get rid of
        our temp table */</span>
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">TABLE</span> #indexDefragList;
&nbsp;
    <span style="color: #0000FF;">SET</span> <span style="color: #0000FF;">NOCOUNT</span> <span style="color: #0000FF;">OFF</span>;
    <span style="color: #0000FF;">RETURN</span> <span style="color: #000;">0</span>
<span style="color: #0000FF;">END</span>
Go</pre></div></div>

<p>&nbsp;</p>
<p><strong>Standard Version:</strong></p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">IF</span> <span style="color: #808080;">EXISTS</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">tables</span>
                <span style="color: #0000FF;">WHERE</span> <span style="color: #808080;">&#91;</span>name<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> N<span style="color: #FF0000;">'dba_indexDefragLog'</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">BEGIN</span>
&nbsp;
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">dba_indexDefragLog</span>;
&nbsp;
    <span style="color: #0000FF;">PRINT</span> <span style="color: #FF0000;">'dba_indexDefragLog table dropped!'</span>;
&nbsp;
<span style="color: #0000FF;">END</span>
&nbsp;
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> dbo.<span style="color: #202020;">dba_indexDefragLog</span>
<span style="color: #808080;">&#40;</span>
      indexDefrag_id    <span style="color: #0000FF;">INT</span> <span style="color: #0000FF;">IDENTITY</span><span style="color: #808080;">&#40;</span><span style="color: #000;">1</span>,<span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>   <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , objectID          <span style="color: #0000FF;">INT</span>                 <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , objectName        <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">130</span><span style="color: #808080;">&#41;</span>       <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , indexID           <span style="color: #0000FF;">INT</span>                 <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , indexName         <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">130</span><span style="color: #808080;">&#41;</span>       <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , fragmentation     <span style="color: #0000FF;">FLOAT</span>               <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , page_count        <span style="color: #0000FF;">INT</span>                 <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , dateTimeStart     <span style="color: #0000FF;">DATETIME</span>            <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    , durationSeconds   <span style="color: #0000FF;">INT</span>                 <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>
    <span style="color: #0000FF;">CONSTRAINT</span> PK_indexDefragLog
        <span style="color: #0000FF;">PRIMARY</span> <span style="color: #0000FF;">KEY</span> <span style="color: #0000FF;">CLUSTERED</span> <span style="color: #808080;">&#40;</span>indexDefrag_id<span style="color: #808080;">&#41;</span>
<span style="color: #808080;">&#41;</span>;
&nbsp;
<span style="color: #0000FF;">PRINT</span> <span style="color: #FF0000;">'dba_indexDefragLog Table Created'</span>;
&nbsp;
<span style="color: #0000FF;">IF</span> <span style="color: #FF00FF;">OBJECTPROPERTY</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'dbo.dba_indexDefragStandard_sp'</span><span style="color: #808080;">&#41;</span>,
        N<span style="color: #FF0000;">'IsProcedure'</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">IS</span> Null
<span style="color: #0000FF;">BEGIN</span>
    <span style="color: #0000FF;">EXECUTE</span> <span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Create Procedure dbo.dba_indexDefragStandard_sp
        As Print '</span><span style="color: #FF0000;">'Hello World!'</span><span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>;
    <span style="color: #0000FF;">RAISERROR</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">'Procedure dba_indexDefragStandard_sp created.'</span>
        , <span style="color: #000;">10</span>, <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>;
<span style="color: #0000FF;">END</span>;
Go
&nbsp;
<span style="color: #0000FF;">SET</span> ANSI_Nulls <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">SET</span> Ansi_Padding <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">SET</span> Ansi_Warnings <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">SET</span> ArithAbort <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">SET</span> Concat_Null_Yields_Null <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">SET</span> <span style="color: #0000FF;">NOCOUNT</span> <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">SET</span> Numeric_RoundAbort <span style="color: #0000FF;">OFF</span>;
<span style="color: #0000FF;">SET</span> Quoted_Identifier <span style="color: #0000FF;">ON</span>;
Go
&nbsp;
<span style="color: #0000FF;">ALTER</span> <span style="color: #0000FF;">PROCEDURE</span> dbo.<span style="color: #202020;">dba_indexDefragStandard_sp</span>
&nbsp;
    <span style="color: #008080;">/* Declare Parameters */</span>
      @minFragmentation     <span style="color: #0000FF;">FLOAT</span>           <span style="color: #808080;">=</span> <span style="color: #000;">10.0</span>
        <span style="color: #008080;">/* in percent, will not defrag if fragmentation
           less than specified */</span>
    , @rebuildThreshold     <span style="color: #0000FF;">FLOAT</span>           <span style="color: #808080;">=</span> <span style="color: #000;">30.0</span>
        <span style="color: #008080;">/* in percent, greater than @rebuildThreshold
           will result in rebuild instead of reorg */</span>
    , @executeSQL           <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
        <span style="color: #008080;">/* 1 = execute; 0 = print command only */</span>
    , @tableName            <span style="color: #0000FF;">VARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>   <span style="color: #808080;">=</span> Null 
        <span style="color: #008080;">/* Option to specify a table name */</span>
    , @printCommands        <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
        <span style="color: #008080;">/* 1 = print commands; 0 = do not print commands */</span>
    , @printFragmentation   <span style="color: #0000FF;">BIT</span>             <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
        <span style="color: #008080;">/* 1 = print fragmentation prior to defrag; 
           0 = do not print */</span>
    , @defragDelay          <span style="color: #0000FF;">CHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">8</span><span style="color: #808080;">&#41;</span>         <span style="color: #808080;">=</span> <span style="color: #FF0000;">'00:00:05'</span>
        <span style="color: #008080;">/* time to wait between defrag commands */</span>
<span style="color: #0000FF;">AS</span>
<span style="color: #008080;">/********************************************************************
    Name:       dba_indexDefragStandard_sp
&nbsp;
    Author:     Michelle F. Ufford
&nbsp;
    Purpose:    Defrags all indexes for the current database
&nbsp;
    Notes:      This script was designed for SQL Server 2005
                Standard edition.
&nbsp;
    CAUTION: Monitor transaction log if executing for the first time!
&nbsp;
      @minFragmentation     defaulted to 10%, will not defrag if
                            fragmentation if less than specified.
&nbsp;
      @rebuildThreshold     defaulted to 30% as recommended by
                            Microsoft in BOL;
                            &gt; than 30% will result in rebuild instead
&nbsp;
      @executeSQL           1 = execute the SQL generated by this proc;
                            0 = print command only
&nbsp;
      @tableName            Specify if you only want to defrag indexes
                            for a specific table
&nbsp;
      @printCommands        1 = print commands to screen;
                            0 = do not print commands
&nbsp;
      @printFragmentation   1 = print fragmentation to screen;
                            0 = do not print fragmentation
&nbsp;
      @defragDelay          time to wait between defrag commands;
                            gives the server some time to catch up
&nbsp;
    Called by:  SQL Agent Job or DBA
&nbsp;
    Date        Initials  Description
    ----------------------------------------------------------------
    2008-10-27  MFU       Initial Release
    2008-11-17  MFU       Added page_count to log table
                          , added @printFragmentation option
********************************************************************
    Exec dbo.dba_indexDefragStandard_sp
          @executeSQL         = 1
        , @printCommands      = 1
        , @minFragmentation   = 0
        , @printFragmentation = 1;
********************************************************************/</span>
&nbsp;
<span style="color: #0000FF;">SET</span> <span style="color: #0000FF;">NOCOUNT</span> <span style="color: #0000FF;">ON</span>;
<span style="color: #0000FF;">SET</span> XACT_Abort <span style="color: #0000FF;">ON</span>;
&nbsp;
<span style="color: #0000FF;">BEGIN</span>
&nbsp;
    <span style="color: #008080;">/* Declare our variables */</span>
    <span style="color: #0000FF;">DECLARE</span>   @objectID         <span style="color: #0000FF;">INT</span>
            , @indexID          <span style="color: #0000FF;">INT</span>
            , @schemaName       <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">130</span><span style="color: #808080;">&#41;</span>
            , @objectName       <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">130</span><span style="color: #808080;">&#41;</span>
            , @indexName        <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">130</span><span style="color: #808080;">&#41;</span>
            , @fragmentation    <span style="color: #0000FF;">FLOAT</span>
            , @pageCount        <span style="color: #0000FF;">INT</span>
            , @sqlCommand       <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">4000</span><span style="color: #808080;">&#41;</span>
            , @rebuildCommand   <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #000;">200</span><span style="color: #808080;">&#41;</span>
            , @dateTimeStart    <span style="color: #0000FF;">DATETIME</span>
            , @dateTimeEnd      <span style="color: #0000FF;">DATETIME</span>
            , @containsLOB      <span style="color: #0000FF;">BIT</span>;
&nbsp;
    <span style="color: #008080;">/* Just a little validation... */</span>
    <span style="color: #0000FF;">IF</span> @minFragmentation Not Between <span style="color: #000;">0.00</span> And <span style="color: #000;">100.0</span>
        <span style="color: #0000FF;">SET</span> @minFragmentation <span style="color: #808080;">=</span> <span style="color: #000;">10.0</span>;
&nbsp;
    <span style="color: #0000FF;">IF</span> @rebuildThreshold Not Between <span style="color: #000;">0.00</span> And <span style="color: #000;">100.0</span>
        <span style="color: #0000FF;">SET</span> @rebuildThreshold <span style="color: #808080;">=</span> <span style="color: #000;">30.0</span>;
&nbsp;
    <span style="color: #0000FF;">IF</span> @defragDelay Not Like <span style="color: #FF0000;">'00:[0-5][0-9]:[0-5][0-9]'</span>
        <span style="color: #0000FF;">SET</span> @defragDelay <span style="color: #808080;">=</span> <span style="color: #FF0000;">'00:00:05'</span>;
&nbsp;
    <span style="color: #008080;">/* Determine which indexes to defrag using our
       user-defined parameters */</span>
    <span style="color: #0000FF;">SELECT</span>
          <span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #0000FF;">AS</span> objectID
        , index_id <span style="color: #0000FF;">AS</span> indexID
        , avg_fragmentation_in_percent <span style="color: #0000FF;">AS</span> fragmentation
        , page_count 
        , <span style="color: #000;">0</span> <span style="color: #0000FF;">AS</span> <span style="color: #FF0000;">'defragStatus'</span>
            <span style="color: #008080;">/* 0 = unprocessed, 1 = processed */</span>
    <span style="color: #0000FF;">INTO</span> #indexDefragList
    <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">dm_db_index_physical_stats</span>
        <span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">DB_ID</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>, <span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#40;</span>@tableName<span style="color: #808080;">&#41;</span>, <span style="color: #808080;">NULL</span> , <span style="color: #808080;">NULL</span>, N<span style="color: #FF0000;">'Limited'</span><span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">WHERE</span> avg_fragmentation_in_percent <span style="color: #808080;">&gt;</span> @minFragmentation
        And index_id <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span>
    <span style="color: #0000FF;">OPTION</span> <span style="color: #808080;">&#40;</span>MaxDop <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #008080;">/* Create a clustered index to boost performance a little */</span>
    <span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">CLUSTERED</span> <span style="color: #0000FF;">INDEX</span> CIX_temp_indexDefragList
        <span style="color: #0000FF;">ON</span> #indexDefragList<span style="color: #808080;">&#40;</span>objectID, indexID<span style="color: #808080;">&#41;</span>;
&nbsp;
    <span style="color: #008080;">/* Begin our loop for defragging */</span>
    <span style="color: #0000FF;">WHILE</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #FF00FF;">COUNT</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">*</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">FROM</span> #indexDefragList
            <span style="color: #0000FF;">WHERE</span> defragStatus <span style="color: #808080;">=</span> <span style="color: #000;">0</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span>
    <span style="color: #0000FF;">BEGIN</span>
&nbsp;
        <span style="color: #008080;">/* Grab the most fragmented index first to defrag */</span>
        <span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">TOP</span> <span style="color: #000;">1</span>
              @objectID         <span style="color: #808080;">=</span> objectID
            , @fragmentation    <span style="color: #808080;">=</span> fragmentation
            , @indexID          <span style="color: #808080;">=</span> indexID
            , @pageCount        <span style="color: #808080;">=</span> page_count
        <span style="color: #0000FF;">FROM</span> #indexDefragList
        <span style="color: #0000FF;">WHERE</span> defragStatus <span style="color: #808080;">=</span> <span style="color: #000;">0</span>
        <span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> fragmentation <span style="color: #0000FF;">DESC</span>;
&nbsp;
        <span style="color: #008080;">/* Look up index information */</span>
        <span style="color: #0000FF;">SELECT</span> @objectName <span style="color: #808080;">=</span> <span style="color: #FF00FF;">QUOTENAME</span><span style="color: #808080;">&#40;</span>o.<span style="color: #202020;">name</span><span style="color: #808080;">&#41;</span>
             , @schemaName <span style="color: #808080;">=</span> <span style="color: #FF00FF;">QUOTENAME</span><span style="color: #808080;">&#40;</span>s.<span style="color: #202020;">name</span><span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">objects</span> <span style="color: #0000FF;">AS</span> o
        <span style="color: #0000FF;">Inner</span> Join sys.<span style="color: #202020;">schemas</span> <span style="color: #0000FF;">AS</span> s
            <span style="color: #0000FF;">ON</span> s.<span style="color: #202020;">schema_id</span> <span style="color: #808080;">=</span> o.<span style="color: #202020;">schema_id</span>
        <span style="color: #0000FF;">WHERE</span> o.<span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> @objectID;
&nbsp;
        <span style="color: #0000FF;">SELECT</span> @indexName <span style="color: #808080;">=</span> <span style="color: #FF00FF;">QUOTENAME</span><span style="color: #808080;">&#40;</span>name<span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">indexes</span>
        <span style="color: #0000FF;">WHERE</span> <span style="color: #FF00FF;">OBJECT_ID</span> <span style="color: #808080;">=</span> @objectID
            And index_id <span style="color: #808080;">=</span> @indexID
            And type <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span>;
&nbsp;
        <span style="color: #008080;">/* Look for LOBs */</span>
        <span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">TOP</span> <span style="color: #000;">1</span>
            @containsLOB <span style="color: #808080;">=</span> column_id
        <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">columns</span> <span style="color: #0000FF;">WITH</span> <span style="color: #808080;">&#40;</span>NOLOCK<span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">WHERE</span> 
            <span style="color: #808080;">&#91;</span><span style="color: #FF00FF;">OBJECT_ID</span><span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> @objectID
            And <span style="color: #808080;">&#40;</span>system_type_id In <span style="color: #808080;">&#40;</span><span style="color: #000;">34</span>, <span style="color: #000;">35</span>, <span style="color: #000;">99</span><span style="color: #808080;">&#41;</span>
            <span style="color: #008080;">-- 34 = image, 35 = text, 99 = ntext</span>
                    Or max_length <span style="color: #808080;">=</span> <span style="color: #808080;">-</span><span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>;
            <span style="color: #008080;">-- varbinary(max), varchar(max), nvarchar(max), xml</span>
&nbsp;
        <span style="color: #008080;">/* See if we should rebuild or reorganize; handle thusly */</span>
        <span style="color: #0000FF;">IF</span> @fragmentation <span style="color: #808080;">&lt;</span> @rebuildThreshold 
            Or IsNull<span style="color: #808080;">&#40;</span>@containsLOB, <span style="color: #000;">0</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span> 
            <span style="color: #008080;">-- Cannot rebuild if the table has one or more LOB</span>
            <span style="color: #0000FF;">SET</span> @sqlCommand <span style="color: #808080;">=</span> N<span style="color: #FF0000;">'Alter Index '</span> <span style="color: #808080;">+</span> @indexName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">' On '</span>
                <span style="color: #808080;">+</span> @schemaName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">'.'</span> <span style="color: #808080;">+</span> @objectName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">' ReOrganize;'</span>
        <span style="color: #0000FF;">ELSE</span>
            <span style="color: #0000FF;">SET</span> @sqlCommand <span style="color: #808080;">=</span> N<span style="color: #FF0000;">'Alter Index '</span> <span style="color: #808080;">+</span> @indexName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">' On '</span>
                <span style="color: #808080;">+</span> @schemaName <span style="color: #808080;">+</span> N<span style="color: #FF0000;">'.'</span> <span style="color: #808080;">+</span> @objectName <span style="color: #808080;">+</span>  <span style="color: #FF0000;">' Rebuild '</span>
                <span style="color: #808080;">+</span> <span style="color: #FF0000;">'With (MaxDop = 1)'</span>; <span style="color: #008080;">-- minimize impact on server</span>
&nbsp;
        <span style="color: #008080;">/* Are we executing the SQL?  If so, do it */</span>
        <span style="color: #0000FF;">IF</span> @executeSQL <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
        <span style="color: #0000FF;">BEGIN</span>
&nbsp;
            <span style="color: #008080;">/* Grab the time for logging purposes */</span>
            <span style="color: #0000FF;">SET</span> @dateTimeStart  <span style="color: #808080;">=</span> <span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>;
            <span style="color: #0000FF;">EXECUTE</span> <span style="color: #808080;">&#40;</span>@sqlCommand<span style="color: #808080;">&#41;</span>;
            <span style="color: #0000FF;">SET</span> @dateTimeEnd  <span style="color: #808080;">=</span> <span style="color: #FF00FF;">GETDATE</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>;
&nbsp;
            <span style="color: #008080;">/* Log our actions */</span>
            <span style="color: #0000FF;">INSERT</span> <span style="color: #0000FF;">INTO</span> dbo.<span style="color: #202020;">dba_indexDefragLog</span>
            <span style="color: #808080;">&#40;</span>
                  objectID
                , objectName
                , indexID
                , indexName
                , fragmentation
                , page_count
                , dateTimeStart
                , durationSeconds
            <span style="color: #808080;">&#41;</span>
            <span style="color: #0000FF;">SELECT</span>
                  @objectID
                , @objectName
                , @indexID
                , @indexName
                , @fragmentation
                , @pageCount
                , @dateTimeStart
                , <span style="color: #FF00FF;">DATEDIFF</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SECOND</span>, @dateTimeStart, @dateTimeEnd<span style="color: #808080;">&#41;</span>;
&nbsp;
            <span style="color: #008080;">/* Just a little breather for the server */</span>
            <span style="color: #0000FF;">WAITFOR</span> Delay @defragDelay;
&nbsp;
            <span style="color: #008080;">/* Print if specified to do so */</span>
            <span style="color: #0000FF;">IF</span> @printCommands <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
                <span style="color: #0000FF;">PRINT</span> N<span style="color: #FF0000;">'Executed: '</span> <span style="color: #808080;">+</span> @sqlCommand;
        <span style="color: #0000FF;">END</span>
        <span style="color: #0000FF;">ELSE</span>
        <span style="color: #008080;">/* Looks like we're not executing, just print
            the commands */</span>
        <span style="color: #0000FF;">BEGIN</span>
            <span style="color: #0000FF;">IF</span> @printCommands <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
                <span style="color: #0000FF;">PRINT</span> @sqlCommand;
        <span style="color: #0000FF;">END</span>
&nbsp;
        <span style="color: #008080;">/* Update our index defrag list when we've
            finished with that index */</span>
        <span style="color: #0000FF;">UPDATE</span> #indexDefragList
        <span style="color: #0000FF;">SET</span> defragStatus <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
        <span style="color: #0000FF;">WHERE</span> objectID  <span style="color: #808080;">=</span> @objectID
          And indexID   <span style="color: #808080;">=</span> @indexID;
&nbsp;
    <span style="color: #0000FF;">END</span>
&nbsp;
    <span style="color: #008080;">/* Do we want to output our fragmentation results? */</span>
    <span style="color: #0000FF;">IF</span> @printFragmentation <span style="color: #808080;">=</span> <span style="color: #000;">1</span>
        <span style="color: #0000FF;">SELECT</span> idl.<span style="color: #202020;">objectID</span>
            , o.<span style="color: #202020;">name</span> <span style="color: #0000FF;">As</span> <span style="color: #FF0000;">'tableName'</span>
            , idl.<span style="color: #202020;">indexID</span>
            , i.<span style="color: #202020;">name</span> <span style="color: #0000FF;">As</span> <span style="color: #FF0000;">'indexName'</span>
            , idl.<span style="color: #202020;">fragmentation</span>
            , idl.<span style="color: #202020;">page_count</span>
        <span style="color: #0000FF;">FROM</span> #indexDefragList <span style="color: #0000FF;">AS</span> idl
        <span style="color: #808080;">JOIN</span> sys.<span style="color: #202020;">objects</span> <span style="color: #0000FF;">AS</span> o
            <span style="color: #0000FF;">ON</span> idl.<span style="color: #202020;">objectID</span> <span style="color: #808080;">=</span> o.<span style="color: #FF00FF;">object_id</span>
        <span style="color: #808080;">JOIN</span> sys.<span style="color: #202020;">indexes</span> <span style="color: #0000FF;">As</span> i
            <span style="color: #0000FF;">ON</span> idl.<span style="color: #202020;">objectID</span> <span style="color: #808080;">=</span> i.<span style="color: #FF00FF;">object_id</span>
            <span style="color: #808080;">AND</span> idl.<span style="color: #202020;">indexID</span> <span style="color: #808080;">=</span> i.<span style="color: #202020;">index_id</span>;
&nbsp;
    <span style="color: #008080;">/* When everything is done, make sure to get rid of
        our temp table */</span>
    <span style="color: #0000FF;">DROP</span> <span style="color: #0000FF;">TABLE</span> #indexDefragList;
&nbsp;
    <span style="color: #0000FF;">SET</span> <span style="color: #0000FF;">NOCOUNT</span> <span style="color: #0000FF;">OFF</span>;
    <span style="color: #0000FF;">RETURN</span> <span style="color: #000;">0</span>
<span style="color: #0000FF;">END</span>
Go</pre></div></div>

<p>&nbsp;</p>
<p>For those who are having troubles with this script&#8230;</p>
<p>1) &#8220;Not all of my indexes were defragged!&#8221; or &#8220;Nothing happened when I executed this script.&#8221; </p>
<p>This script will only defrag those indexes that surpass the specified threshold.  If you&#8217;re not seeing your index in the output, try executing this:</p>

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

<p>Check to see what your index&#8217;s fragmentation level is.  Maybe it&#8217;s not as fragmented as you feared.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>2) &#8220;My indexes are still fragmented after running this script.&#8221;</p>
<p>  To quote The Powers That Be (aka Microsoft)&#8230;</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.&#8221;  &#8212; <a href="http://msdn.microsoft.com/en-us/library/ms189858.aspx" target="_blank">Reorganizing and Rebuilding Indexes</a></p></blockquote>
<p>3) &#8220;Can I use this in my production environment?&#8221;</p>
<p>That really depends on your environment.  I&#8217;ve successfully used this in some very large production environments.  However, I wouldn&#8217;t exactly recommend executing the script in the middle of a business day on a billion+ row, heavily fragmented, unpartitioned table, either.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </p>
<p>If you&#8217;re not sure what the impact will be, execute the commands-only version of the script&#8230;</p>

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

<p>&#8230; then execute the statements one at a time.  Make sure you monitor tempdb and the transaction log to ensure you don&#8217;t have any space issues.</p>
<p>If you have any additional questions or suggestions for this script, leave me a comment and I&#8217;ll be happy to help.  <img src='http://sqlfool.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2008/11/updated-index-defrag-script-2005-2008/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>Performance Comparison of Singleton, XML, and TVP Inserts</title>
		<link>http://sqlfool.com/2008/11/performance-comparison-of-singleton-xml-and-tvp-inserts/</link>
		<comments>http://sqlfool.com/2008/11/performance-comparison-of-singleton-xml-and-tvp-inserts/#comments</comments>
		<pubDate>Fri, 14 Nov 2008 01:26:33 +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[2008]]></category>
		<category><![CDATA[large]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://sqlfool.com/?p=156</guid>
		<description><![CDATA[As promised, today I took a look at the performance of bulk inserts using XML and Table-Valued Parameters. I also compared it against singleton inserts to show the value in the bulk-insert approach. My tests were pretty simple: insert 100 records using each method. Each test was executed 10 times to ensure consistency. The duration [...]]]></description>
			<content:encoded><![CDATA[<p>As promised, today I took a look at the performance of bulk inserts using XML and Table-Valued Parameters.  I also compared it against singleton inserts to show the value in the bulk-insert approach.</p>
<p>My tests were pretty simple: insert 100 records using each method.  Each test was executed 10 times to ensure consistency.  The duration was recorded in microseconds.  </p>
<p>The goal was to compare the performance of the inserts.  Because I was executing this entire test within SQL Server, I had to isolate only the actual insert transactions and ignore everything else, such as the loading of the data; that work would normally be performed by the calling application.</p>
<p>So without further ado&#8230; screenshots of the Profiler traces: (click to enlarge)</p>
<div class="wp-caption alignnone" style="width: 753px"><a href="http://www.sqlfool.com/blogImages/20081113/SingletonInsert.gif"><img alt="TVP" src="http://www.sqlfool.com/blogImages/20081113/SingletonInsert.gif" title="Single Insert Method" width="400" height="200" /></a><p class="wp-caption-text">Single Insert Method</p></div>
<div class="wp-caption alignnone" style="width: 753px"><a href="http://www.sqlfool.com/blogImages/20081113/XML.gif"><img alt="TVP" src="http://www.sqlfool.com/blogImages/20081113/XML.gif" title="XML Method" width="400" height="200" /></a><p class="wp-caption-text">XML Method</p></div>
<div class="wp-caption alignnone" style="width: 753px"><a href="http://www.sqlfool.com/blogImages/20081113/TVP.gif"><img alt="TVP" src="http://www.sqlfool.com/blogImages/20081113/TVP.gif" title="Table-Valued Parameter Method" width="400" height="200" /></a><p class="wp-caption-text">Table-Valued Parameter Method</p></div>
<p><strong>Summary</strong></p>
<table border="1" cellspacing="0" cellpadding="5">
<tr>
<td>Method</td>
<td>Avg CPU</td>
<td>Avg Reads</td>
<td>Avg Writes</td>
<td>Avg Duration (micro)</td>
</tr>
<tr>
<td>Singleton Method</td>
<td>3</td>
<td>202</td>
<td>0</td>
<td>13378</td>
</tr>
<tr>
<td>XML Method</td>
<td>0</td>
<td>222</td>
<td>0</td>
<td>3124</td>
</tr>
<tr>
<td>TVP Method</td>
<td>1</td>
<td>207</td>
<td>0</td>
<td>780</td>
</tr>
</table>
<p>&nbsp;</p>
<p>As expected, both the XML and the TVP method performed significantly better than the single-insert method.  As hoped, the table-valued parameter arguably performed the best of all 3. </p>
]]></content:encoded>
			<wfw:commentRss>http://sqlfool.com/2008/11/performance-comparison-of-singleton-xml-and-tvp-inserts/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

