<?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>JohnSterrett.com &#187; Scripts</title>
	<atom:link href="http://johnsterrett.com/category/scripts/feed/" rel="self" type="application/rss+xml" />
	<link>http://johnsterrett.com</link>
	<description>My journey though SQL and life!</description>
	<lastBuildDate>Thu, 17 May 2012 06:17:50 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.2</generator>
		<item>
		<title>T-SQL Tuesday: What&#8217;s Currently Running?</title>
		<link>http://johnsterrett.com/2011/12/13/t-sql-tuesday-whats-currently-running/</link>
		<comments>http://johnsterrett.com/2011/12/13/t-sql-tuesday-whats-currently-running/#comments</comments>
		<pubDate>Tue, 13 Dec 2011 13:41:09 +0000</pubDate>
		<dc:creator>johnsterrett</dc:creator>
				<category><![CDATA[Scripts]]></category>
		<category><![CDATA[SQLServerPedia Syndication]]></category>
		<category><![CDATA[DMV]]></category>
		<category><![CDATA[T-SQL]]></category>

		<guid isPermaLink="false">http://johnsterrett.com/?p=946</guid>
		<description><![CDATA[My good friend Allen White is hosting this months installment of #TSQL2sDay so I am motivated to jump in. #TSQL2sDay is the creation of Adam Machanic. The concept is simple, about a week before the second Tuesday of the month a theme will &#8230; <a href="http://johnsterrett.com/2011/12/13/t-sql-tuesday-whats-currently-running/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fjohnsterrett.com%2F2011%2F12%2F13%2Ft-sql-tuesday-whats-currently-running%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fjohnsterrett.com%2F2011%2F12%2F13%2Ft-sql-tuesday-whats-currently-running%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>My good friend <a href="http://sqlblog.com/blogs/allen_white/default.aspx">Allen White</a> is hosting this months installment of #TSQL2sDay so I am motivated to jump in. #TSQL2sDay is the creation of Adam Machanic. The concept is simple, about a week before the second Tuesday of the month a theme will be posted.  Any blogger that wishes to participate is invited to write a post on the chosen topic and any post that is related to both SQL Server and the theme is fair game.The challenge for <a href="http://sqlblog.com/blogs/allen_white/archive/2011/12/05/t-sql-tuesday-025-invitation-to-share-your-tricks.aspx">this month&#8217;s T-SQL Tuesday</a> is: <strong>What T-SQL tricks do you use today to make your job easier?</strong></p>
<h2>What&#8217;s Currently Running?</h2>
<p>One of my favorite tricks is actually just a little script I have in my toolbox to find out <a href="http://johnsterrett.com/2011/12/13/t-sql-tuesday-whats-currently-running/">what queries are currently running right now</a>. In fact I have had quite a few people ask me the for this script so I am glad to share it in this blog post.  With SQL Server 2005 and above  SQL Server provides Database Management Views that give you direct access to executing requests and running process. The following query uses sys.dm_exec_request, sys.sysprocesses. We will also use cross apply to get the query text from sys.dm_exec_sql_text and the execution plan from sys.dm_exec_query_plan.</p>
<h2>The Good Stuff&#8230;</h2>
<p><strong>{UPDATE: 1/1/2012 &#8211; Replaced sysprocesses with sys.dm_exec_sessions as recommended by Phil in the comments}</strong></p>
<pre class="brush: plain; title: ;">
-- Do not lock anything, and do not get held up by any locks.
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

SELECT [Spid] = sp.session_Id
,er.request_id
,er.command
,[Database] = DB_NAME(er.database_id)
,[User] = login_name
,er.blocking_session_id
,[Status] = er.status
,[Wait] = wait_type
,CAST('&lt;?query --'+CHAR(13)+SUBSTRING(qt.text,
(er.statement_start_offset / 2)+1,     ((CASE er.statement_end_offset
WHEN -1 THEN DATALENGTH(qt.text)    ELSE er.statement_end_offset
END - er.statement_start_offset)/2) + 1)+CHAR(13)+'--?&gt;' AS xml) as sql_statement
,[Parent Query] = qt.text
,p.query_plan
,er.cpu_time
, er.reads
, er.writes
, er.Logical_reads
, er.row_count
, Program = program_name
,Host_name
,start_time
FROM sys.dm_exec_requests er INNER JOIN sys.dm_exec_sessions sp ON er.session_id = sp.session_id
CROSS APPLY sys.dm_exec_sql_text(er.sql_handle)as qt
cross apply sys.dm_exec_query_plan(er.plan_handle) p
WHERE sp.is_user_process = 1
/* sp.session_Id &gt; 50
-- Ignore system spids. -- */
AND sp.session_Id NOT IN (@@SPID)
ORDER BY 1, 2
</pre>
<div class="shr-publisher-946"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://johnsterrett.com/2011/12/13/t-sql-tuesday-whats-currently-running/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Using Profiler to trace database calls from third-party applications</title>
		<link>http://johnsterrett.com/2010/06/16/using-profiler-to-trace-database-calls-from-third-party-applications/</link>
		<comments>http://johnsterrett.com/2010/06/16/using-profiler-to-trace-database-calls-from-third-party-applications/#comments</comments>
		<pubDate>Wed, 16 Jun 2010 15:00:55 +0000</pubDate>
		<dc:creator>johnsterrett</dc:creator>
				<category><![CDATA[Scripts]]></category>
		<category><![CDATA[SQL Server 2008]]></category>

		<guid isPermaLink="false">http://johnsterrett.com/?p=234</guid>
		<description><![CDATA[Today using profiler to trace database calls from third-party applications was published on www.mssqltips.com.  Hopefully, this tip will help some people understand why profiler is bacon.  In this example I trace two queries with Management Studio.  Speaking of Management Studio, have you &#8230; <a href="http://johnsterrett.com/2010/06/16/using-profiler-to-trace-database-calls-from-third-party-applications/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fjohnsterrett.com%2F2010%2F06%2F16%2Fusing-profiler-to-trace-database-calls-from-third-party-applications%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fjohnsterrett.com%2F2010%2F06%2F16%2Fusing-profiler-to-trace-database-calls-from-third-party-applications%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Today <a href="http://www.mssqltips.com/tip.asp?tip=2040">using profiler to trace database calls from third-party applications </a>was published on <a href="http://www.mssqltips.com">www.mssqltips.com</a>.  Hopefully, this tip will help some people understand why profiler is bacon.  In this example I trace two queries with Management Studio.  Speaking of Management Studio, have you ever wondered what queries are executed by your favorite features of Management Studio?  You can follow the steps in this tip to do that too.</p>
<p>This is my fist tip published at <a href="http://www.mssqltips.com">www.mssqltips.com</a>.  I look forward to publishing tips on a monthly basis.</p>
<div class="shr-publisher-234"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://johnsterrett.com/2010/06/16/using-profiler-to-trace-database-calls-from-third-party-applications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>When was that object modified?</title>
		<link>http://johnsterrett.com/2009/10/06/when-was-that-object-modified/</link>
		<comments>http://johnsterrett.com/2009/10/06/when-was-that-object-modified/#comments</comments>
		<pubDate>Tue, 06 Oct 2009 16:37:31 +0000</pubDate>
		<dc:creator>johnsterrett</dc:creator>
				<category><![CDATA[Scripts]]></category>
		<category><![CDATA[SQLServerPedia Syndication]]></category>
		<category><![CDATA[DMV]]></category>
		<category><![CDATA[T-SQL]]></category>

		<guid isPermaLink="false">http://www.johnsterrett.com/?p=81</guid>
		<description><![CDATA[Yes, every once in a while when I am deploying an application I ask myself the following question.  What database objects (tables, stored procedures, functions etc..) did I modify with this release?   Ideally this is documented in the release plan but I &#8230; <a href="http://johnsterrett.com/2009/10/06/when-was-that-object-modified/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fjohnsterrett.com%2F2009%2F10%2F06%2Fwhen-was-that-object-modified%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fjohnsterrett.com%2F2009%2F10%2F06%2Fwhen-was-that-object-modified%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Yes, every once in a while when I am deploying an application I ask myself the following question.  What database objects (tables, stored procedures, functions etc..) did I modify with this release?  </p>
<p>Ideally this is documented in the release plan but I will admit I have been known to slip every once in a while.  Therefore, I am showcasing a query that can provide help.  This query was written by <a href="http://stackoverflow.com/users/16473/gordon-bell">Gordon Bell</a> and it can be found <a href="http://stackoverflow.com/questions/121243/hidden-features-of-sql-server">here</a>.   It uses the sys.objects DMV that are included in SQL 2005 &amp; 2008. </p>
<p>I will defiantly throw this script into my bag of tricks. </p>
<pre class="csharpcode"><span class="kwrd">select</span> name, modify_date,
<span class="kwrd">case</span> <span class="kwrd">when</span> type_desc = <span class="str">'USER_TABLE'</span> <span class="kwrd">then</span> <span class="str">'Table'</span>
<span class="kwrd">when</span> type_desc = <span class="str">'SQL_STORED_PROCEDURE'</span> <span class="kwrd">then</span> <span class="str">'Stored Procedure'</span>
<span class="kwrd">when</span> type_desc <span class="kwrd">in</span> (<span class="str">'SQL_INLINE_TABLE_VALUED_FUNCTION'</span>, <span class="str">'SQL_SCALAR_FUNCTION'</span>,
<span class="str">'SQL_TABLE_VALUED_FUNCTION'</span>) <span class="kwrd">then</span> <span class="str">'Function'</span>
<span class="kwrd">end</span> <span class="kwrd">as</span> type_desc
<span class="kwrd">from</span> sys.objects
<span class="kwrd">where</span> type <span class="kwrd">in</span> (<span class="str">'U'</span>, <span class="str">'P'</span>, <span class="str">'FN'</span>, <span class="str">'IF'</span>, <span class="str">'TF'</span>)
<span class="kwrd">and</span> is_ms_shipped = 0
<span class="kwrd">order</span> <span class="kwrd">by</span> 2 desc</pre>
<p><!--</p>
<p>.csharpcode, .csharpcode pre<br />
{<br />
font-size: small;<br />
color: black;<br />
font-family: consolas, "Courier New", courier, monospace;<br />
background-color: #ffffff;<br />
/*white-space: pre;*/<br />
}<br />
.csharpcode pre { margin: 0em; }<br />
.csharpcode .rem { color: #008000; }<br />
.csharpcode .kwrd { color: #0000ff; }<br />
.csharpcode .str { color: #006080; }<br />
.csharpcode .op { color: #0000c0; }<br />
.csharpcode .preproc { color: #cc6633; }<br />
.csharpcode .asp { background-color: #ffff00; }<br />
.csharpcode .html { color: #800000; }<br />
.csharpcode .attr { color: #ff0000; }<br />
.csharpcode .alt<br />
{<br />
background-color: #f4f4f4;<br />
width: 100%;<br />
margin: 0em;<br />
}<br />
.csharpcode .lnum { color: #606060; } --></p>
<div class="shr-publisher-81"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://johnsterrett.com/2009/10/06/when-was-that-object-modified/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Get index fragmentation statistics</title>
		<link>http://johnsterrett.com/2009/09/30/get-index-fragmentation-statistics/</link>
		<comments>http://johnsterrett.com/2009/09/30/get-index-fragmentation-statistics/#comments</comments>
		<pubDate>Wed, 30 Sep 2009 15:31:51 +0000</pubDate>
		<dc:creator>johnsterrett</dc:creator>
				<category><![CDATA[Scripts]]></category>
		<category><![CDATA[SQL Server 2008]]></category>
		<category><![CDATA[SQLServerPedia Syndication]]></category>
		<category><![CDATA[DMV]]></category>
		<category><![CDATA[indexes]]></category>

		<guid isPermaLink="false">http://www.johnsterrett.com/?p=74</guid>
		<description><![CDATA[I recently attended a Pittsburgh SQL Server user group meeting where Brent Ozar gave a presentation on the silent performance killer.  This motivated me to create a stored procedure that could leverage the DMVs in SQL 2005/2008 to gather index &#8230; <a href="http://johnsterrett.com/2009/09/30/get-index-fragmentation-statistics/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fjohnsterrett.com%2F2009%2F09%2F30%2Fget-index-fragmentation-statistics%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fjohnsterrett.com%2F2009%2F09%2F30%2Fget-index-fragmentation-statistics%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>I recently attended a Pittsburgh SQL Server user group meeting where <a href="http://www.brentozar.com/">Brent Ozar</a> gave a presentation on the <a href="http://www.brentozar.com/archive/2009/02/index-fragmentation-findings-part-1-the-basics/">silent performance killer</a>.  This motivated me to create a stored procedure that could leverage the DMVs in SQL 2005/2008 to gather index fragmentation statistics for all databases on a given server.</p>
<h2>Goal</h2>
<p>The goal is very simple.  Build a query that could be scheduled to grab statistics that are helpful towards determining if an index needs to be defragged or reorganized.  I would like to throw these results into a table so I could analyze them at a later date.  I would also like to monitor the fill factor and padding to determine if I need to make changes and to analyze if the changes are really helpful.</p>
<h2>Download Scripts</h2>
<p>The following script uses the following DMV’s <a href="http://msdn.microsoft.com/en-us/library/ms188917.aspx">sys.dm_db_index_physical_stats</a>, <a href="http://msdn.microsoft.com/en-us/library/ms190324.aspx">sys.objects</a> and <a href="http://msdn.microsoft.com/en-us/library/ms173760.aspx">sys.indexes</a> and this script is provided as is.</p>
<div id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:67868802-4c0a-4d46-8baf-3a5ecca4eca9" class="wlWriterEditableSmartContent" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<p><a href="http://johnsterrett.com/img/Getindexfragmentationstatistics_B1B1/GetStatsForIndexesStoredProcedure.sql" target="_blank"></a></div>
<div id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:02649ce7-775f-4a18-9475-092edfca84fc" class="wlWriterEditableSmartContent" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<p>To download the script <a href="http://johnsterrett.com/img/Getindexfragmentationstatistics_B1B1/GetStatsForIndexesStoredProcedure_3.sql" target="_blank">click here</a></div>
<div id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:c9feced2-11f3-426e-8854-f3051c9eb67b" class="wlWriterEditableSmartContent" style="padding-right: 0px; display: inline; padding-left: 0px; float: left; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<p>To download the create table script for the table used <a href="http://johnsterrett.com/img/Getindexfragmentationstatistics_B1B1/SQLTableIndexStats.sql" target="_blank">click here</a></div>
<p><BR/></p>
<h2>Table Definition</h2>
<p>The following is an explanation of the columns.  The following descriptions come from MSDN.</p>
<table border="3" cellspacing="0" cellpadding="2" width="508">
<tbody>
<tr>
<td width="166" valign="top">
<p align="center"><strong>Column Name</strong></p>
</td>
<td width="336" valign="top">
<p align="center"><strong>Description</strong></p>
</td>
</tr>
<tr>
<td width="167" valign="top">databaseName</td>
<td width="336" valign="top"><strong></strong></p>
<p>Name of database, unique within an instance of SQL Server.</td>
</tr>
<tr>
<td width="167" valign="top">objectName</td>
<td width="336" valign="top">Object name.</td>
</tr>
<tr>
<td width="167" valign="top">indexName</td>
<td width="336" valign="top">Name of the index. <strong>name</strong> is unique only within the object.</p>
<p>NULL = Heap</td>
</tr>
<tr>
<td width="167" valign="top">partitionNumber</td>
<td width="336" valign="top">1-based partition number within the owning object; a table, view, or index.</p>
<p>1 = Nonpartitioned index or heap.</td>
</tr>
<tr>
<td width="167" valign="top">fragmentation</td>
<td width="336" valign="top">Logical fragmentation for indexes, or extent fragmentation for heaps in the IN_ROW_DATA allocation unit.</p>
<p>The value is measured as a percentage and takes into account multiple files. For definitions of logical and extent fragmentation, see Remarks.</p>
<p>0 for LOB_DATA and ROW_OVERFLOW_DATA allocation units.</p>
<p>NULL for heaps when <em>mode</em> = SAMPLED.</td>
</tr>
<tr>
<td width="167" valign="top">fill_factor</td>
<td width="336" valign="top">&gt; 0 = FILLFACTOR percentage used when the index was created or rebuilt.</p>
<p>0 = Default value</td>
</tr>
<tr>
<td width="167" valign="top">is_padded</td>
<td width="336" valign="top">1 = PADINDEX is ON.</p>
<p>0 = PADINDEX is OFF.</td>
</tr>
<tr>
<td width="167" valign="top">type_desc</td>
<td width="336" valign="top">Description of index type:</p>
<p>HEAP<br />
CLUSTERED<br />
NONCLUSTERED<br />
XML<br />
SPATIAL</td>
</tr>
<tr>
<td width="167" valign="top">page_count</td>
<td width="336" valign="top">Total number of index or data pages.</p>
<p>For an index, the total number of index pages in the current level of the b-tree in the IN_ROW_DATA allocation unit.</p>
<p>For a heap, the total number of data pages in the IN_ROW_DATA allocation unit.</p>
<p>For LOB_DATA or ROW_OVERFLOW_DATA allocation units, total number of pages in the allocation unit.</td>
</tr>
<tr>
<td width="167" valign="top">date</td>
<td width="336" valign="top">this is the current date GETDATE()</td>
</tr>
</tbody>
</table>
<h2>Script</h2>
<div class="csharpcode">
<pre><span class="lnum">   1:  </span><span class="kwrd">ALTER</span> <span class="kwrd">PROCEDURE</span> [dbo].[GetStatsForIndexes]</pre>
<pre><span class="lnum">   2:  </span>    @PageCount <span class="kwrd">INT</span> = 100</pre>
<pre><span class="lnum">   3:  </span></pre>
<pre><span class="lnum">   4:  </span><span class="kwrd">AS</span></pre>
<pre><span class="lnum">   5:  </span><span class="kwrd">BEGIN</span></pre>
<pre><span class="lnum">   6:  </span>    <span class="rem">-- SET NOCOUNT ON added to prevent extra result sets from</span></pre>
<pre><span class="lnum">   7:  </span>    <span class="rem">-- interfering with SELECT statements.</span></pre>
<pre><span class="lnum">   8:  </span>    <span class="kwrd">SET</span> NOCOUNT <span class="kwrd">ON</span>;</pre>
<pre><span class="lnum">   9:  </span></pre>
<pre><span class="lnum">  10:  </span>    <span class="rem">-- Declare varables</span></pre>
<pre><span class="lnum">  11:  </span>    <span class="kwrd">DECLARE</span> @dbID <span class="kwrd">INT</span>, @dbName <span class="kwrd">VARCHAR</span>(128), @<span class="kwrd">SQL</span> NVARCHAR(<span class="kwrd">MAX</span>)</pre>
<pre><span class="lnum">  12:  </span></pre>
<pre><span class="lnum">  13:  </span>    <span class="rem">-- Create a temp table to store all active databases</span></pre>
<pre><span class="lnum">  14:  </span>    <span class="kwrd">CREATE</span> <span class="kwrd">TABLE</span> #databaseList</pre>
<pre><span class="lnum">  15:  </span>    (</pre>
<pre><span class="lnum">  16:  </span>          databaseID        <span class="kwrd">INT</span></pre>
<pre><span class="lnum">  17:  </span>        , databaseName      <span class="kwrd">VARCHAR</span>(128)</pre>
<pre><span class="lnum">  18:  </span>    );</pre>
<pre><span class="lnum">  19:  </span></pre>
<pre><span class="lnum">  20:  </span>    <span class="rem">-- we only want non-system databases who are currenlty online</span></pre>
<pre><span class="lnum">  21:  </span>    INSERT <span class="kwrd">INTO</span> #databaseList (databaseID, databaseName)</pre>
<pre><span class="lnum">  22:  </span>    <span class="kwrd">SELECT</span> d.database_id, d.name <span class="kwrd">FROM</span> sys.databases d <span class="kwrd">where</span> d.[<span class="kwrd">state</span>] = 0 <span class="kwrd">and</span> d.database_id &gt; 4</pre>
<pre><span class="lnum">  23:  </span></pre>
<pre><span class="lnum">  24:  </span></pre>
<pre><span class="lnum">  25:  </span>    <span class="rem">-- Loop through all databases </span></pre>
<pre><span class="lnum">  26:  </span>       <span class="kwrd">WHILE</span> (<span class="kwrd">SELECT</span> <span class="kwrd">COUNT</span>(*) <span class="kwrd">FROM</span> #databaseList) &gt; 0  <span class="kwrd">BEGIN</span></pre>
<pre><span class="lnum">  27:  </span></pre>
<pre><span class="lnum">  28:  </span>           <span class="rem">-- get a database id</span></pre>
<pre><span class="lnum">  29:  </span>        <span class="kwrd">SELECT</span> <span class="kwrd">TOP</span> 1 @dbID = databaseID, @dbName = databaseName</pre>
<pre><span class="lnum">  30:  </span>        <span class="kwrd">FROM</span> #databaseList;</pre>
<pre><span class="lnum">  31:  </span></pre>
<pre><span class="lnum">  32:  </span>            <span class="kwrd">SET</span> @<span class="kwrd">SQL</span> = <span class="str">'INSERT INTO DBA_Tools.dbo.IDX_FRAG (databaseName, ObjectName, indexName, partitionNumber, fragmentation, fill_factor, is_padded, type_desc, page_count, [date])</span></pre>
<pre><span class="lnum">  33:  </span>                SELECT</pre>
<pre><span class="lnum">  34:  </span>                  db.name AS databaseName</pre>
<pre><span class="lnum">  35:  </span>                , obj.name AS ObjectName</pre>
<pre><span class="lnum">  36:  </span>                , idx.name AS indexName</pre>
<pre><span class="lnum">  37:  </span>                , ps.partition_number AS partitionNumber</pre>
<pre><span class="lnum">  38:  </span>                , ps.avg_fragmentation_in_percent AS fragmentation</pre>
<pre><span class="lnum">  39:  </span>                ,idx.fill_factor</pre>
<pre><span class="lnum">  40:  </span>                ,idx.is_padded</pre>
<pre><span class="lnum">  41:  </span>                ,idx.type_desc</pre>
<pre><span class="lnum">  42:  </span>                , ps.page_count</pre>
<pre><span class="lnum">  43:  </span>                , GETDATE() as [date]</pre>
<pre><span class="lnum">  44:  </span>            FROM sys.databases db</pre>
<pre><span class="lnum">  45:  </span>              INNER JOIN sys.dm_db_index_physical_stats ('+<span class="kwrd">CAST</span>(@dbID <span class="kwrd">AS</span> <span class="kwrd">VARCHAR</span>(10))+<span class="str">', NULL, NULL , NULL, N'</span><span class="str">'Limited'</span><span class="str">') ps</span></pre>
<pre><span class="lnum">  46:  </span>                  ON db.database_id = ps.database_id</pre>
<pre><span class="lnum">  47:  </span>              INNER JOIN '+ @dbName+<span class="str">'.sys.objects obj ON obj.object_id = ps.object_id</span></pre>
<pre><span class="lnum">  48:  </span>              INNER JOIN '+ @dbName+<span class="str">'.sys.indexes idx ON idx.index_id = ps.index_id AND idx.object_id = ps.object_id</span></pre>
<pre><span class="lnum">  49:  </span>            WHERE ps.index_id &gt; 0</pre>
<pre><span class="lnum">  50:  </span>               AND ps.page_count &gt; 100</pre>
<pre><span class="lnum">  51:  </span>            ORDER BY page_count desc</pre>
<pre><span class="lnum">  52:  </span>            OPTION (MaxDop 1);'</pre>
<pre><span class="lnum">  53:  </span></pre>
<pre><span class="lnum">  54:  </span>        <span class="kwrd">EXECUTE</span> sp_executesql @<span class="kwrd">SQL</span></pre>
<pre><span class="lnum">  55:  </span>        <span class="rem">-- remove the database from the databases table</span></pre>
<pre><span class="lnum">  56:  </span>        <span class="kwrd">DELETE</span> <span class="kwrd">FROM</span> #databaseList <span class="kwrd">WHERE</span> databaseID = @dbID</pre>
<pre><span class="lnum">  57:  </span></pre>
<pre><span class="lnum">  58:  </span>        <span class="rem">-- get the next database in the databases table</span></pre>
<pre><span class="lnum">  59:  </span>        <span class="kwrd">SELECT</span> <span class="kwrd">TOP</span> 1 @dbID = databaseID, @dbName = databaseName</pre>
<pre><span class="lnum">  60:  </span>        <span class="kwrd">FROM</span> #databaseList;</pre>
<pre><span class="lnum">  61:  </span></pre>
<pre><span class="lnum">  62:  </span>    <span class="kwrd">END</span></pre>
<pre><span class="lnum">  63:  </span>    <span class="rem">-- temp table is no longer needed, so we will kill it.</span></pre>
<pre><span class="lnum">  64:  </span>    <span class="kwrd">DROP</span> <span class="kwrd">TABLE</span> #databaseList;</pre>
<pre><span class="lnum">  65:  </span><span class="kwrd">END</span></pre>
</div>
<p><!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } --> <!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } --></p>
<div class="shr-publisher-74"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://johnsterrett.com/2009/09/30/get-index-fragmentation-statistics/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Converting a vertical table to horizontal table</title>
		<link>http://johnsterrett.com/2009/09/24/converting-a-vertical-table-to-horizontal-table/</link>
		<comments>http://johnsterrett.com/2009/09/24/converting-a-vertical-table-to-horizontal-table/#comments</comments>
		<pubDate>Fri, 25 Sep 2009 00:45:00 +0000</pubDate>
		<dc:creator>johnsterrett</dc:creator>
				<category><![CDATA[Scripts]]></category>
		<category><![CDATA[SQLServerPedia Syndication]]></category>
		<category><![CDATA[T-SQL]]></category>

		<guid isPermaLink="false">http://www.johnsterrett.com/?p=55</guid>
		<description><![CDATA[Last week I received a request to convert a vertical table from a vendor application into a horizontal table.  There was one catch, the vertical table included text columns that needed to be pivoted horizontally.  The following was my plan &#8230; <a href="http://johnsterrett.com/2009/09/24/converting-a-vertical-table-to-horizontal-table/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fjohnsterrett.com%2F2009%2F09%2F24%2Fconverting-a-vertical-table-to-horizontal-table%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fjohnsterrett.com%2F2009%2F09%2F24%2Fconverting-a-vertical-table-to-horizontal-table%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Last week I received a request to convert a vertical table from a vendor application into a horizontal table.  There was one catch, the vertical table included text columns that needed to be pivoted horizontally.  The following was my plan for tackling this request.</p>
<ol>
<li>You must figure out how many columns are required for the worst case scenario in you horizontal table.  You can do this by multiplying the columns being pivoted by the rows in the vertical table. In this example you know the worst case is eight (see figure two.)  <em><strong>In this example we will assume that you will not know how many columns are needed.</strong> </em></li>
<li>Now we will use dynamic sql to create our new table that will support the columns needed in the horizontal table.</li>
<li>Next we will create a cursor that will loop through the vertical table to create and execute insert statements to populate the horizontal table.</li>
</ol>
<p>Example of vertical table (Input)</p>
<table border="0" cellspacing="0" cellpadding="2" width="392">
<tbody>
<tr>
<td width="100" valign="top"><strong><span style="text-decoration: underline;">ManagerName</span></strong></td>
<td width="100" valign="top"><strong><span style="text-decoration: underline;">ManagerEmail</span></strong></td>
<td width="93" valign="top"><strong><span style="text-decoration: underline;">Review</span></strong></td>
<td width="97" valign="top"><strong><span style="text-decoration: underline;">Employee</span></strong></td>
</tr>
<tr>
<td width="102" valign="top">Jack Wilson</td>
<td width="102" valign="top"><a href="mailto:jwilson@comp.com">jwilson@comp.com</a></td>
<td width="93" valign="top">2009 Review</td>
<td width="97" valign="top">John Sterrett</td>
</tr>
<tr>
<td width="101" valign="top">Jack Wilson</td>
<td width="103" valign="top"><a href="mailto:jwilson@comp.com">jwilson@comp.com</a></td>
<td width="93" valign="top">2009 Review</td>
<td width="97" valign="top">Bo Smith</td>
</tr>
<tr>
<td width="102" valign="top">Hank Reed</td>
<td width="103" valign="top"><a href="mailto:hreed@comp.com">hreed@comp.com</a></td>
<td width="93" valign="top">2008 Review</td>
<td width="97" valign="top">John Sterrett</td>
</tr>
<tr>
<td width="102" valign="top">Jack Wilson</td>
<td width="103" valign="top"><a href="mailto:jwilson@comp.com">jwilson@comp.com</a></td>
<td width="93" valign="top">2008 Review</td>
<td width="97" valign="top">Chris Cupp</td>
</tr>
</tbody>
</table>
<p>Figure 1 – The vertical table</p>
<p>The following is the horizontal table (output)</p>
<table border="0" cellspacing="0" cellpadding="2" width="400">
<tbody>
<tr>
<td width="50" valign="top"><strong><span style="text-decoration: underline;">ManagerName</span></strong></td>
<td width="50" valign="top"><strong><span style="text-decoration: underline;">ManagerEmail</span></strong></td>
<td width="50" valign="top"><strong><span style="text-decoration: underline;">Review1</span></strong></td>
<td width="50" valign="top"><strong><span style="text-decoration: underline;">Employee1</span></strong></td>
<td width="50" valign="top"><strong><span style="text-decoration: underline;">Review2</span></strong></td>
<td width="50" valign="top"><strong><span style="text-decoration: underline;">Employee2</span></strong></td>
<td width="50" valign="top"><strong><span style="text-decoration: underline;">Review3</span></strong></td>
<td width="50" valign="top"><strong><span style="text-decoration: underline;">Employee3</span></strong></td>
</tr>
<tr>
<td width="50" valign="top">Jack Wilson</td>
<td width="50" valign="top"><a href="mailto:jwilson@comp.com">jwilson@comp.com</a></td>
<td width="50" valign="top">2009 Review</td>
<td width="50" valign="top">John Sterrett</td>
<td width="50" valign="top">2009 Review</td>
<td width="50" valign="top">Bo Smith</td>
<td width="50" valign="top">2008 Review</td>
<td width="50" valign="top">John Sterrett</td>
</tr>
<tr>
<td width="50" valign="top">Hank Reed</td>
<td width="50" valign="top"><a href="mailto:hreed@comp.com">hreed@comp.com</a></td>
<td width="50" valign="top">2008 Review</td>
<td width="50" valign="top">Chris Cupp</td>
<td width="50" valign="top">NULL</td>
<td width="50" valign="top">NULL</td>
<td width="50" valign="top">NULL</td>
<td width="50" valign="top">NULL</td>
</tr>
</tbody>
</table>
<p>Figure 2 – The horizontal table</p>
<p>For this example we used two scripts.  The first script will create a vertical table and insert the sample data.  The second script populates the horizontal table and also prints out all scripts created dynamically to the message window.</p>
<div id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:937ede7a-553c-4460-911a-25c74c0e47e9" class="wlWriterEditableSmartContent" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<p><a href="http://johnsterrett.com/img/Convertingaverticaltabletohorizontaltabl_FBB4/BlogHorizontaltable2.sql" target="_blank">Script to create vertical table</a></div>
<div id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:d4ac6b18-ce76-4dcf-af0d-a021ad6c75ee" class="wlWriterEditableSmartContent" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<p><a href="http://johnsterrett.com/img/Convertingaverticaltabletohorizontaltabl_FBB4/BlogHorizontalTable.sql" target="_blank">Script to create horizontal table</a></div>
<p>If you have any questions please feel free to leave a comment . I will try to point you in the right direction.</p>
<p><!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } --></p>
<div class="shr-publisher-55"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://johnsterrett.com/2009/09/24/converting-a-vertical-table-to-horizontal-table/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Find tables that contain column name</title>
		<link>http://johnsterrett.com/2009/07/07/find-tables-that-contain-column-name/</link>
		<comments>http://johnsterrett.com/2009/07/07/find-tables-that-contain-column-name/#comments</comments>
		<pubDate>Tue, 07 Jul 2009 15:41:29 +0000</pubDate>
		<dc:creator>johnsterrett</dc:creator>
				<category><![CDATA[Scripts]]></category>
		<category><![CDATA[SQL Server 2008]]></category>

		<guid isPermaLink="false">http://www.johnsterrett.com/2009/07/07/find-tables-that-contain-column-name/</guid>
		<description><![CDATA[The following script is used when I need to perform a search to find tables that contain a column name. -- Use Control+Shift+M to specify a value column name SELECT TABLE_SCHEMA + '.' + TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = &#8230; <a href="http://johnsterrett.com/2009/07/07/find-tables-that-contain-column-name/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fjohnsterrett.com%2F2009%2F07%2F07%2Ffind-tables-that-contain-column-name%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fjohnsterrett.com%2F2009%2F07%2F07%2Ffind-tables-that-contain-column-name%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>The following script is used when I need to perform a search to find tables that contain a column name.</p>
<pre class="csharpcode"><span class="rem">-- Use Control+Shift+M to specify a value column name</span>

<span class="kwrd">SELECT</span>    TABLE_SCHEMA + <span class="str">'.'</span> + TABLE_NAME
<span class="kwrd">FROM</span>    INFORMATION_SCHEMA.COLUMNS
<span class="kwrd">WHERE</span>    COLUMN_NAME = N<span class="str">'&lt;column_name,varchar,(column_name)&gt;'</span></pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>or you can also use the following query..&#160; </p>
<pre class="csharpcode"><span class="rem">-- Use Control+Shift+M to specify a value column name</span>

<span class="kwrd">SELECT</span> sc.[name] <span class="kwrd">AS</span> column_name, so.[name] <span class="kwrd">AS</span> [<span class="kwrd">TABLE</span>]
<span class="kwrd">FROM</span> syscolumns sc
<span class="kwrd">INNER</span> <span class="kwrd">JOIN</span> sysobjects so <span class="kwrd">ON</span> sc.id=so.id
<span class="kwrd">WHERE</span> sc.[name] <span class="kwrd">LIKE</span> N<span class="str">'&lt;column_name,varchar,(column_name)&gt;'</span>
<span class="kwrd">AND</span> so.xtype = <span class="str">'U'</span></pre>
<pre class="csharpcode"><span class="str"></span></pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>I</p>
<div class="shr-publisher-37"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://johnsterrett.com/2009/07/07/find-tables-that-contain-column-name/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

