<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Michael J. Swart</title>
	
	<link>http://michaeljswart.com</link>
	<description>Database Whisperer</description>
	<lastBuildDate>Thu, 24 May 2012 13:21:57 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/TheDatabaseWhisperer" /><feedburner:info uri="thedatabasewhisperer" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>The View of Foreign Keys That I Wanted</title>
		<link>http://feedproxy.google.com/~r/TheDatabaseWhisperer/~3/DXff9vbZmGA/</link>
		<comments>http://michaeljswart.com/2012/05/the-view-of-foreign-keys-that-i-wanted/#comments</comments>
		<pubDate>Thu, 24 May 2012 00:47:47 +0000</pubDate>
		<dc:creator>Michael J. Swart</dc:creator>
				<category><![CDATA[SQLServerPedia Syndication]]></category>
		<category><![CDATA[Technical Articles]]></category>
		<category><![CDATA[foreign keys]]></category>
		<category><![CDATA[system views]]></category>

		<guid isPermaLink="false">http://michaeljswart.com/?p=2813</guid>
		<description><![CDATA[So I've been working on an automation project that makes frequent use of foreign key metadata.]]></description>
			<content:encoded><![CDATA[<p><img src="http://michaeljswart.com/wp-content/uploads/2012/05/keylargo.png" alt="tropical sunset" title="Nice view of foreign keys (Florida keys are foreign to this Canadian)" width="500" height="300" class="alignnone size-full wp-image-2826" /></p>
<p>So I&#8217;ve been working on an automation project that makes frequent use of foreign key metadata. I find myself writing queries for this data but I discovered that there&#8217;s no super-easy out-of-the-box view of foreign keys for me to use. Here are the ones I considered.</p>
<h3>INFORMATION_SCHEMA views</h3>
<p>INFORMATION_SCHEMA views that give me foreign key information include
<ul>
<li>INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE for the foreign key info</li>
<li>INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS for the referring columns,</li>
<li>INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE for the referenced columns</li>
</ul>
<p>The first view here gives a list of foreign keys and you have to join to the other two tables in order to find the column names. But it&#8217;s a crummy solution. First of all, if the foreign key has multiple columns, there&#8217;s no real way to match the referring columns to the referenced columns.</p>
<p>The second thing is that we don&#8217;t see foreign keys that point to unique Keys (as pointed out by Aaron Bertrand in his post <a href="http://sqlblog.com/blogs/aaron_bertrand/archive/2011/11/03/the-case-against-information-schema-views.aspx">The case against INFORMATION_SCHEMA views</a>.</p>
<p>So that&#8217;s out. What else have we got in?</p>
<h3>Microsoft SQL Server system views</h3>
<p>These views include
<ul>
<li>sys.foreign_keys</li>
<li>sys.foreign_key_columns</li>
<li>with support from sys.columns and sys.tables</li>
</ul>
<p>These are the views I deserve, but not the views I need right now. The joins are just too annoying to remember and type each time. </p>
<p>Besides, the word &#8220;parent&#8221; used here changes with context. The parent table in a foreign key relationship owns the foreign key and does the pointing. But say I&#8217;m modeling a hierarchy. In the context of the data model, children records point to their parent records. The mental effort needed to keep these straight is not difficult, but it&#8217;s annoying.</p>
<h3>My Own Views</h3>
<p>So I&#8217;ve created my own, the goal is to simplify typing and minimize joins. I skip the word &#8220;parent&#8221; all together and use &#8220;referrer&#8221; and &#8220;referrenced&#8221;. Feel free to use and build on these.</p>
<p><strong>FOREIGN_KEYS</strong></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;">VIEW</span> dbo.<span style="color: #202020;">FOREIGN_KEYS</span>
<span style="color: #0000FF;">AS</span>
<span style="color: #0000FF;">SELECT</span>  SCHEMA_NAME<span style="color: #808080;">&#40;</span>fk.<span style="color: #202020;">schema_id</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> FKSchema ,
        fk.<span style="color: #202020;">name</span> <span style="color: #0000FF;">AS</span> FK ,
        SCHEMA_NAME<span style="color: #808080;">&#40;</span>p.<span style="color: #202020;">schema_id</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> ReferrerSchema ,
        p.<span style="color: #202020;">name</span> <span style="color: #0000FF;">AS</span> Referrer ,
        <span style="color: #FF00FF;">STUFF</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#40;</span> <span style="color: #0000FF;">SELECT</span> <span style="color: #FF0000;">','</span> <span style="color: #808080;">+</span> c.<span style="color: #202020;">name</span>
                     <span style="color: #0000FF;">FROM</span>   sys.<span style="color: #202020;">foreign_key_columns</span> fkc
                            <span style="color: #808080;">JOIN</span> sys.<span style="color: #202020;">columns</span> c <span style="color: #0000FF;">ON</span> fkc.<span style="color: #202020;">parent_object_id</span> <span style="color: #808080;">=</span> c.<span style="color: #FF00FF;">object_id</span>
                                                  <span style="color: #808080;">AND</span> fkc.<span style="color: #202020;">parent_column_id</span> <span style="color: #808080;">=</span> c.<span style="color: #202020;">column_id</span>
                     <span style="color: #0000FF;">WHERE</span>  fkc.<span style="color: #202020;">constraint_object_id</span> <span style="color: #808080;">=</span> fk.<span style="color: #FF00FF;">object_id</span>
                     <span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> fkc.<span style="color: #202020;">constraint_column_id</span> <span style="color: #0000FF;">ASC</span>
                   <span style="color: #0000FF;">FOR</span>
                     XML <span style="color: #0000FF;">PATH</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span> ,
                         TYPE
                   <span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">MAX</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>, <span style="color: #000;">1</span>, <span style="color: #000;">1</span>, <span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> ReferrerColumns ,
        SCHEMA_NAME<span style="color: #808080;">&#40;</span>r.<span style="color: #202020;">schema_id</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> ReferencedSchema ,
        r.<span style="color: #202020;">name</span> <span style="color: #0000FF;">AS</span> Referenced ,
        <span style="color: #FF00FF;">STUFF</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">CAST</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#40;</span> <span style="color: #0000FF;">SELECT</span> <span style="color: #FF0000;">','</span> <span style="color: #808080;">+</span> c.<span style="color: #202020;">name</span>
                     <span style="color: #0000FF;">FROM</span>   sys.<span style="color: #202020;">foreign_key_columns</span> fkc
                            <span style="color: #808080;">JOIN</span> sys.<span style="color: #202020;">columns</span> c <span style="color: #0000FF;">ON</span> fkc.<span style="color: #202020;">referenced_object_id</span> <span style="color: #808080;">=</span> c.<span style="color: #FF00FF;">object_id</span>
                                                  <span style="color: #808080;">AND</span> fkc.<span style="color: #202020;">referenced_column_id</span> <span style="color: #808080;">=</span> c.<span style="color: #202020;">column_id</span>
                     <span style="color: #0000FF;">WHERE</span>  fkc.<span style="color: #202020;">constraint_object_id</span> <span style="color: #808080;">=</span> fk.<span style="color: #FF00FF;">object_id</span>
                     <span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> fkc.<span style="color: #202020;">constraint_column_id</span> <span style="color: #0000FF;">ASC</span>
                   <span style="color: #0000FF;">FOR</span>
                     XML <span style="color: #0000FF;">PATH</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span> ,
                         TYPE
                   <span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> <span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">MAX</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>, <span style="color: #000;">1</span>, <span style="color: #000;">1</span>, <span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> ReferencedColumns ,
        fk.<span style="color: #202020;">delete_referential_action_desc</span> <span style="color: #0000FF;">AS</span> deleteAction ,
        fk.<span style="color: #202020;">update_referential_action_desc</span> <span style="color: #0000FF;">AS</span> updateAction ,
        fk.<span style="color: #FF00FF;">object_id</span> <span style="color: #0000FF;">AS</span> FKId ,
        p.<span style="color: #FF00FF;">object_id</span> <span style="color: #0000FF;">AS</span> ReferrerId ,
        r.<span style="color: #FF00FF;">object_id</span> <span style="color: #0000FF;">AS</span> ReferencedId
<span style="color: #0000FF;">FROM</span>    sys.<span style="color: #202020;">foreign_keys</span> fk
        <span style="color: #808080;">JOIN</span> sys.<span style="color: #202020;">tables</span> p <span style="color: #0000FF;">ON</span> p.<span style="color: #FF00FF;">object_id</span> <span style="color: #808080;">=</span> fk.<span style="color: #202020;">parent_object_id</span>
        <span style="color: #808080;">JOIN</span> sys.<span style="color: #202020;">tables</span> r <span style="color: #0000FF;">ON</span> r.<span style="color: #FF00FF;">object_id</span> <span style="color: #808080;">=</span> fk.<span style="color: #202020;">referenced_object_id</span>
GO</pre></div></div>

<p><strong>FOREIGN_KEY_COLUMNS</strong></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;">VIEW</span> dbo.<span style="color: #202020;">FOREIGN_KEY_COLUMNS</span>
<span style="color: #0000FF;">AS</span>
<span style="color: #0000FF;">SELECT</span>  SCHEMA_NAME<span style="color: #808080;">&#40;</span>fk.<span style="color: #202020;">schema_id</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> FKSchema ,
        fk.<span style="color: #202020;">name</span> <span style="color: #0000FF;">AS</span> FK ,
        SCHEMA_NAME<span style="color: #808080;">&#40;</span>p.<span style="color: #202020;">schema_id</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> ReferrerSchema ,
        p.<span style="color: #202020;">name</span> <span style="color: #0000FF;">AS</span> Referrer ,
        pc.<span style="color: #202020;">name</span> <span style="color: #0000FF;">AS</span> ReferrerColumn ,
        SCHEMA_NAME<span style="color: #808080;">&#40;</span>r.<span style="color: #202020;">schema_id</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">AS</span> ReferencedSchema ,
        r.<span style="color: #202020;">name</span> <span style="color: #0000FF;">AS</span> Referenced,
        rc.<span style="color: #202020;">name</span> <span style="color: #0000FF;">AS</span> ReferencedColumn ,
        fk.<span style="color: #FF00FF;">object_id</span> <span style="color: #0000FF;">AS</span> FKId ,
        fkc.<span style="color: #202020;">constraint_column_id</span> <span style="color: #0000FF;">AS</span> FKColumnId ,
        p.<span style="color: #FF00FF;">object_id</span> <span style="color: #0000FF;">AS</span> ReferrerId ,
        r.<span style="color: #FF00FF;">object_id</span> <span style="color: #0000FF;">AS</span> ReferencedId
<span style="color: #0000FF;">FROM</span>    sys.<span style="color: #202020;">foreign_keys</span> fk
        <span style="color: #808080;">JOIN</span> sys.<span style="color: #202020;">foreign_key_columns</span> fkc <span style="color: #0000FF;">ON</span> fkc.<span style="color: #202020;">constraint_object_id</span> <span style="color: #808080;">=</span> fk.<span style="color: #FF00FF;">object_id</span>
        <span style="color: #808080;">JOIN</span> sys.<span style="color: #202020;">tables</span> p <span style="color: #0000FF;">ON</span> p.<span style="color: #FF00FF;">object_id</span> <span style="color: #808080;">=</span> fk.<span style="color: #202020;">parent_object_id</span>
        <span style="color: #808080;">JOIN</span> sys.<span style="color: #202020;">columns</span> pc <span style="color: #0000FF;">ON</span> fkc.<span style="color: #202020;">parent_object_id</span> <span style="color: #808080;">=</span> pc.<span style="color: #FF00FF;">object_id</span>
                               <span style="color: #808080;">AND</span> fkc.<span style="color: #202020;">parent_column_id</span> <span style="color: #808080;">=</span> pc.<span style="color: #202020;">column_id</span>
        <span style="color: #808080;">JOIN</span> sys.<span style="color: #202020;">tables</span> r <span style="color: #0000FF;">ON</span> r.<span style="color: #FF00FF;">object_id</span> <span style="color: #808080;">=</span> fk.<span style="color: #202020;">referenced_object_id</span>
        <span style="color: #808080;">JOIN</span> sys.<span style="color: #202020;">columns</span> rc <span style="color: #0000FF;">ON</span> fkc.<span style="color: #202020;">referenced_object_id</span> <span style="color: #808080;">=</span> rc.<span style="color: #FF00FF;">object_id</span>
                               <span style="color: #808080;">AND</span> fkc.<span style="color: #202020;">referenced_column_id</span> <span style="color: #808080;">=</span> rc.<span style="color: #202020;">column_id</span>
GO</pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://michaeljswart.com/2012/05/the-view-of-foreign-keys-that-i-wanted/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://michaeljswart.com/2012/05/the-view-of-foreign-keys-that-i-wanted/</feedburner:origLink></item>
		<item>
		<title>Lessons From Geordi La Forge</title>
		<link>http://feedproxy.google.com/~r/TheDatabaseWhisperer/~3/YaWFZQGQxSk/</link>
		<comments>http://michaeljswart.com/2012/05/lessons-from-geordi-la-forge/#comments</comments>
		<pubDate>Mon, 14 May 2012 15:56:23 +0000</pubDate>
		<dc:creator>Michael J. Swart</dc:creator>
				<category><![CDATA[Data Cartoons]]></category>
		<category><![CDATA[Miscelleaneous SQL]]></category>
		<category><![CDATA[SQLServerPedia Syndication]]></category>
		<category><![CDATA[Tongue In Cheek]]></category>

		<guid isPermaLink="false">http://michaeljswart.com/?p=2787</guid>
		<description><![CDATA[I've been rewatching Star Trek again, I find I relate most to Geordi La Forge. He's a technical guy.]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been rewatching Star Trek again, I find I relate most to Geordi La Forge. He&#8217;s a technical guy. He wears the yellow shirt of engineering instead of the red shirt of command.</p>
<p>So I was inspired to write this light hearted post. I usually find non-technical posts a little wishy-washy (No offense to you Seth-Godin-types). But I liked the way this drawing turned out and I had to use it somehow right?</p>
<p><a href="http://michaeljswart.com/wp-content/uploads/2012/05/geordix2.png"><img class="alignnone size-full wp-image-2799" title="This picture of Geordi challenges you to a staring contest, BEGIN!" src="http://michaeljswart.com/wp-content/uploads/2012/05/geordi1.png" alt="Picture of Geordi Laforge captioned W W G L F D" width="500" height="300" /></a></p>
<p>You may have already seen articles or websites elsewhere that detail a comparison between Star Trek operations and company operations. Well here&#8217;s another one. For the moment we&#8217;ll sidestep the lessons learned from Picard (on how to be a inspiring leader) and go straight to Geordi. Here are the lessons:</p>
<h3>Make Everyone Believe You Can Do Anything &#8230;</h3>
<p>Here&#8217;s how Geordi&#8217;s typically responds to requests from the captain:</p>
<p><img class="alignnone size-full wp-image-2803" title="Can we fix it? YES WE CAN!" src="http://michaeljswart.com/wp-content/uploads/2012/05/CanYouFixIt1.png" alt="Can you fix the neutrino flux generator? ==&gt; either &quot;I can fix that captain. Estimated time two minutes.&quot; or &quot;Sorry captain, The flux couplers aren't in phase.&quot;" width="344" height="173" /></p>
<p>Did you see what he did there? It&#8217;s not a choice between &#8220;I can&#8221; or &#8220;I can&#8217;t&#8221;. It&#8217;s also not a choice between &#8220;it&#8217;s possible&#8221; or &#8220;it&#8217;s impossible&#8221;. If Geordi can accomplish a task, he essentially takes the credit with &#8220;I can do this&#8221;. If he can&#8217;t accomplish the task, then his words imply &#8220;It can&#8217;t be done.&#8221; He never implies that his skills are lacking. So are Geordi&#8217;s skills ever lacking? No:</p>
<h3>&#8230; And Then Make Sure They&#8217;re Right &#8230;</h3>
<p>Even when the pressure&#8217;s on and someone calls your bluff. There&#8217;s a persistence that can pay off:<br />
<strong>RIKER</strong>: Gentlemen, we&#8217;re giving you an assignment. The one thing we don&#8217;t want to hear is that it&#8217;s impossible.<br />
<strong>PICARD: </strong>I need the transporters to function, despite the hyperonic radiation.<br />
<strong>LA FORGE: </strong>Yeah, but that&#8217;s imp&#8230; Yes, sir.</p>
<p>and then later:<br />
<strong>LA FORGE: </strong>Captain &#8211; we can do it. We can modify the transporters. It&#8217;ll take fifteen years and a research team of a hundred&#8230;</p>
<p>Most impossible things are actually just really <em>really</em> difficult. For example, recently I <a href="http://dba.stackexchange.com/questions/15350">asked a question</a> on stackexchange about avoiding downtime during a migration. The first feedback I got was the comment &#8220;I don&#8217;t think [the downtime] can be avoided&#8221; which got a couple up-votes. But it turns out there was a way; it just took a lot of effort (I blogged about that effort in <a href="http://michaeljswart.com/2012/04/modifying-tables-online-part-1-migration-strategy/">this series</a>). It&#8217;s the yellow shirt&#8217;s job to explain the &#8220;how&#8221; and &#8220;what&#8221; so that the red shirts can make informed choices.</p>
<p>Later on in another episode:<br />
<strong>LA FORGE: </strong>Ferengi codes are damn near impossible to break.<br />
<strong>PICARD: </strong>Gentlemen, I have the utmost confidence in your ability to perform&#8230; the impossible.</p>
<p>See! It paid off. But it&#8217;s easy for me to give advice that boils down to &#8220;be able to do anything&#8221; it&#8217;s another thing to make it so. How do you get great at what you do?</p>
<h3>&#8230; By Being Awesome</h3>
<p>Easier said than done right?</p>
<p>So Geordi&#8217;s got skills, and he uses those skills to build a great career for himself. But where did he get those skills? I figure you can become great at something in a number of ways:</p>
<ul>
<li>Be talented at it (you can&#8217;t change you, but you can change fields)</li>
<li>Hard work. There&#8217;s no getting by without hard work. Imagine you&#8217;re on vacation sitting on a beach. You&#8217;re looking at the hut next to you and see some guy in a chair reading <a href="http://www.sqlmag.com/">SQL Server Pro</a> on his iPad. You just can&#8217;t compete with that guy. I&#8217;m not suggesting you read trade magazines on holiday, but are you in a field where you might want to?</li>
</ul>
<p>It boils down to finding your passion. And I hope you&#8217;ve found yours. Geordi is a guy whose passionate about the latest thing in his field. It almost seems like he cares about it more than job security:</p>
<p><strong>PICARD: </strong>Warp without warp drive.<br />
<strong>RIKER: </strong>They&#8217;re gonna put you out of a job, Geordi.<br />
<strong>LA FORGE: </strong>I hope so, Commander.</p>
<h3>Antilessons From Geordi</h3>
<p>But I like my role models the same way I like a buffet. I pick and choose the good lessons and leave the rest behind. Here&#8217;s a Geordi &#8220;lesson&#8221; that didn&#8217;t make the cut:</p>
<p><strong><strong>LA FORGE</strong>:</strong> I don&#8217;t know, Data, my gut tells me we ought to be listening to what this guy&#8217;s trying to tell us.<br />
<strong><strong>DATA</strong>:</strong> Your gut?<br />
<strong><strong>LA FORGE</strong>:</strong> It&#8217;s just a&#8230; a feeling, you know, an instinct. Intuition.<br />
<strong><strong>DATA</strong>:</strong> But those qualities would interfere with rational judgment, would they not?<br />
<strong><strong>LA FORGE</strong>:</strong> You&#8217;re right, sometimes they do.<br />
<strong>DATA:</strong> Then&#8230; why not rely strictly on the facts?<br />
<strong><strong>LA FORGE</strong>:</strong> Because you just can&#8217;t rely on the plain and simple facts. Sometimes they lie.</p>
<p>I don&#8217;t buy it. I get what he&#8217;s trying to say and the sentiment is correct, but the point of view is wrong. Facts don&#8217;t lie by definition. When Geordi says that facts lie sometimes, I would say instead that the facts are incomplete, or an assumption has been made incorrectly.</p>
<p>Once I was asked by a developer why his code was throwing the error message:</p>
<blockquote><p><span style="color: #ff0000;">Table &#8216;noidentity&#8217; does not have the identity property. Cannot perform SET operation.</span></p></blockquote>
<p>even though the table in question was showing that it did have an identity column.</p>
<p>I said show me. And he did. And was it the same table? It was. And was it the same database? Yes. Are you sure? Of course. Can you show me the connection string? Hang on a second&#8230;. ohhhh. (Omitted in this mini-dialogue is  about 15 minutes of head-scratching on both our parts).</p>
<p>Yes, sometimes the facts lie&#8230; but only when they&#8217;re not facts.</p>
<h3>More Geordi Lessons in The Comments</h3>
<p>I&#8217;ve put a few more of my favorites in <a href="http://michaeljswart.com/2012/05/lessons-from-geordi-la-forge/#comments">the comment</a> section of this post. Do you have any favorite Geordi lessons (or Star Trek lessons in general)?</p>
]]></content:encoded>
			<wfw:commentRss>http://michaeljswart.com/2012/05/lessons-from-geordi-la-forge/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://michaeljswart.com/2012/05/lessons-from-geordi-la-forge/</feedburner:origLink></item>
		<item>
		<title>Modifying Tables Online – Part 5: Just One More Thing</title>
		<link>http://feedproxy.google.com/~r/TheDatabaseWhisperer/~3/DiAlwxS0_Qg/</link>
		<comments>http://michaeljswart.com/2012/04/modifying-tables-online-part-5-just-one-more-thing/#comments</comments>
		<pubDate>Fri, 27 Apr 2012 14:50:29 +0000</pubDate>
		<dc:creator>Michael J. Swart</dc:creator>
				<category><![CDATA[SQLServerPedia Syndication]]></category>
		<category><![CDATA[Technical Articles]]></category>
		<category><![CDATA["sql server"]]></category>
		<category><![CDATA[online schema changes]]></category>
		<category><![CDATA[table migrations]]></category>

		<guid isPermaLink="false">http://michaeljswart.com/?p=2757</guid>
		<description><![CDATA[So Rob Volk commented on Part 3 of my blog. The comment prompted me to write a part five (which you're reading now). So you can thank him for this bonus section.]]></description>
			<content:encoded><![CDATA[<div style="background: #e9f4d9; border: 1px solid #587E25; display: block; height: auto; max-width: 96%; margin: 4px; padding: 10px;">
<p><strong>SERIES: Modifying Tables Online</strong></p>
<p>In the next few days I want to describe a way to modify the definition of very large tables while keeping the table available for other queries. Some table changes are already <em>online</em> operations. But <em>offline</em> changes need extra work to keep the table available. I explore one way to do that in this series.</p>
<p>This article used to be a single blog post, but I broke it into four parts because it seemed too long. Read Part 1, and understand the strategy I&#8217;m using. Treat Parts 2-4 as appendixes. When you want to use this plan (or one like it), come back and use them as examples. You won&#8217;t be able to make use of the examples by cutting and pasting directly (unless you happen to be running an bike equipment store called Adventureworks), but modifications shouldn&#8217;t be too hard.</p>
<ul>
<li><a href="http://michaeljswart.com/2012/04/modifying-tables-online-part-1-migration-strategy/">Part 1: Migration Strategy</a></li>
<li><a href="http://michaeljswart.com/2012/04/modifying-tables-online-part-2-implementation-example/">Part 2: Implementation Example</a></li>
<li><a href="http://michaeljswart.com/2012/04/modifying-tables-online-part-3-example-with-error-handling/">Part 3: Same Example With Error Handling</a></li>
<li><a href="http://michaeljswart.com/2012/04/modifying-tables-online-part-4-testing/">Part 4: Testing</a></li>
<li><strong>Part 5: Just One More Thing</strong></li>
</ul>
</div>
<h3>Just One More Thing</h3>
<p>So <a href="http://michaeljswart.com/2012/04/modifying-tables-online-part-3-example-with-error-handling/">Rob Volk commented</a> on Part 3 of my blog. The comment prompted me to write a part five (which you&#8217;re reading now). So you can thank him for this bonus section.</p>
<p><img src="http://michaeljswart.com/wp-content/uploads/2012/04/Columbo.png" alt="" title="There&#039;s one thing that still bothers me... Why don&#039;t you just use schemas?" width="500" height="300" class="alignnone size-full wp-image-2756" /></p>
<p>I&#8217;m going to quote Rob directly. He wrote: </p>
<blockquote><p>
One question/suggestion, have you considered using a new schema (e.g. Sales_New) and creating the new table in that schema? The benefit is that all the defaults, keys, triggers, and indexes can retain the same names as the original, and the switch becomes a single ALTER SCHEMA…TRANSFER operation. (or two, one for the old table and one for the new)
</p></blockquote>
<p>He&#8217;s absolutely right. The switch step becomes much much simpler and simpler is almost always better (as it is in this case). My migration would start by creating some extra schemas and then creating the staging table. In the Adventureworks example I&#8217;ve been using, that looks something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">use</span> AdventureWorks2012
go
<span style="color: #0000FF;">create</span> <span style="color: #0000FF;">schema</span> staging;
go
<span style="color: #0000FF;">create</span> <span style="color: #0000FF;">schema</span> obsolete;
go
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> staging.<span style="color: #202020;">SalesOrderHeader</span><span style="color: #808080;">&#40;</span>
<span style="color: #008080;">-- etc...</span></pre></div></div>

<p>So now our DB is prepared and looks like this:<br />
<img src="http://michaeljswart.com/wp-content/uploads/2012/04/OneMoreThing1.png" alt="" title="Prepare the staging table" width="526" height="189" class="alignnone size-full wp-image-2754" /></p>
<p>Copy the data over to the staging table the same way. In my SalesOrderHeader example, that code doesn&#8217;t change at all except that I replace &#8220;Sales.SalesOrderHeader_new&#8221; with &#8220;Staging.SalesOrderHeader&#8221;.</p>
<p>When ready, the switch now includes code like this:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">ALTER</span> <span style="color: #0000FF;">SCHEMA</span> obsolete TRANSFER Sales.<span style="color: #202020;">SalesOrderHeader</span>;
<span style="color: #0000FF;">ALTER</span> <span style="color: #0000FF;">SCHEMA</span> Sales TRANSFER staging.<span style="color: #202020;">SalesOrderHeader</span>;
&nbsp;
<span style="color: #0000FF;">drop</span> <span style="color: #0000FF;">trigger</span> obsolete.<span style="color: #202020;">t_i_SalesOrderHeader</span>;
<span style="color: #0000FF;">drop</span> <span style="color: #0000FF;">trigger</span> obsolete.<span style="color: #202020;">t_u_SalesOrderHeader</span>;
<span style="color: #0000FF;">drop</span> <span style="color: #0000FF;">trigger</span> obsolete.<span style="color: #202020;">t_d_SalesOrderHeader</span>;</pre></div></div>

<p>Looks simple right! It is. Simple is better. The schema now looks something like this:<br />
<img src="http://michaeljswart.com/wp-content/uploads/2012/04/OneMoreThing2.png" alt="" title="Switch out the original and switch in the staging" width="526" height="189" class="alignnone size-full wp-image-2755" /><br />
A few things to be careful of: </p>
<ul>
<li>Foreign keys: Although no renaming is necessary, they still have to dropped from and to the obsolete table. And foreign keys pointing to the new table still need to be added.</li>
<li>Existing triggers: They should recreated on the new table.</li>
</ul>
<h3>That&#8217;s It</h3>
<p>So dear reader, that&#8217;s the series. It was fun for me to explore in depth an intermediate topic. Thanks for bearing with me. I know the series was a little dry, but I figured that I wanted to use this walk-through for myself as a template for future migration projects and that if I thought it was useful, maybe you would think so too.</p>
]]></content:encoded>
			<wfw:commentRss>http://michaeljswart.com/2012/04/modifying-tables-online-part-5-just-one-more-thing/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://michaeljswart.com/2012/04/modifying-tables-online-part-5-just-one-more-thing/</feedburner:origLink></item>
		<item>
		<title>Modifying Tables Online – Part 4: Testing</title>
		<link>http://feedproxy.google.com/~r/TheDatabaseWhisperer/~3/CoKt0zwD7po/</link>
		<comments>http://michaeljswart.com/2012/04/modifying-tables-online-part-4-testing/#comments</comments>
		<pubDate>Thu, 26 Apr 2012 16:00:25 +0000</pubDate>
		<dc:creator>Michael J. Swart</dc:creator>
				<category><![CDATA[SQLServerPedia Syndication]]></category>
		<category><![CDATA[Technical Articles]]></category>
		<category><![CDATA["sql server"]]></category>
		<category><![CDATA[online schema changes]]></category>
		<category><![CDATA[table migrations]]></category>

		<guid isPermaLink="false">http://michaeljswart.com/?p=2670</guid>
		<description><![CDATA[So my testing is also pretty straightforward. I backup the Adventureworks2012 database on my dev machine ...]]></description>
			<content:encoded><![CDATA[<div style="background: #e9f4d9; border: 1px solid #587E25; display: block; height: auto; max-width: 96%; margin: 4px; padding: 10px;">
<p><strong>SERIES: Modifying Tables Online</strong></p>
<p>In the next few days I want to describe a way to modify the definition of very large tables while keeping the table available for other queries. Some table changes are already <em>online</em> operations. But <em>offline</em> changes need extra work to keep the table available. I explore one way to do that in this series.</p>
<p>This article used to be a single blog post, but I broke it into four parts because it seemed too long. Read Part 1, and understand the strategy I&#8217;m using. Treat Parts 2-4 as appendixes. When you want to use this plan (or one like it), come back and use them as examples. You won&#8217;t be able to make use of the examples by cutting and pasting directly (unless you happen to be running an bike equipment store called Adventureworks), but modifications shouldn&#8217;t be too hard.</p>
<ul>
<li><a href="http://michaeljswart.com/2012/04/modifying-tables-online-part-1-migration-strategy/">Part 1: Migration Strategy</a></li>
<li><a href="http://michaeljswart.com/2012/04/modifying-tables-online-part-2-implementation-example/">Part 2: Implementation Example</a></li>
<li><a href="http://michaeljswart.com/2012/04/modifying-tables-online-part-3-example-with-error-handling/">Part 3: Same Example With Error Handling</a></li>
<li><strong>Part 4: Testing</strong></li>
<li><a href="http://michaeljswart.com/2012/04/modifying-tables-online-part-5-just-one-more-thing/">Part 5: Just One More Thing</a></li>
</ul>
</div>
<p>This is part 4 of the series (you can consider this Appendix 3, The main article <a href="http://michaeljswart.com/2012/04/modifying-tables-online-part-1-migration-strategy/">is found here</a>).</p>
<p>So my testing is also pretty straightforward. I
<ol>
<li>Backup the Adventureworks2012 database on my dev machine</li>
<li>Start sending a whack of queries to the database to simulate concurrent activity</li>
<li>Make Adventureworks2012.Sales.SalesOrderHeader larger by adding lots of rows</li>
<li>Migrate the database using <a href="http://michaeljswart.com/2012/04/modifying-tables-online-part-3-example-with-error-handling/">the script from part 3</a></li>
<li>Look for any errors, fix them, restore the db and repeat the process if necessary</li>
<li>Otherwise &#8230; profit?</li>
</ol>
<p>You should be able to handle each of these steps. Except that I want to explain exactly how I personally handle number 2: I use an application to send queries to the database many times. Sounds easy right? The trick is that I want to call the stored procedure many times at once. </p>
<h3>Activity Generator</h3>
<p>This is a C# program which I compile into a .net application (I can&#8217;t wait for <a href="http://www.google.com/search?q=.net+4.5+async+and+await">.net 4.5&#8242;s async and await</a>)</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Collections.Generic</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Linq</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Text</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Data.SqlClient</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Threading</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">namespace</span> ConsoleApplication1 <span style="color: #008000;">&#123;</span>
    <span style="color: #6666cc; font-weight: bold;">class</span> Program <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">int</span> counter <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> Main<span style="color: #008000;">&#40;</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> args <span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
            SqlConnectionStringBuilder cs <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> SqlConnectionStringBuilder<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            cs<span style="color: #008000;">.</span><span style="color: #0000FF;">DataSource</span> <span style="color: #008000;">=</span> <span style="color: #666666;">@&quot;.&quot;</span><span style="color: #008000;">;</span>
            cs<span style="color: #008000;">.</span><span style="color: #0000FF;">InitialCatalog</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Adventureworks2012&quot;</span><span style="color: #008000;">;</span>
            cs<span style="color: #008000;">.</span><span style="color: #0000FF;">IntegratedSecurity</span> <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">;</span>
            cs<span style="color: #008000;">.</span><span style="color: #0000FF;">AsynchronousProcessing</span> <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">;</span>
            <span style="color: #6666cc; font-weight: bold;">string</span> connectionString <span style="color: #008000;">=</span> cs<span style="color: #008000;">.</span><span style="color: #0000FF;">ToString</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #6666cc; font-weight: bold;">string</span> sql <span style="color: #008000;">=</span> <span style="color: #666666;">@&quot;s_DoSomething&quot;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF; font-weight: bold;">for</span><span style="color: #008000;">&#40;</span> <span style="color: #6666cc; font-weight: bold;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> <span style="color: #FF0000;">100000</span><span style="color: #008000;">;</span> i<span style="color: #008000;">++</span> <span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
                SqlConnection conn <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> SqlConnection<span style="color: #008000;">&#40;</span> connectionString <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                conn<span style="color: #008000;">.</span><span style="color: #0000FF;">Open</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                SqlCommand cmd <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> SqlCommand<span style="color: #008000;">&#40;</span> sql, conn <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">CommandType</span> <span style="color: #008000;">=</span> <span style="color: #000000;">System.<span style="color: #0000FF;">Data</span></span><span style="color: #008000;">.</span><span style="color: #0000FF;">CommandType</span><span style="color: #008000;">.</span><span style="color: #0000FF;">StoredProcedure</span><span style="color: #008000;">;</span>
                cmd<span style="color: #008000;">.</span><span style="color: #0000FF;">BeginExecuteNonQuery</span><span style="color: #008000;">&#40;</span> <span style="color: #008000;">new</span> AsyncCallback<span style="color: #008000;">&#40;</span> EndExecution <span style="color: #008000;">&#41;</span>, cmd <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
            Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Format</span><span style="color: #008000;">&#40;</span> <span style="color: #666666;">@&quot;Error count: {0}&quot;</span>, counter <span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            Console<span style="color: #008000;">.</span><span style="color: #0000FF;">ReadLine</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> EndExecution<span style="color: #008000;">&#40;</span> IAsyncResult c <span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
            SqlCommand endCmd <span style="color: #008000;">=</span> <span style="color: #008000;">&#40;</span> c<span style="color: #008000;">.</span><span style="color: #0000FF;">AsyncState</span> <span style="color: #0600FF; font-weight: bold;">as</span> SqlCommand <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">try</span> <span style="color: #008000;">&#123;</span>
                endCmd<span style="color: #008000;">.</span><span style="color: #0000FF;">EndExecuteNonQuery</span><span style="color: #008000;">&#40;</span> c <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span> <span style="color: #0600FF; font-weight: bold;">catch</span><span style="color: #008000;">&#40;</span> Exception ex <span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
                <span style="color: #008080; font-style: italic;">//counter++;</span>
                Interlocked<span style="color: #008000;">.</span><span style="color: #0000FF;">Increment</span><span style="color: #008000;">&#40;</span> <span style="color: #0600FF; font-weight: bold;">ref</span> counter <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span> ex<span style="color: #008000;">.</span><span style="color: #0000FF;">Message</span> <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span> <span style="color: #0600FF; font-weight: bold;">finally</span> <span style="color: #008000;">&#123;</span>
                endCmd<span style="color: #008000;">.</span><span style="color: #0000FF;">Connection</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Close</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>You might have noticed that this program is extremely boring. It&#8217;s just calling one stored procedure: <em>s_DoSomething</em> over and over as fast as it can. The advantage is that I&#8217;m free to modify s_DoSomething (which is for me a lot easier than modifying this application). </p>
<p>So what does this procedure do? I&#8217;m glad you asked:</p>
<h3>s_DoSomething</h3>
<p>This procedure executes at random one task chosen from a set of typical OLTP tasks that use the table Sales.SalesOrderHeader. Here&#8217;s the one I used:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">create</span> <span style="color: #0000FF;">procedure</span> s_DoSomething 
<span style="color: #0000FF;">as</span>
<span style="color: #0000FF;">begin</span>
&nbsp;
    <span style="color: #0000FF;">declare</span> @choice <span style="color: #0000FF;">int</span> <span style="color: #808080;">=</span> <span style="color: #000;">1</span> <span style="color: #808080;">+</span> <span style="color: #FF00FF;">RAND</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">*</span> <span style="color: #000;">6</span>
    <span style="color: #0000FF;">declare</span> @SalesOrderId <span style="color: #0000FF;">int</span>;
&nbsp;
    <span style="color: #0000FF;">if</span> <span style="color: #808080;">&#40;</span>@choice <span style="color: #808080;">=</span> <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">insert</span> Sales.<span style="color: #202020;">SalesOrderHeader</span><span style="color: #808080;">&#40;</span>DueDate, OrderDate, CustomerID, BillToAddressID, ShipToAddressID, ShipMethodID<span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">select</span> <span style="color: #0000FF;">top</span> <span style="color: #000;">1000</span> DueDate, <span style="color: #FF00FF;">DATEADD</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">day</span>, <span style="color: #808080;">-</span><span style="color: #000;">1</span>, DueDate<span style="color: #808080;">&#41;</span>, CustomerID, BillToAddressID, ShipToAddressID, ShipMethodID
        <span style="color: #0000FF;">from</span> Sales.<span style="color: #202020;">SalesOrderHeader</span>
    <span style="color: #0000FF;">else</span> <span style="color: #0000FF;">if</span> <span style="color: #808080;">&#40;</span>@choice <span style="color: #808080;">=</span> <span style="color: #000;">2</span><span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">delete</span> <span style="color: #0000FF;">top</span> <span style="color: #808080;">&#40;</span><span style="color: #000;">100</span><span style="color: #808080;">&#41;</span> Sales.<span style="color: #202020;">SalesOrderHeader</span>
    <span style="color: #0000FF;">else</span> <span style="color: #0000FF;">if</span> <span style="color: #808080;">&#40;</span>@choice <span style="color: #808080;">=</span> <span style="color: #000;">3</span><span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">begin</span>
            <span style="color: #0000FF;">declare</span> @personid <span style="color: #0000FF;">int</span>;
&nbsp;
            <span style="color: #0000FF;">select</span> <span style="color: #0000FF;">top</span> <span style="color: #000;">1</span> @personid <span style="color: #808080;">=</span> BusinessEntityID
            <span style="color: #0000FF;">from</span> Sales.<span style="color: #202020;">SalesPerson</span>
            <span style="color: #0000FF;">order</span> <span style="color: #0000FF;">by</span> newid<span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>;
&nbsp;
            <span style="color: #0000FF;">select</span> <span style="color: #808080;">*</span> 
            <span style="color: #0000FF;">from</span> sales.<span style="color: #202020;">SalesOrderHeader</span>
            <span style="color: #0000FF;">where</span> SalesPersonID <span style="color: #808080;">=</span> @personid;
        <span style="color: #0000FF;">end</span>;
    <span style="color: #0000FF;">else</span> <span style="color: #0000FF;">if</span> <span style="color: #808080;">&#40;</span>@choice <span style="color: #808080;">IN</span> <span style="color: #808080;">&#40;</span><span style="color: #000;">4</span>,<span style="color: #000;">5</span>,<span style="color: #000;">6</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">begin</span>
            <span style="color: #0000FF;">select</span> <span style="color: #0000FF;">top</span> <span style="color: #000;">1</span> @SalesOrderId <span style="color: #808080;">=</span> SalesOrderId
            <span style="color: #0000FF;">from</span> Sales.<span style="color: #202020;">SalesOrderHeader</span> <span style="color: #0000FF;">with</span> <span style="color: #808080;">&#40;</span>nolock<span style="color: #808080;">&#41;</span>;
&nbsp;
            <span style="color: #0000FF;">select</span> <span style="color: #0000FF;">top</span> <span style="color: #000;">100</span> <span style="color: #808080;">*</span> 
            <span style="color: #0000FF;">from</span> Sales.<span style="color: #202020;">SalesOrderHeader</span> 
            <span style="color: #0000FF;">where</span> SalesOrderId <span style="color: #808080;">&gt;</span> @SalesOrderId
        <span style="color: #0000FF;">end</span>
&nbsp;
<span style="color: #0000FF;">end</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://michaeljswart.com/2012/04/modifying-tables-online-part-4-testing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://michaeljswart.com/2012/04/modifying-tables-online-part-4-testing/</feedburner:origLink></item>
		<item>
		<title>Modifying Tables Online – Part 3: Example With Error Handling</title>
		<link>http://feedproxy.google.com/~r/TheDatabaseWhisperer/~3/UdPXJOe5mrQ/</link>
		<comments>http://michaeljswart.com/2012/04/modifying-tables-online-part-3-example-with-error-handling/#comments</comments>
		<pubDate>Fri, 20 Apr 2012 17:56:56 +0000</pubDate>
		<dc:creator>Michael J. Swart</dc:creator>
				<category><![CDATA[SQLServerPedia Syndication]]></category>
		<category><![CDATA[Technical Articles]]></category>
		<category><![CDATA["sql server"]]></category>
		<category><![CDATA[online schema changes]]></category>
		<category><![CDATA[table migrations]]></category>

		<guid isPermaLink="false">http://michaeljswart.com/?p=2668</guid>
		<description><![CDATA[I present without any further comment, the scripts (with error-handling).]]></description>
			<content:encoded><![CDATA[<div style="background: #e9f4d9; border: 1px solid #587E25; display: block; height: auto; max-width: 96%; margin: 4px; padding: 10px;">
<p><strong>SERIES: Modifying Tables Online</strong></p>
<p>In the next few days I want to describe a way to modify the definition of very large tables while keeping the table available for other queries. Some table changes are already <em>online</em> operations. But <em>offline</em> changes need extra work to keep the table available. I explore one way to do that in this series.</p>
<p>This article used to be a single blog post, but I broke it into four parts because it seemed too long. Read Part 1, and understand the strategy I&#8217;m using. Treat Parts 2-4 as appendixes. When you want to use this plan (or one like it), come back and use them as examples. You won&#8217;t be able to make use of the examples by cutting and pasting directly (unless you happen to be running an bike equipment store called Adventureworks), but modifications shouldn&#8217;t be too hard.</p>
<ul>
<li><a href="http://michaeljswart.com/2012/04/modifying-tables-online-part-1-migration-strategy/">Part 1: Migration Strategy</a></li>
<li><a href="http://michaeljswart.com/2012/04/modifying-tables-online-part-2-implementation-example/">Part 2: Implementation Example</a></li>
<li><strong>Part 3: Same Example With Error Handling</strong></li>
<li><a href="http://michaeljswart.com/2012/04/modifying-tables-online-part-4-testing/">Part 4: Testing</a></li>
<li><a href="http://michaeljswart.com/2012/04/modifying-tables-online-part-5-just-one-more-thing/">Part 5: Just One More Thing</a></li>
</ul>
</div>
<p>This is part 3 of the series (you can consider this Appendix 2, The main article <a href="http://michaeljswart.com/2012/04/modifying-tables-online-part-1-migration-strategy/">is found here</a>).</p>
<p>What you find below is <em>exactly</em> the same script as you find in <a href="http://michaeljswart.com/2012/04/modifying-tables-online-part-1-migration-strategy/">Part 2: Implementation Example</a> with the exception that I&#8217;ve included error handling and wrappers to handle the following goals:</p>
<ul>
<li>If a statement fails, no data is lost</li>
<li>If a statement fails, other queries are not impacted (i.e. we&#8217;re online)</li>
<li>If a statement fails anywhere, it can be retried from the beginning with no lost work. This means for example that when data is copied to the staging table in batches, and that process is interrupted and restarted, the script &#8220;picks up where it left off&#8221;.</li>
<li>The process is re-runnable. This means that if the script succeeds and for some reason the script is run again then no errors are raised and no work is performed.</li>
<li>The last step, the switch, is an atomic transaction. It succeeds 100% or fails and rolls back 100%.</li>
</ul>
<p>I present without any further comment, the scripts (with error-handling).</p>
<h3>Create Staging Table</h3>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">use</span> AdventureWorks2012
&nbsp;
<span style="color: #008080;">-- original table isn't migrated, staging table doesn't exist</span>
<span style="color: #0000FF;">IF</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">EXISTS</span> 
    <span style="color: #808080;">&#40;</span>
        <span style="color: #0000FF;">SELECT</span> <span style="color: #000;">1</span> 
        <span style="color: #0000FF;">FROM</span> <span style="color: #808080;">IN</span>F<span style="color: #808080;">OR</span>MATION_SCHEMA.<span style="color: #202020;">TABLES</span> 
        <span style="color: #0000FF;">WHERE</span> TABLE_SCHEMA <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Sales'</span> 
        <span style="color: #808080;">AND</span> TABLE_NAME <span style="color: #808080;">=</span> <span style="color: #FF0000;">'SalesOrderHeader_new'</span>
    <span style="color: #808080;">&#41;</span>
<span style="color: #808080;">AND</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: #000;">1</span> 
        <span style="color: #0000FF;">FROM</span> <span style="color: #808080;">IN</span>F<span style="color: #808080;">OR</span>MATION_SCHEMA.<span style="color: #202020;">COLUMNS</span> 
        <span style="color: #0000FF;">WHERE</span> TABLE_SCHEMA <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Sales'</span> 
        <span style="color: #808080;">AND</span> TABLE_NAME <span style="color: #808080;">=</span> <span style="color: #FF0000;">'SalesOrderHeader'</span> 
        <span style="color: #808080;">AND</span> COLUMN_NAME <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Rowversion'</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> Sales.<span style="color: #202020;">SalesOrderHeader_new</span><span style="color: #808080;">&#40;</span>
        SalesOrderID <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: #0000FF;">FOR</span> <span style="color: #0000FF;">REPLICATION</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
        RevisionNumber <span style="color: #0000FF;">tinyint</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
        OrderDate <span style="color: #0000FF;">datetime</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
        DueDate <span style="color: #0000FF;">datetime</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
        ShipDate <span style="color: #0000FF;">datetime</span> <span style="color: #808080;">NULL</span>,
        <span style="color: #808080;">&#91;</span>Status<span style="color: #808080;">&#93;</span> <span style="color: #0000FF;">tinyint</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
        OnlineOrderFlag dbo.<span style="color: #202020;">Flag</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
        SalesOrderNumber  <span style="color: #0000FF;">AS</span> <span style="color: #808080;">&#40;</span>isnull<span style="color: #808080;">&#40;</span>N<span style="color: #FF0000;">'SO'</span><span style="color: #808080;">+</span><span style="color: #0000FF;">CONVERT</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">nvarchar</span><span style="color: #808080;">&#40;</span><span style="color: #000;">23</span><span style="color: #808080;">&#41;</span>,SalesOrderID<span style="color: #808080;">&#41;</span>,N<span style="color: #FF0000;">'*** ERROR ***'</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>,
        PurchaseOrderNumber dbo.<span style="color: #202020;">OrderNumber</span> <span style="color: #808080;">NULL</span>,
        AccountNumber dbo.<span style="color: #202020;">AccountNumber</span> <span style="color: #808080;">NULL</span>,
        CustomerID <span style="color: #0000FF;">int</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
        SalesPersonID <span style="color: #0000FF;">int</span> <span style="color: #808080;">NULL</span>,
        TerritoryID <span style="color: #0000FF;">int</span> <span style="color: #808080;">NULL</span>,
        BillToAddressID <span style="color: #0000FF;">int</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
        ShipToAddressID <span style="color: #0000FF;">int</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
        ShipMethodID <span style="color: #0000FF;">int</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
        CreditCardID <span style="color: #0000FF;">int</span> <span style="color: #808080;">NULL</span>,
        CreditCardApprovalCode <span style="color: #0000FF;">varchar</span><span style="color: #808080;">&#40;</span><span style="color: #000;">15</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">NULL</span>,
        CurrencyRateID <span style="color: #0000FF;">int</span> <span style="color: #808080;">NULL</span>,
        SubTotal <span style="color: #0000FF;">money</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
        TaxAmt <span style="color: #0000FF;">money</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
        Freight <span style="color: #0000FF;">money</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
        TotalDue  <span style="color: #0000FF;">AS</span> <span style="color: #808080;">&#40;</span>isnull<span style="color: #808080;">&#40;</span><span style="color: #808080;">&#40;</span>SubTotal<span style="color: #808080;">+</span>TaxAmt<span style="color: #808080;">&#41;</span><span style="color: #808080;">+</span>Freight,<span style="color: #808080;">&#40;</span><span style="color: #000;">0</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>,
        Comment <span style="color: #0000FF;">nvarchar</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">NULL</span>,
        rowguid <span style="color: #0000FF;">uniqueidentifier</span> <span style="color: #0000FF;">ROWGUIDCOL</span>  <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
        ModifiedDate <span style="color: #0000FF;">datetime</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
        <span style="color: #808080;">&#91;</span>Rowversion<span style="color: #808080;">&#93;</span> rowversion <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>, <span style="color: #008080;">-- This is the new column!!</span>
        <span style="color: #0000FF;">constraint</span> PK_SalesOrderHeader_new_SalesOrderID
            <span style="color: #0000FF;">primary</span> <span style="color: #0000FF;">key</span> <span style="color: #0000FF;">clustered</span> <span style="color: #808080;">&#40;</span>SalesOrderID <span style="color: #0000FF;">ASC</span><span style="color: #808080;">&#41;</span>,
        <span style="color: #0000FF;">constraint</span> FK_SalesOrderHeader_new_Address_BillToAddressID 
            <span style="color: #0000FF;">foreign</span> <span style="color: #0000FF;">key</span><span style="color: #808080;">&#40;</span>BillToAddressID<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">references</span> Person.<span style="color: #808080;">&#91;</span>Address<span style="color: #808080;">&#93;</span> <span style="color: #808080;">&#40;</span>AddressID<span style="color: #808080;">&#41;</span>,
        <span style="color: #0000FF;">constraint</span> FK_SalesOrderHeader_new_Address_ShipToAddressID 
            <span style="color: #0000FF;">foreign</span> <span style="color: #0000FF;">key</span><span style="color: #808080;">&#40;</span>ShipToAddressID<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">references</span> Person.<span style="color: #808080;">&#91;</span>Address<span style="color: #808080;">&#93;</span> <span style="color: #808080;">&#40;</span>AddressID<span style="color: #808080;">&#41;</span>,
        <span style="color: #0000FF;">constraint</span> FK_SalesOrderHeader_new_CreditCard_CreditCardID 
            <span style="color: #0000FF;">foreign</span> <span style="color: #0000FF;">key</span><span style="color: #808080;">&#40;</span>CreditCardID<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">references</span> Sales.<span style="color: #202020;">CreditCard</span> <span style="color: #808080;">&#40;</span>CreditCardID<span style="color: #808080;">&#41;</span>,
        <span style="color: #0000FF;">constraint</span> FK_SalesOrderHeader_new_CurrencyRate_CurrencyRateID 
            <span style="color: #0000FF;">foreign</span> <span style="color: #0000FF;">key</span><span style="color: #808080;">&#40;</span>CurrencyRateID<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">references</span> Sales.<span style="color: #202020;">CurrencyRate</span> <span style="color: #808080;">&#40;</span>CurrencyRateID<span style="color: #808080;">&#41;</span>,
        <span style="color: #0000FF;">constraint</span> FK_SalesOrderHeader_new_Customer_CustomerID 
            <span style="color: #0000FF;">foreign</span> <span style="color: #0000FF;">key</span><span style="color: #808080;">&#40;</span>CustomerID<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">references</span> Sales.<span style="color: #202020;">Customer</span> <span style="color: #808080;">&#40;</span>CustomerID<span style="color: #808080;">&#41;</span>,
        <span style="color: #0000FF;">constraint</span> FK_SalesOrderHeader_new_SalesPerson_SalesPersonID 
            <span style="color: #0000FF;">foreign</span> <span style="color: #0000FF;">key</span><span style="color: #808080;">&#40;</span>SalesPersonID<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">references</span> Sales.<span style="color: #202020;">SalesPerson</span> <span style="color: #808080;">&#40;</span>BusinessEntityID<span style="color: #808080;">&#41;</span>,
        <span style="color: #0000FF;">constraint</span> FK_SalesOrderHeader_new_SalesTerritory_TerritoryID 
            <span style="color: #0000FF;">foreign</span> <span style="color: #0000FF;">key</span><span style="color: #808080;">&#40;</span>TerritoryID<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">references</span> Sales.<span style="color: #202020;">SalesTerritory</span> <span style="color: #808080;">&#40;</span>TerritoryID<span style="color: #808080;">&#41;</span>,
        <span style="color: #0000FF;">constraint</span> FK_SalesOrderHeader_new_ShipMethod_ShipMethodID 
            <span style="color: #0000FF;">foreign</span> <span style="color: #0000FF;">key</span><span style="color: #808080;">&#40;</span>ShipMethodID<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">references</span> Purchasing.<span style="color: #202020;">ShipMethod</span> <span style="color: #808080;">&#40;</span>ShipMethodID<span style="color: #808080;">&#41;</span>,
        <span style="color: #0000FF;">constraint</span> CK_SalesOrderHeader_new_DueDate 
            <span style="color: #0000FF;">check</span> <span style="color: #808080;">&#40;</span>DueDate<span style="color: #808080;">&gt;=</span>OrderDate<span style="color: #808080;">&#41;</span>,
        <span style="color: #0000FF;">constraint</span> CK_SalesOrderHeader_new_Freight 
            <span style="color: #0000FF;">check</span> <span style="color: #808080;">&#40;</span>Freight<span style="color: #808080;">&gt;=</span><span style="color: #000;">0.00</span><span style="color: #808080;">&#41;</span>,
        <span style="color: #0000FF;">constraint</span> CK_SalesOrderHeader_new_ShipDate 
            <span style="color: #0000FF;">check</span> <span style="color: #808080;">&#40;</span>ShipDate<span style="color: #808080;">&gt;=</span>OrderDate or ShipDate <span style="color: #0000FF;">is</span> null<span style="color: #808080;">&#41;</span>,
        <span style="color: #0000FF;">constraint</span> CK_SalesOrderHeader_new_Status 
            <span style="color: #0000FF;">check</span> <span style="color: #808080;">&#40;</span><span style="color: #808080;">&#91;</span>Status<span style="color: #808080;">&#93;</span><span style="color: #808080;">&gt;=</span><span style="color: #000;">0</span> and <span style="color: #808080;">&#91;</span>Status<span style="color: #808080;">&#93;</span><span style="color: #808080;">&lt;=</span><span style="color: #000;">8</span><span style="color: #808080;">&#41;</span>,
        <span style="color: #0000FF;">constraint</span> CK_SalesOrderHeader_new_SubTotal 
            <span style="color: #0000FF;">check</span> <span style="color: #808080;">&#40;</span>SubTotal<span style="color: #808080;">&gt;=</span><span style="color: #000;">0.00</span><span style="color: #808080;">&#41;</span>,
        <span style="color: #0000FF;">constraint</span> CK_SalesOrderHeader_new_TaxAmt 
            <span style="color: #0000FF;">check</span> <span style="color: #808080;">&#40;</span>TaxAmt<span style="color: #808080;">&gt;=</span><span style="color: #000;">0.00</span><span style="color: #808080;">&#41;</span>
    <span style="color: #808080;">&#41;</span>
&nbsp;
    <span style="color: #008080;">-- add default constraints</span>
    <span style="color: #0000FF;">alter</span> <span style="color: #0000FF;">table</span> Sales.<span style="color: #202020;">SalesOrderHeader_new</span> <span style="color: #0000FF;">add</span>
    <span style="color: #0000FF;">constraint</span> DF_SalesOrderHeader_new_RevisionNumber  
        <span style="color: #0000FF;">default</span> <span style="color: #000;">0</span> <span style="color: #0000FF;">for</span> RevisionNumber,
    <span style="color: #0000FF;">constraint</span> DF_SalesOrderHeader_new_OrderDate  
        <span style="color: #0000FF;">default</span> <span style="color: #FF00FF;">getdate</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">for</span> OrderDate,
    <span style="color: #0000FF;">constraint</span> DF_SalesOrderHeader_new_Status  
        <span style="color: #0000FF;">default</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">for</span> <span style="color: #808080;">&#91;</span>Status<span style="color: #808080;">&#93;</span>,
    <span style="color: #0000FF;">constraint</span> DF_SalesOrderHeader_new_OnlineOrderFlag  
        <span style="color: #0000FF;">default</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">for</span> OnlineOrderFlag,
    <span style="color: #0000FF;">constraint</span> DF_SalesOrderHeader_new_SubTotal  
        <span style="color: #0000FF;">default</span> <span style="color: #000;">0.00</span> <span style="color: #0000FF;">for</span> SubTotal,
    <span style="color: #0000FF;">constraint</span> DF_SalesOrderHeader_new_TaxAmt  
        <span style="color: #0000FF;">default</span> <span style="color: #000;">0.00</span> <span style="color: #0000FF;">for</span> TaxAmt,
    <span style="color: #0000FF;">constraint</span> DF_SalesOrderHeader_new_Freight  
        <span style="color: #0000FF;">default</span> <span style="color: #000;">0.00</span> <span style="color: #0000FF;">for</span> Freight,
    <span style="color: #0000FF;">constraint</span> DF_SalesOrderHeader_new_rowguid  
        <span style="color: #0000FF;">default</span> newid<span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">for</span> rowguid,
    <span style="color: #0000FF;">constraint</span> DF_SalesOrderHeader_new_ModifiedDate  
        <span style="color: #0000FF;">default</span> <span style="color: #FF00FF;">getdate</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">for</span> ModifiedDate
&nbsp;
        <span style="color: #008080;">-- two nc ak</span>
    <span style="color: #0000FF;">create</span> <span style="color: #0000FF;">unique</span> <span style="color: #0000FF;">nonclustered</span> <span style="color: #0000FF;">index</span> AK_SalesOrderHeader_new_rowguid 
        <span style="color: #0000FF;">on</span> Sales.<span style="color: #202020;">SalesOrderHeader_new</span><span style="color: #808080;">&#40;</span>rowguid <span style="color: #0000FF;">ASC</span><span style="color: #808080;">&#41;</span>
&nbsp;
    <span style="color: #0000FF;">create</span> <span style="color: #0000FF;">unique</span> <span style="color: #0000FF;">nonclustered</span> <span style="color: #0000FF;">index</span> AK_SalesOrderHeader_new_SalesOrderNumber
        <span style="color: #0000FF;">on</span> Sales.<span style="color: #202020;">SalesOrderHeader_new</span><span style="color: #808080;">&#40;</span>SalesOrderNumber<span style="color: #808080;">&#41;</span>
&nbsp;
        <span style="color: #008080;">-- two nc ix</span>
    <span style="color: #0000FF;">create</span> <span style="color: #0000FF;">nonclustered</span> <span style="color: #0000FF;">index</span> IX_SalesOrderHeader_new_CustomerID
        <span style="color: #0000FF;">on</span> Sales.<span style="color: #202020;">SalesOrderHeader_new</span><span style="color: #808080;">&#40;</span>CustomerID<span style="color: #808080;">&#41;</span>
&nbsp;
    <span style="color: #0000FF;">create</span> <span style="color: #0000FF;">nonclustered</span> <span style="color: #0000FF;">index</span> IX_SalesOrderHeader_new_SalesPersonID
        <span style="color: #0000FF;">on</span> Sales.<span style="color: #202020;">SalesOrderHeader_new</span><span style="color: #808080;">&#40;</span>SalesPersonID<span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">END</span>
GO</pre></div></div>

<h3>Add Triggers</h3>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">-- staging table exists</span>
<span style="color: #008080;">-- original table isn't migrated, </span>
<span style="color: #008080;">-- triggers don't exist</span>
<span style="color: #0000FF;">IF</span> <span style="color: #808080;">EXISTS</span> 
    <span style="color: #808080;">&#40;</span>
        <span style="color: #0000FF;">SELECT</span> <span style="color: #000;">1</span> 
        <span style="color: #0000FF;">FROM</span> <span style="color: #808080;">IN</span>F<span style="color: #808080;">OR</span>MATION_SCHEMA.<span style="color: #202020;">TABLES</span> 
        <span style="color: #0000FF;">WHERE</span> TABLE_SCHEMA <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Sales'</span> 
        <span style="color: #808080;">AND</span> TABLE_NAME <span style="color: #808080;">=</span> <span style="color: #FF0000;">'SalesOrderHeader_new'</span>
    <span style="color: #808080;">&#41;</span>
<span style="color: #808080;">AND</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: #000;">1</span> 
        <span style="color: #0000FF;">FROM</span> <span style="color: #808080;">IN</span>F<span style="color: #808080;">OR</span>MATION_SCHEMA.<span style="color: #202020;">COLUMNS</span> 
        <span style="color: #0000FF;">WHERE</span> TABLE_SCHEMA <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Sales'</span> 
        <span style="color: #808080;">AND</span> TABLE_NAME <span style="color: #808080;">=</span> <span style="color: #FF0000;">'SalesOrderHeader'</span> 
        <span style="color: #808080;">AND</span> COLUMN_NAME <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Rowversion'</span>
    <span style="color: #808080;">&#41;</span>
<span style="color: #808080;">AND</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: #000;">1</span> 
        <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">triggers</span>
        <span style="color: #0000FF;">WHERE</span> name <span style="color: #808080;">=</span> <span style="color: #FF0000;">'t_i_SalesOrderHeader'</span>
    <span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">BEGIN</span>
&nbsp;
    <span style="color: #0000FF;">EXEC</span> <span style="color: #AF0000;">sp_executesql</span> N<span style="color: #FF0000;">'
        create trigger t_i_SalesOrderHeader
        on Sales.SalesOrderHeader
        after insert
        as 
            set identity_insert Sales.SalesOrderHeader_new on;
&nbsp;
            insert SalesOrderHeader_new(SalesOrderID, RevisionNumber, OrderDate, DueDate, ShipDate, [Status], OnlineOrderFlag, PurchaseOrderNumber, AccountNumber, CustomerID, SalesPersonID, TerritoryID, BillToAddressID, ShipToAddressID, ShipMethodID, CreditCardID, CreditCardApprovalCode, CurrencyRateID, SubTotal, TaxAmt, Freight, Comment, rowguid, ModifiedDate)
            select SalesOrderID, RevisionNumber, OrderDate, DueDate, ShipDate, [Status], OnlineOrderFlag, PurchaseOrderNumber, AccountNumber, CustomerID, SalesPersonID, TerritoryID, BillToAddressID, ShipToAddressID, ShipMethodID, CreditCardID, CreditCardApprovalCode, CurrencyRateID, SubTotal, TaxAmt, Freight, Comment, rowguid, ModifiedDate
            from inserted
&nbsp;
            set identity_insert Sales.SalesOrderHeader_new off;'</span>;
<span style="color: #0000FF;">END</span>
GO
&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: #000;">1</span> 
        <span style="color: #0000FF;">FROM</span> <span style="color: #808080;">IN</span>F<span style="color: #808080;">OR</span>MATION_SCHEMA.<span style="color: #202020;">TABLES</span> 
        <span style="color: #0000FF;">WHERE</span> TABLE_SCHEMA <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Sales'</span> 
        <span style="color: #808080;">AND</span> TABLE_NAME <span style="color: #808080;">=</span> <span style="color: #FF0000;">'SalesOrderHeader_new'</span>
    <span style="color: #808080;">&#41;</span>
<span style="color: #808080;">AND</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: #000;">1</span> 
        <span style="color: #0000FF;">FROM</span> <span style="color: #808080;">IN</span>F<span style="color: #808080;">OR</span>MATION_SCHEMA.<span style="color: #202020;">COLUMNS</span> 
        <span style="color: #0000FF;">WHERE</span> TABLE_SCHEMA <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Sales'</span> 
        <span style="color: #808080;">AND</span> TABLE_NAME <span style="color: #808080;">=</span> <span style="color: #FF0000;">'SalesOrderHeader'</span> 
        <span style="color: #808080;">AND</span> COLUMN_NAME <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Rowversion'</span>
    <span style="color: #808080;">&#41;</span>
<span style="color: #808080;">AND</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: #000;">1</span> 
        <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">triggers</span>
        <span style="color: #0000FF;">WHERE</span> name <span style="color: #808080;">=</span> <span style="color: #FF0000;">'t_u_SalesOrderHeader'</span>
    <span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">BEGIN</span>
    <span style="color: #0000FF;">EXEC</span> <span style="color: #AF0000;">sp_executesql</span> N<span style="color: #FF0000;">'
        create trigger t_u_SalesOrderHeader
        on Sales.SalesOrderHeader
        after update
        as 
            -- assuming pk values are never altered.
            update Sales.SalesOrderHeader_new
            set 
                RevisionNumber = i.RevisionNumber,
                OrderDate  = i.OrderDate,
                DueDate  = i.DueDate,
                ShipDate  = i.ShipDate,
                [Status]  = i.[Status],
                OnlineOrderFlag  = i.OnlineOrderFlag,
                PurchaseOrderNumber  = i.PurchaseOrderNumber,
                AccountNumber  = i.AccountNumber,
                CustomerID  = i.CustomerID,
                SalesPersonID  = i.SalesPersonID,
                TerritoryID  = i.TerritoryID,
                BillToAddressID  = i.BillToAddressID,
                ShipToAddressID  = i.ShipToAddressID,
                ShipMethodID  = i.ShipMethodID,
                CreditCardID  = i.CreditCardID,
                CreditCardApprovalCode = i.CreditCardApprovalCode,
                CurrencyRateID  = i.CurrencyRateID,
                SubTotal  = i.SubTotal,
                TaxAmt  = i.TaxAmt,
                Freight  = i.Freight,
                Comment  = i.Comment,
                rowguid  = i.rowguid,
                ModifiedDate = i.ModifiedDate
            from Sales.SalesOrderHeader_new s
            join inserted i 
                on s.SalesOrderID = i.SalesOrderID;'</span>;
<span style="color: #0000FF;">END</span>
GO
&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: #000;">1</span> 
        <span style="color: #0000FF;">FROM</span> <span style="color: #808080;">IN</span>F<span style="color: #808080;">OR</span>MATION_SCHEMA.<span style="color: #202020;">TABLES</span> 
        <span style="color: #0000FF;">WHERE</span> TABLE_SCHEMA <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Sales'</span> 
        <span style="color: #808080;">AND</span> TABLE_NAME <span style="color: #808080;">=</span> <span style="color: #FF0000;">'SalesOrderHeader_new'</span>
    <span style="color: #808080;">&#41;</span>
<span style="color: #808080;">AND</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: #000;">1</span> 
        <span style="color: #0000FF;">FROM</span> <span style="color: #808080;">IN</span>F<span style="color: #808080;">OR</span>MATION_SCHEMA.<span style="color: #202020;">COLUMNS</span> 
        <span style="color: #0000FF;">WHERE</span> TABLE_SCHEMA <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Sales'</span> 
        <span style="color: #808080;">AND</span> TABLE_NAME <span style="color: #808080;">=</span> <span style="color: #FF0000;">'SalesOrderHeader'</span> 
        <span style="color: #808080;">AND</span> COLUMN_NAME <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Rowversion'</span>
    <span style="color: #808080;">&#41;</span>
<span style="color: #808080;">AND</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: #000;">1</span> 
        <span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">triggers</span>
        <span style="color: #0000FF;">WHERE</span> name <span style="color: #808080;">=</span> <span style="color: #FF0000;">'t_d_SalesOrderHeader'</span>
    <span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">BEGIN</span>
    <span style="color: #0000FF;">EXEC</span> <span style="color: #AF0000;">sp_executesql</span> N<span style="color: #FF0000;">'
        create trigger t_d_SalesOrderHeader
        on Sales.SalesOrderHeader
        after delete
        as 
            delete Sales.SalesOrderHeader_new
            from Sales.SalesOrderHeader_new s
            join deleted d 
                on d.SalesOrderID = s.SalesOrderID ;'</span>;
<span style="color: #0000FF;">END</span>
GO</pre></div></div>

<h3>Move the data over in batches</h3>

<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>;
<span style="color: #0000FF;">set</span> <span style="color: #0000FF;">transaction</span> <span style="color: #0000FF;">isolation</span> <span style="color: #0000FF;">level</span> serializable;
<span style="color: #0000FF;">set</span> deadlock_priority LOW
&nbsp;
<span style="color: #0000FF;">declare</span> @i <span style="color: #0000FF;">int</span>;
<span style="color: #0000FF;">declare</span> @new_i <span style="color: #0000FF;">int</span> <span style="color: #808080;">=</span> <span style="color: #000;">0</span>;
<span style="color: #0000FF;">declare</span> @largestSalesOrderId <span style="color: #0000FF;">int</span>;
<span style="color: #0000FF;">declare</span> @minBatchSize <span style="color: #0000FF;">int</span> <span style="color: #808080;">=</span> <span style="color: #000;">5000</span>
&nbsp;
<span style="color: #0000FF;">set</span> <span style="color: #0000FF;">identity_insert</span> Sales.<span style="color: #202020;">SalesOrderHeader_new</span> <span style="color: #0000FF;">on</span>;
&nbsp;
<span style="color: #008080;">-- largest SalesOrderId to migrate </span>
<span style="color: #0000FF;">select</span> @largestSalesOrderId <span style="color: #808080;">=</span> isnull<span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">max</span><span style="color: #808080;">&#40;</span>SalesOrderID<span style="color: #808080;">&#41;</span>, <span style="color: #000;">0</span><span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">from</span> Sales.<span style="color: #202020;">SalesOrderHeader</span>
&nbsp;
<span style="color: #008080;">-- lowest SalesOrderId to migrate</span>
<span style="color: #0000FF;">select</span> <span style="color: #0000FF;">top</span> <span style="color: #000;">1</span> @i <span style="color: #808080;">=</span> so.<span style="color: #202020;">SalesOrderId</span>
<span style="color: #0000FF;">from</span> Sales.<span style="color: #202020;">SalesOrderHeader</span> so
<span style="color: #0000FF;">left</span> join Sales.<span style="color: #202020;">SalesOrderHeader_new</span> so_new
	<span style="color: #0000FF;">ON</span> so.<span style="color: #202020;">SalesOrderId</span> <span style="color: #808080;">=</span> so_new.<span style="color: #202020;">SalesOrderId</span>
<span style="color: #0000FF;">where</span> so_new.<span style="color: #202020;">SalesOrderId</span> <span style="color: #0000FF;">is</span> null
<span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> so.<span style="color: #202020;">SalesOrderId</span>
&nbsp;
<span style="color: #008080;">-- batch loop</span>
<span style="color: #0000FF;">while</span> @i <span style="color: #808080;">&lt;</span> @largestSalesOrderId
<span style="color: #0000FF;">begin</span>
&nbsp;
    <span style="color: #0000FF;">declare</span> @counter <span style="color: #0000FF;">int</span> <span style="color: #808080;">=</span> <span style="color: #000;">0</span>;
    <span style="color: #0000FF;">declare</span> @error <span style="color: #0000FF;">int</span> <span style="color: #808080;">=</span> <span style="color: #000;">0</span>;
&nbsp;
    <span style="color: #008080;">-- retry loop:</span>
    <span style="color: #0000FF;">while</span> <span style="color: #808080;">&#40;</span><span style="color: #000;">1</span><span style="color: #808080;">=</span><span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>
    <span style="color: #0000FF;">begin</span>
        <span style="color: #0000FF;">begin</span> try
            <span style="color: #0000FF;">select</span> <span style="color: #0000FF;">top</span> <span style="color: #808080;">&#40;</span>@minBatchSize<span style="color: #808080;">&#41;</span> @new_i <span style="color: #808080;">=</span> SalesOrderID
            <span style="color: #0000FF;">from</span> Sales.<span style="color: #202020;">SalesOrderHeader</span>
            <span style="color: #0000FF;">where</span> SalesOrderID <span style="color: #808080;">&gt;</span> @i
            <span style="color: #0000FF;">order</span> <span style="color: #0000FF;">by</span> SalesOrderID <span style="color: #0000FF;">asc</span>;
&nbsp;
            merge Sales.<span style="color: #202020;">SalesOrderHeader_new</span> <span style="color: #0000FF;">as</span> target
            <span style="color: #0000FF;">using</span> <span style="color: #808080;">&#40;</span>
                    <span style="color: #0000FF;">select</span> SalesOrderID, RevisionNumber, OrderDate, DueDate, ShipDate, <span style="color: #808080;">&#91;</span>Status<span style="color: #808080;">&#93;</span>, OnlineOrderFlag, PurchaseOrderNumber, AccountNumber, CustomerID, SalesPersonID, TerritoryID, BillToAddressID, ShipToAddressID, ShipMethodID, CreditCardID, CreditCardApprovalCode, CurrencyRateID, SubTotal, TaxAmt, Freight, Comment, rowguid, ModifiedDate
                    <span style="color: #0000FF;">from</span> Sales.<span style="color: #202020;">SalesOrderHeader</span>
                    <span style="color: #0000FF;">where</span> SalesOrderID <span style="color: #808080;">&gt;</span> @i
                    and SalesOrderID <span style="color: #808080;">&lt;=</span> @new_i
                <span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">as</span> source <span style="color: #808080;">&#40;</span>SalesOrderID, RevisionNumber, OrderDate, DueDate, ShipDate, <span style="color: #808080;">&#91;</span>Status<span style="color: #808080;">&#93;</span>, OnlineOrderFlag, PurchaseOrderNumber, AccountNumber, CustomerID, SalesPersonID, TerritoryID, BillToAddressID, ShipToAddressID, ShipMethodID, CreditCardID, CreditCardApprovalCode, CurrencyRateID, SubTotal, TaxAmt, Freight, Comment, rowguid, ModifiedDate<span style="color: #808080;">&#41;</span>
            <span style="color: #0000FF;">on</span> target.<span style="color: #202020;">SalesOrderID</span> <span style="color: #808080;">=</span> source.<span style="color: #202020;">SalesOrderID</span>
            <span style="color: #0000FF;">when</span> not matched <span style="color: #0000FF;">then</span>
                <span style="color: #0000FF;">insert</span> <span style="color: #808080;">&#40;</span>SalesOrderID, RevisionNumber, OrderDate, DueDate, ShipDate, <span style="color: #808080;">&#91;</span>Status<span style="color: #808080;">&#93;</span>, OnlineOrderFlag, PurchaseOrderNumber, AccountNumber, CustomerID, SalesPersonID, TerritoryID, BillToAddressID, ShipToAddressID, ShipMethodID, CreditCardID, CreditCardApprovalCode, CurrencyRateID, SubTotal, TaxAmt, Freight, Comment, rowguid, ModifiedDate<span style="color: #808080;">&#41;</span>
                <span style="color: #0000FF;">values</span> <span style="color: #808080;">&#40;</span>source.<span style="color: #202020;">SalesOrderID</span>, source.<span style="color: #202020;">RevisionNumber</span>, source.<span style="color: #202020;">OrderDate</span>, source.<span style="color: #202020;">DueDate</span>, source.<span style="color: #202020;">ShipDate</span>, source.<span style="color: #808080;">&#91;</span>Status<span style="color: #808080;">&#93;</span>, source.<span style="color: #202020;">OnlineOrderFlag</span>, source.<span style="color: #202020;">PurchaseOrderNumber</span>, source.<span style="color: #202020;">AccountNumber</span>, source.<span style="color: #202020;">CustomerID</span>, source.<span style="color: #202020;">SalesPersonID</span>, source.<span style="color: #202020;">TerritoryID</span>, source.<span style="color: #202020;">BillToAddressID</span>, source.<span style="color: #202020;">ShipToAddressID</span>, source.<span style="color: #202020;">ShipMethodID</span>, source.<span style="color: #202020;">CreditCardID</span>, source.<span style="color: #202020;">CreditCardApprovalCode</span>, source.<span style="color: #202020;">CurrencyRateID</span>, source.<span style="color: #202020;">SubTotal</span>, source.<span style="color: #202020;">TaxAmt</span>, source.<span style="color: #202020;">Freight</span>, source.<span style="color: #202020;">Comment</span>, source.<span style="color: #202020;">rowguid</span>, source.<span style="color: #202020;">ModifiedDate</span><span style="color: #808080;">&#41;</span>;
&nbsp;
            <span style="color: #008080;">--success            </span>
            <span style="color: #0000FF;">select</span> @i <span style="color: #808080;">=</span> @new_i, @error <span style="color: #808080;">=</span> <span style="color: #000;">0</span>;
            <span style="color: #0000FF;">break</span>;
&nbsp;
        <span style="color: #0000FF;">end</span> try
        <span style="color: #0000FF;">begin</span> catch
            <span style="color: #0000FF;">select</span> @counter    <span style="color: #808080;">=</span> @counter <span style="color: #808080;">+</span> <span style="color: #000;">1</span>,
                @error <span style="color: #808080;">=</span> <span style="color: #FF00FF;">@@ERROR</span>;
&nbsp;
            <span style="color: #0000FF;">if</span> <span style="color: #808080;">&#40;</span>@counter <span style="color: #808080;">&gt;=</span> <span style="color: #000;">5</span><span style="color: #808080;">&#41;</span>
            <span style="color: #0000FF;">begin</span>
                <span style="color: #008080;">-- this batch failed five times! Something's wrong</span>
                <span style="color: #0000FF;">raiserror</span> <span style="color: #808080;">&#40;</span>N<span style="color: #FF0000;">'Could not copy Sales.SalesOrderHeader rows to Sales.SalesOrderHeader_new'</span>,
                    <span style="color: #000;">16</span>, <span style="color: #000;">1</span>, @error<span style="color: #808080;">&#41;</span>;
                <span style="color: #0000FF;">break</span>;
            <span style="color: #0000FF;">end</span>
        <span style="color: #0000FF;">end</span> catch
    <span style="color: #0000FF;">end</span> 
&nbsp;
    <span style="color: #0000FF;">if</span> @error <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">0</span>
    <span style="color: #0000FF;">begin</span>
        <span style="color: #008080;">-- an error has been raised. Discontinue.</span>
        <span style="color: #0000FF;">break</span>;
    <span style="color: #0000FF;">end</span>
&nbsp;
<span style="color: #0000FF;">end</span>
&nbsp;
<span style="color: #0000FF;">set</span> <span style="color: #0000FF;">identity_insert</span> Sales.<span style="color: #202020;">SalesOrderHeader_new</span> <span style="color: #0000FF;">off</span>;
go</pre></div></div>

<h3>Do The Switch</h3>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">set</span> xact_abort <span style="color: #0000FF;">on</span>
<span style="color: #0000FF;">set</span> deadlock_priority high
<span style="color: #0000FF;">set</span> <span style="color: #0000FF;">transaction</span> <span style="color: #0000FF;">isolation</span> <span style="color: #0000FF;">level</span> serializable
<span style="color: #0000FF;">begin</span> <span style="color: #0000FF;">transaction</span>
<span style="color: #0000FF;">IF</span> <span style="color: #808080;">EXISTS</span> 
    <span style="color: #808080;">&#40;</span>
        <span style="color: #0000FF;">SELECT</span> <span style="color: #000;">1</span> 
        <span style="color: #0000FF;">FROM</span> <span style="color: #808080;">IN</span>F<span style="color: #808080;">OR</span>MATION_SCHEMA.<span style="color: #202020;">TABLES</span> 
        <span style="color: #0000FF;">WHERE</span> TABLE_SCHEMA <span style="color: #808080;">=</span> <span style="color: #FF0000;">'Sales'</span> 
        <span style="color: #808080;">AND</span> TABLE_NAME <span style="color: #808080;">=</span> <span style="color: #FF0000;">'SalesOrderHeader_new'</span>
    <span style="color: #808080;">&#41;</span>
<span style="color: #0000FF;">BEGIN</span>
    <span style="color: #0000FF;">begin</span> try
        <span style="color: #008080;">-- rename pks and indexes from original table</span>
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.PK_SalesOrderHeader_SalesOrderID'</span>, N<span style="color: #FF0000;">'PK_SalesOrderHeader_old_SalesOrderID'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.SalesOrderHeader.AK_SalesOrderHeader_rowguid'</span>, N<span style="color: #FF0000;">'AK_SalesOrderHeader_old_rowguid'</span>, N<span style="color: #FF0000;">'INDEX'</span>
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.SalesOrderHeader.AK_SalesOrderHeader_SalesOrderNumber'</span>, N<span style="color: #FF0000;">'AK_SalesOrderHeader_old_SalesOrderNumber'</span>, N<span style="color: #FF0000;">'INDEX'</span>
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.SalesOrderHeader.IX_SalesOrderHeader_CustomerID'</span>, N<span style="color: #FF0000;">'IX_SalesOrderHeader_old_CustomerID'</span>, N<span style="color: #FF0000;">'INDEX'</span>
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.SalesOrderHeader.IX_SalesOrderHeader_SalesPersonID'</span>, N<span style="color: #FF0000;">'IX_SalesOrderHeader_old_SalesPersonID'</span>, N<span style="color: #FF0000;">'INDEX'</span>
&nbsp;
        <span style="color: #008080;">-- rename checks and defaults</span>
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.CK_SalesOrderHeader_Status'</span>, <span style="color: #FF0000;">'CK_SalesOrderHeader_old_Status'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.CK_SalesOrderHeader_DueDate'</span>, <span style="color: #FF0000;">'CK_SalesOrderHeader_old_DueDate'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.CK_SalesOrderHeader_ShipDate'</span>, <span style="color: #FF0000;">'CK_SalesOrderHeader_old_ShipDate'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.CK_SalesOrderHeader_SubTotal'</span>, <span style="color: #FF0000;">'CK_SalesOrderHeader_old_SubTotal'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.CK_SalesOrderHeader_TaxAmt'</span>, <span style="color: #FF0000;">'CK_SalesOrderHeader_old_TaxAmt'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.CK_SalesOrderHeader_Freight'</span>, <span style="color: #FF0000;">'CK_SalesOrderHeader_old_Freight'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_RevisionNumber'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_old_RevisionNumber'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_OrderDate'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_old_OrderDate'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_Status'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_old_Status'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_OnlineOrderFlag'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_old_OnlineOrderFlag'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_SubTotal'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_old_SubTotal'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_TaxAmt'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_old_TaxAmt'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_Freight'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_old_Freight'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_rowguid'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_old_rowguid'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_ModifiedDate'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_old_ModifiedDate'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
&nbsp;
        <span style="color: #008080;">-- drop fks from original table</span>
        <span style="color: #0000FF;">alter</span> <span style="color: #0000FF;">table</span> Sales.<span style="color: #202020;">SalesOrderHeader</span>
            <span style="color: #0000FF;">drop</span> <span style="color: #0000FF;">constraint</span> 
            FK_SalesOrderHeader_Address_BillToAddressID,
            FK_SalesOrderHeader_Address_ShipToAddressID,
            FK_SalesOrderHeader_CreditCard_CreditCardID,
            FK_SalesOrderHeader_CurrencyRate_CurrencyRateID,
            FK_SalesOrderHeader_Customer_CustomerID,
            FK_SalesOrderHeader_SalesPerson_SalesPersonID,
            FK_SalesOrderHeader_ShipMethod_ShipMethodID,
            FK_SalesOrderHeader_SalesTerritory_TerritoryID
&nbsp;
        <span style="color: #008080;">-- drop fks to original table</span>
        <span style="color: #0000FF;">alter</span> <span style="color: #0000FF;">table</span> Sales.<span style="color: #202020;">SalesOrderDetail</span>
            <span style="color: #0000FF;">drop</span> <span style="color: #0000FF;">constraint</span> FK_SalesOrderDetail_SalesOrderHeader_SalesOrderID;
&nbsp;
        <span style="color: #0000FF;">alter</span> <span style="color: #0000FF;">table</span> Sales.<span style="color: #202020;">SalesOrderHeaderSalesReason</span>
            <span style="color: #0000FF;">drop</span> <span style="color: #0000FF;">constraint</span> FK_SalesOrderHeaderSalesReason_SalesOrderHeader_SalesOrderID;
&nbsp;
        <span style="color: #008080;">-- drop triggers on original table</span>
        <span style="color: #0000FF;">drop</span> <span style="color: #0000FF;">trigger</span> Sales.<span style="color: #202020;">t_i_SalesOrderHeader</span>;
        <span style="color: #0000FF;">drop</span> <span style="color: #0000FF;">trigger</span> Sales.<span style="color: #202020;">t_u_SalesOrderHeader</span>;
        <span style="color: #0000FF;">drop</span> <span style="color: #0000FF;">trigger</span> Sales.<span style="color: #202020;">t_d_SalesOrderHeader</span>;
&nbsp;
        <span style="color: #008080;">-- drop uSalesOrderHeader (but remember its definition)</span>
        <span style="color: #0000FF;">declare</span> @triggersql <span style="color: #0000FF;">nvarchar</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">max</span><span style="color: #808080;">&#41;</span>;
        <span style="color: #0000FF;">select</span> @triggersql <span style="color: #808080;">=</span> OBJECT_DEF<span style="color: #808080;">IN</span>ITION<span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">object_id</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">from</span> sys.<span style="color: #202020;">triggers</span> <span style="color: #0000FF;">where</span> name <span style="color: #808080;">=</span> <span style="color: #FF0000;">'uSalesOrderHeader'</span>;
        <span style="color: #0000FF;">drop</span> <span style="color: #0000FF;">trigger</span> Sales.<span style="color: #202020;">uSalesOrderHeader</span>; 
&nbsp;
        <span style="color: #008080;">-- rename original table to &quot;old&quot;</span>
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.SalesOrderHeader'</span>, N<span style="color: #FF0000;">'SalesOrderHeader_old'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
&nbsp;
        <span style="color: #008080;">--rename the new indexes</span>
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.PK_SalesOrderHeader_new_SalesOrderID'</span>, N<span style="color: #FF0000;">'PK_SalesOrderHeader_SalesOrderID'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.SalesOrderHeader_new.AK_SalesOrderHeader_new_rowguid'</span>, N<span style="color: #FF0000;">'AK_SalesOrderHeader_rowguid'</span>, N<span style="color: #FF0000;">'INDEX'</span>
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.SalesOrderHeader_new.AK_SalesOrderHeader_new_SalesOrderNumber'</span>, N<span style="color: #FF0000;">'AK_SalesOrderHeader_SalesOrderNumber'</span>, N<span style="color: #FF0000;">'INDEX'</span>
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.SalesOrderHeader_new.IX_SalesOrderHeader_new_CustomerID'</span>, N<span style="color: #FF0000;">'IX_SalesOrderHeader_CustomerID'</span>, N<span style="color: #FF0000;">'INDEX'</span>
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.SalesOrderHeader_new.IX_SalesOrderHeader_new_SalesPersonID'</span>, N<span style="color: #FF0000;">'IX_SalesOrderHeader_SalesPersonID'</span>, N<span style="color: #FF0000;">'INDEX'</span>
&nbsp;
        <span style="color: #008080;">-- rename the new checks and defaults</span>
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.CK_SalesOrderHeader_new_Status'</span>, <span style="color: #FF0000;">'CK_SalesOrderHeader_Status'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.CK_SalesOrderHeader_new_DueDate'</span>, <span style="color: #FF0000;">'CK_SalesOrderHeader_DueDate'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.CK_SalesOrderHeader_new_ShipDate'</span>, <span style="color: #FF0000;">'CK_SalesOrderHeader_ShipDate'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.CK_SalesOrderHeader_new_SubTotal'</span>, <span style="color: #FF0000;">'CK_SalesOrderHeader_SubTotal'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.CK_SalesOrderHeader_new_TaxAmt'</span>, <span style="color: #FF0000;">'CK_SalesOrderHeader_TaxAmt'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.CK_SalesOrderHeader_new_Freight'</span>, <span style="color: #FF0000;">'CK_SalesOrderHeader_Freight'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_new_RevisionNumber'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_RevisionNumber'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_new_OrderDate'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_OrderDate'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_new_Status'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_Status'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_new_OnlineOrderFlag'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_OnlineOrderFlag'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_new_SubTotal'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_SubTotal'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_new_TaxAmt'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_TaxAmt'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_new_Freight'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_Freight'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_new_rowguid'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_rowguid'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_new_ModifiedDate'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_ModifiedDate'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
&nbsp;
        <span style="color: #008080;">-- rename &quot;new&quot; table</span>
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.SalesOrderHeader_new'</span>, N<span style="color: #FF0000;">'SalesOrderHeader'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
&nbsp;
        <span style="color: #008080;">--rename fks pointing out</span>
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.FK_SalesOrderHeader_new_Address_BillToAddressID'</span>, N<span style="color: #FF0000;">'FK_SalesOrderHeader_Address_BillToAddressID'</span>, N<span style="color: #FF0000;">'OBJECT'</span>
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.FK_SalesOrderHeader_new_Address_ShipToAddressID'</span>, N<span style="color: #FF0000;">'FK_SalesOrderHeader_Address_ShipToAddressID'</span>, N<span style="color: #FF0000;">'OBJECT'</span> 
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.FK_SalesOrderHeader_new_CreditCard_CreditCardID'</span>, N<span style="color: #FF0000;">'FK_SalesOrderHeader_CreditCard_CreditCardID'</span>, N<span style="color: #FF0000;">'OBJECT'</span>
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.FK_SalesOrderHeader_new_CurrencyRate_CurrencyRateID'</span>, N<span style="color: #FF0000;">'FK_SalesOrderHeader_CurrencyRate_CurrencyRateID'</span>, N<span style="color: #FF0000;">'OBJECT'</span>
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.FK_SalesOrderHeader_new_Customer_CustomerID'</span>, N<span style="color: #FF0000;">'FK_SalesOrderHeader_Customer_CustomerID'</span>, N<span style="color: #FF0000;">'OBJECT'</span>
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.FK_SalesOrderHeader_new_SalesPerson_SalesPersonID'</span>, N<span style="color: #FF0000;">'FK_SalesOrderHeader_SalesPerson_SalesPersonID'</span>, N<span style="color: #FF0000;">'OBJECT'</span>
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.FK_SalesOrderHeader_new_ShipMethod_ShipMethodID'</span>, N<span style="color: #FF0000;">'FK_SalesOrderHeader_ShipMethod_ShipMethodID'</span>, N<span style="color: #FF0000;">'OBJECT'</span>
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.FK_SalesOrderHeader_new_SalesTerritory_TerritoryID'</span>, N<span style="color: #FF0000;">'FK_SalesOrderHeader_SalesTerritory_TerritoryID'</span>, N<span style="color: #FF0000;">'OBJECT'</span>
&nbsp;
        <span style="color: #008080;">-- re-add fks pointing in (without checks for now)</span>
        <span style="color: #0000FF;">alter</span> <span style="color: #0000FF;">table</span> Sales.<span style="color: #202020;">SalesOrderDetail</span> <span style="color: #0000FF;">with</span> <span style="color: #0000FF;">nocheck</span> <span style="color: #0000FF;">add</span>
        <span style="color: #0000FF;">constraint</span> FK_SalesOrderDetail_SalesOrderHeader_SalesOrderID <span style="color: #0000FF;">foreign</span> <span style="color: #0000FF;">key</span> <span style="color: #808080;">&#40;</span>SalesOrderId<span style="color: #808080;">&#41;</span>
            <span style="color: #0000FF;">references</span> Sales.<span style="color: #202020;">SalesOrderHeader</span><span style="color: #808080;">&#40;</span>SalesOrderId<span style="color: #808080;">&#41;</span> 
&nbsp;
        <span style="color: #0000FF;">alter</span> <span style="color: #0000FF;">table</span> Sales.<span style="color: #202020;">SalesOrderHeaderSalesReason</span> <span style="color: #0000FF;">with</span> <span style="color: #0000FF;">nocheck</span> <span style="color: #0000FF;">add</span>
        <span style="color: #0000FF;">constraint</span> FK_SalesOrderHeaderSalesReason_SalesOrderHeader_SalesOrderID <span style="color: #0000FF;">foreign</span> <span style="color: #0000FF;">key</span> <span style="color: #808080;">&#40;</span>SalesOrderId<span style="color: #808080;">&#41;</span>
            <span style="color: #0000FF;">references</span> Sales.<span style="color: #202020;">SalesOrderHeader</span><span style="color: #808080;">&#40;</span>SalesOrderId<span style="color: #808080;">&#41;</span>
&nbsp;
        <span style="color: #008080;">-- re-add trigger (use sp_executesql in order to keep in transaction)</span>
        <span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_executesql</span> @triggersql;
    <span style="color: #0000FF;">end</span> try
&nbsp;
    <span style="color: #0000FF;">begin</span> catch
        <span style="color: #0000FF;">declare</span> @error <span style="color: #0000FF;">nvarchar</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">max</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">=</span> ERR<span style="color: #808080;">OR</span>_MESSAGE<span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span>;
        <span style="color: #0000FF;">select</span> <span style="color: #FF0000;">'An error was encountered... Rolling back'</span> <span style="color: #0000FF;">as</span> <span style="color: #808080;">&#91;</span>message<span style="color: #808080;">&#93;</span>,
            @error <span style="color: #0000FF;">as</span> errorMessage
        <span style="color: #0000FF;">raiserror</span> <span style="color: #808080;">&#40;</span>@error, <span style="color: #000;">16</span>, <span style="color: #000;">1</span><span style="color: #808080;">&#41;</span>
        <span style="color: #0000FF;">rollback</span>
    <span style="color: #0000FF;">end</span> catch
<span style="color: #0000FF;">END</span>
<span style="color: #0000FF;">if</span> <span style="color: #FF00FF;">@@TRANCOUNT</span> <span style="color: #808080;">&gt;</span> <span style="color: #000;">0</span>
    <span style="color: #0000FF;">commit</span>
GO</pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://michaeljswart.com/2012/04/modifying-tables-online-part-3-example-with-error-handling/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://michaeljswart.com/2012/04/modifying-tables-online-part-3-example-with-error-handling/</feedburner:origLink></item>
		<item>
		<title>Modifying Tables Online – Part 2: Implementation Example</title>
		<link>http://feedproxy.google.com/~r/TheDatabaseWhisperer/~3/wsCtPkS1MUE/</link>
		<comments>http://michaeljswart.com/2012/04/modifying-tables-online-part-2-implementation-example/#comments</comments>
		<pubDate>Tue, 17 Apr 2012 16:00:31 +0000</pubDate>
		<dc:creator>Michael J. Swart</dc:creator>
				<category><![CDATA[SQLServerPedia Syndication]]></category>
		<category><![CDATA[Technical Articles]]></category>
		<category><![CDATA["sql server"]]></category>
		<category><![CDATA[online schema changes]]></category>
		<category><![CDATA[table migrations]]></category>

		<guid isPermaLink="false">http://michaeljswart.com/?p=2666</guid>
		<description><![CDATA[So this is me putting the strategy into practice. I've decided to migrate a table from everyone's favorite sample datatabase Adventureworks (2012 edition).]]></description>
			<content:encoded><![CDATA[<div style="background: #e9f4d9; border: 1px solid #587E25; display: block; height: auto; max-width: 96%; margin: 4px; padding: 10px;">
<p><strong>SERIES: Modifying Tables Online</strong></p>
<p>In the next few days I want to describe a way to modify the definition of very large tables while keeping the table available for other queries. Some table changes are already <em>online</em> operations. But <em>offline</em> changes need extra work to keep the table available. I explore one way to do that in this series.</p>
<p>This article used to be a single blog post, but I broke it into four parts because it seemed too long. Read Part 1, and understand the strategy I&#8217;m using. Treat Parts 2-4 as appendixes. When you want to use this plan (or one like it), come back and use them as examples. You won&#8217;t be able to make use of the examples by cutting and pasting directly (unless you happen to be running an bike equipment store called Adventureworks), but modifications shouldn&#8217;t be too hard.</p>
<ul>
<li><a href="http://michaeljswart.com/2012/04/modifying-tables-online-part-1-migration-strategy/">Part 1: Migration Strategy</a></li>
<li><strong>Part 2: Implementation Example</strong></li>
<li><a href="http://michaeljswart.com/2012/04/modifying-tables-online-part-3-example-with-error-handling/">Part 3: Same Example With Error Handling</a></li>
<li><a href="http://michaeljswart.com/2012/04/modifying-tables-online-part-4-testing/">Part 4: Testing</a></li>
<li><a href="http://michaeljswart.com/2012/04/modifying-tables-online-part-5-just-one-more-thing/">Part 5: Just One More Thing</a></li>
</ul>
</div>
<p>So this is me putting the strategy into practice. I&#8217;ve decided to migrate a table from everyone&#8217;s favorite sample datatabase Adventureworks (2012 edition). And the change that I&#8217;m implementing is the addition of a rowversion column which is considered an offline operation:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">-- adding a rowversion column offline</span>
<span style="color: #0000FF;">ALTER</span> <span style="color: #0000FF;">TABLE</span> Sales.<span style="color: #202020;">SalesOrderHeader</span>
<span style="color: #0000FF;">ADD</span> <span style="color: #808080;">&#91;</span>rowversion<span style="color: #808080;">&#93;</span> rowversion;</pre></div></div>

<p>The table I picked is <strong>Sales.SalesOrderHeader</strong>. I picked this table because it&#8217;s got foreign keys (columns pointing to records in other tables). And other tables have foreign keys pointing to SalesOrderHeader too. I also noticed that this table has a large variety of objects and settings which are dependent on it. Besides the foreign keys, other dependencies include</p>
<ul>
<li>triggers</li>
<li>indexes (some UNIQUE and some not, some nonclustered and one not)</li>
<li>an identity column</li>
<li>default constraints</li>
<li>check constraints</li>
<li>computed columns</li>
</ul>
<p>These make Sales.SalesOrderHeader interesting. So here&#8217;s the script (an implementation of the strategy already mentioned). You might be surprised at its size, it&#8217;s directly related to how <em>interesting</em> the table is. I don&#8217;t use any 2012-only features so you&#8217;ll be able to use these examples on SQL Server 2008 or SQL Server 2008 R2.</p>
<h3>Create Staging Table</h3>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">use</span> AdventureWorks2012
&nbsp;
<span style="color: #008080;">-- new table</span>
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">TABLE</span> Sales.<span style="color: #202020;">SalesOrderHeader_new</span><span style="color: #808080;">&#40;</span>
	SalesOrderID <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: #0000FF;">FOR</span> <span style="color: #0000FF;">REPLICATION</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
	RevisionNumber <span style="color: #0000FF;">tinyint</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
	OrderDate <span style="color: #0000FF;">datetime</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
	DueDate <span style="color: #0000FF;">datetime</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
	ShipDate <span style="color: #0000FF;">datetime</span> <span style="color: #808080;">NULL</span>,
	<span style="color: #808080;">&#91;</span>Status<span style="color: #808080;">&#93;</span> <span style="color: #0000FF;">tinyint</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
	OnlineOrderFlag dbo.<span style="color: #202020;">Flag</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
	SalesOrderNumber  <span style="color: #0000FF;">AS</span> <span style="color: #808080;">&#40;</span>isnull<span style="color: #808080;">&#40;</span>N<span style="color: #FF0000;">'SO'</span><span style="color: #808080;">+</span><span style="color: #0000FF;">CONVERT</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">nvarchar</span><span style="color: #808080;">&#40;</span><span style="color: #000;">23</span><span style="color: #808080;">&#41;</span>,SalesOrderID<span style="color: #808080;">&#41;</span>,N<span style="color: #FF0000;">'*** ERROR ***'</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>,
	PurchaseOrderNumber dbo.<span style="color: #202020;">OrderNumber</span> <span style="color: #808080;">NULL</span>,
	AccountNumber dbo.<span style="color: #202020;">AccountNumber</span> <span style="color: #808080;">NULL</span>,
	CustomerID <span style="color: #0000FF;">int</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
	SalesPersonID <span style="color: #0000FF;">int</span> <span style="color: #808080;">NULL</span>,
	TerritoryID <span style="color: #0000FF;">int</span> <span style="color: #808080;">NULL</span>,
	BillToAddressID <span style="color: #0000FF;">int</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
	ShipToAddressID <span style="color: #0000FF;">int</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
	ShipMethodID <span style="color: #0000FF;">int</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
	CreditCardID <span style="color: #0000FF;">int</span> <span style="color: #808080;">NULL</span>,
	CreditCardApprovalCode <span style="color: #0000FF;">varchar</span><span style="color: #808080;">&#40;</span><span style="color: #000;">15</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">NULL</span>,
	CurrencyRateID <span style="color: #0000FF;">int</span> <span style="color: #808080;">NULL</span>,
	SubTotal <span style="color: #0000FF;">money</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
	TaxAmt <span style="color: #0000FF;">money</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
	Freight <span style="color: #0000FF;">money</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
	TotalDue  <span style="color: #0000FF;">AS</span> <span style="color: #808080;">&#40;</span>isnull<span style="color: #808080;">&#40;</span><span style="color: #808080;">&#40;</span>SubTotal<span style="color: #808080;">+</span>TaxAmt<span style="color: #808080;">&#41;</span><span style="color: #808080;">+</span>Freight,<span style="color: #808080;">&#40;</span><span style="color: #000;">0</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>,
	Comment <span style="color: #0000FF;">nvarchar</span><span style="color: #808080;">&#40;</span><span style="color: #000;">128</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">NULL</span>,
	rowguid <span style="color: #0000FF;">uniqueidentifier</span> <span style="color: #0000FF;">ROWGUIDCOL</span>  <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
	ModifiedDate <span style="color: #0000FF;">datetime</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>,
	<span style="color: #808080;">&#91;</span>Rowversion<span style="color: #808080;">&#93;</span> rowversion <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span>, <span style="color: #008080;">-- This is the new column!!</span>
	<span style="color: #0000FF;">constraint</span> PK_SalesOrderHeader_new_SalesOrderID
		<span style="color: #0000FF;">primary</span> <span style="color: #0000FF;">key</span> <span style="color: #0000FF;">clustered</span> <span style="color: #808080;">&#40;</span>SalesOrderID <span style="color: #0000FF;">ASC</span><span style="color: #808080;">&#41;</span>,
	<span style="color: #0000FF;">constraint</span> FK_SalesOrderHeader_new_Address_BillToAddressID
		<span style="color: #0000FF;">foreign</span> <span style="color: #0000FF;">key</span><span style="color: #808080;">&#40;</span>BillToAddressID<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">references</span> Person.<span style="color: #808080;">&#91;</span>Address<span style="color: #808080;">&#93;</span> <span style="color: #808080;">&#40;</span>AddressID<span style="color: #808080;">&#41;</span>,
	<span style="color: #0000FF;">constraint</span> FK_SalesOrderHeader_new_Address_ShipToAddressID
		<span style="color: #0000FF;">foreign</span> <span style="color: #0000FF;">key</span><span style="color: #808080;">&#40;</span>ShipToAddressID<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">references</span> Person.<span style="color: #808080;">&#91;</span>Address<span style="color: #808080;">&#93;</span> <span style="color: #808080;">&#40;</span>AddressID<span style="color: #808080;">&#41;</span>,
	<span style="color: #0000FF;">constraint</span> FK_SalesOrderHeader_new_CreditCard_CreditCardID
		<span style="color: #0000FF;">foreign</span> <span style="color: #0000FF;">key</span><span style="color: #808080;">&#40;</span>CreditCardID<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">references</span> Sales.<span style="color: #202020;">CreditCard</span> <span style="color: #808080;">&#40;</span>CreditCardID<span style="color: #808080;">&#41;</span>,
	<span style="color: #0000FF;">constraint</span> FK_SalesOrderHeader_new_CurrencyRate_CurrencyRateID
		<span style="color: #0000FF;">foreign</span> <span style="color: #0000FF;">key</span><span style="color: #808080;">&#40;</span>CurrencyRateID<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">references</span> Sales.<span style="color: #202020;">CurrencyRate</span> <span style="color: #808080;">&#40;</span>CurrencyRateID<span style="color: #808080;">&#41;</span>,
	<span style="color: #0000FF;">constraint</span> FK_SalesOrderHeader_new_Customer_CustomerID
		<span style="color: #0000FF;">foreign</span> <span style="color: #0000FF;">key</span><span style="color: #808080;">&#40;</span>CustomerID<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">references</span> Sales.<span style="color: #202020;">Customer</span> <span style="color: #808080;">&#40;</span>CustomerID<span style="color: #808080;">&#41;</span>,
	<span style="color: #0000FF;">constraint</span> FK_SalesOrderHeader_new_SalesPerson_SalesPersonID
		<span style="color: #0000FF;">foreign</span> <span style="color: #0000FF;">key</span><span style="color: #808080;">&#40;</span>SalesPersonID<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">references</span> Sales.<span style="color: #202020;">SalesPerson</span> <span style="color: #808080;">&#40;</span>BusinessEntityID<span style="color: #808080;">&#41;</span>,
	<span style="color: #0000FF;">constraint</span> FK_SalesOrderHeader_new_SalesTerritory_TerritoryID
		<span style="color: #0000FF;">foreign</span> <span style="color: #0000FF;">key</span><span style="color: #808080;">&#40;</span>TerritoryID<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">references</span> Sales.<span style="color: #202020;">SalesTerritory</span> <span style="color: #808080;">&#40;</span>TerritoryID<span style="color: #808080;">&#41;</span>,
	<span style="color: #0000FF;">constraint</span> FK_SalesOrderHeader_new_ShipMethod_ShipMethodID
		<span style="color: #0000FF;">foreign</span> <span style="color: #0000FF;">key</span><span style="color: #808080;">&#40;</span>ShipMethodID<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">references</span> Purchasing.<span style="color: #202020;">ShipMethod</span> <span style="color: #808080;">&#40;</span>ShipMethodID<span style="color: #808080;">&#41;</span>,
	<span style="color: #0000FF;">constraint</span> CK_SalesOrderHeader_new_DueDate
		<span style="color: #0000FF;">check</span> <span style="color: #808080;">&#40;</span>DueDate<span style="color: #808080;">&gt;=</span>OrderDate<span style="color: #808080;">&#41;</span>,
	<span style="color: #0000FF;">constraint</span> CK_SalesOrderHeader_new_Freight
		<span style="color: #0000FF;">check</span> <span style="color: #808080;">&#40;</span>Freight<span style="color: #808080;">&gt;=</span><span style="color: #000;">0.00</span><span style="color: #808080;">&#41;</span>,
	<span style="color: #0000FF;">constraint</span> CK_SalesOrderHeader_new_ShipDate
		<span style="color: #0000FF;">check</span> <span style="color: #808080;">&#40;</span>ShipDate<span style="color: #808080;">&gt;=</span>OrderDate or ShipDate <span style="color: #0000FF;">is</span> null<span style="color: #808080;">&#41;</span>,
	<span style="color: #0000FF;">constraint</span> CK_SalesOrderHeader_new_Status
		<span style="color: #0000FF;">check</span> <span style="color: #808080;">&#40;</span><span style="color: #808080;">&#91;</span>Status<span style="color: #808080;">&#93;</span><span style="color: #808080;">&gt;=</span><span style="color: #000;">0</span> and <span style="color: #808080;">&#91;</span>Status<span style="color: #808080;">&#93;</span><span style="color: #808080;">=</span><span style="color: #000;">0.00</span><span style="color: #808080;">&#41;</span>,
	<span style="color: #0000FF;">constraint</span> CK_SalesOrderHeader_new_TaxAmt
		<span style="color: #0000FF;">check</span> <span style="color: #808080;">&#40;</span>TaxAmt<span style="color: #808080;">&gt;=</span><span style="color: #000;">0.00</span><span style="color: #808080;">&#41;</span>
<span style="color: #808080;">&#41;</span>
&nbsp;
<span style="color: #008080;">-- add default constraints</span>
<span style="color: #0000FF;">alter</span> <span style="color: #0000FF;">table</span> Sales.<span style="color: #202020;">SalesOrderHeader_new</span> <span style="color: #0000FF;">add</span>
<span style="color: #0000FF;">constraint</span> DF_SalesOrderHeader_new_RevisionNumber
	<span style="color: #0000FF;">default</span> <span style="color: #000;">0</span> <span style="color: #0000FF;">for</span> RevisionNumber,
<span style="color: #0000FF;">constraint</span> DF_SalesOrderHeader_new_OrderDate
	<span style="color: #0000FF;">default</span> <span style="color: #FF00FF;">getdate</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">for</span> OrderDate,
<span style="color: #0000FF;">constraint</span> DF_SalesOrderHeader_new_Status
	<span style="color: #0000FF;">default</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">for</span> <span style="color: #808080;">&#91;</span>Status<span style="color: #808080;">&#93;</span>,
<span style="color: #0000FF;">constraint</span> DF_SalesOrderHeader_new_OnlineOrderFlag
	<span style="color: #0000FF;">default</span> <span style="color: #000;">1</span> <span style="color: #0000FF;">for</span> OnlineOrderFlag,
<span style="color: #0000FF;">constraint</span> DF_SalesOrderHeader_new_SubTotal
	<span style="color: #0000FF;">default</span> <span style="color: #000;">0.00</span> <span style="color: #0000FF;">for</span> SubTotal,
<span style="color: #0000FF;">constraint</span> DF_SalesOrderHeader_new_TaxAmt
	<span style="color: #0000FF;">default</span> <span style="color: #000;">0.00</span> <span style="color: #0000FF;">for</span> TaxAmt,
<span style="color: #0000FF;">constraint</span> DF_SalesOrderHeader_new_Freight
	<span style="color: #0000FF;">default</span> <span style="color: #000;">0.00</span> <span style="color: #0000FF;">for</span> Freight,
<span style="color: #0000FF;">constraint</span> DF_SalesOrderHeader_new_rowguid
	<span style="color: #0000FF;">default</span> newid<span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">for</span> rowguid,
<span style="color: #0000FF;">constraint</span> DF_SalesOrderHeader_new_ModifiedDate
	<span style="color: #0000FF;">default</span> <span style="color: #FF00FF;">getdate</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">for</span> ModifiedDate
&nbsp;
	<span style="color: #008080;">-- two nc ak</span>
<span style="color: #0000FF;">create</span> <span style="color: #0000FF;">unique</span> <span style="color: #0000FF;">nonclustered</span> <span style="color: #0000FF;">index</span> AK_SalesOrderHeader_new_rowguid
	<span style="color: #0000FF;">on</span> Sales.<span style="color: #202020;">SalesOrderHeader_new</span><span style="color: #808080;">&#40;</span>rowguid <span style="color: #0000FF;">ASC</span><span style="color: #808080;">&#41;</span>
&nbsp;
<span style="color: #0000FF;">create</span> <span style="color: #0000FF;">unique</span> <span style="color: #0000FF;">nonclustered</span> <span style="color: #0000FF;">index</span> AK_SalesOrderHeader_new_SalesOrderNumber
	<span style="color: #0000FF;">on</span> Sales.<span style="color: #202020;">SalesOrderHeader_new</span><span style="color: #808080;">&#40;</span>SalesOrderNumber<span style="color: #808080;">&#41;</span>
&nbsp;
	<span style="color: #008080;">-- two nc ix</span>
<span style="color: #0000FF;">create</span> <span style="color: #0000FF;">nonclustered</span> <span style="color: #0000FF;">index</span> IX_SalesOrderHeader_new_CustomerID
	<span style="color: #0000FF;">on</span> Sales.<span style="color: #202020;">SalesOrderHeader_new</span><span style="color: #808080;">&#40;</span>CustomerID<span style="color: #808080;">&#41;</span>
&nbsp;
<span style="color: #0000FF;">create</span> <span style="color: #0000FF;">nonclustered</span> <span style="color: #0000FF;">index</span> IX_SalesOrderHeader_new_SalesPersonID
	<span style="color: #0000FF;">on</span> Sales.<span style="color: #202020;">SalesOrderHeader_new</span><span style="color: #808080;">&#40;</span>SalesPersonID<span style="color: #808080;">&#41;</span>
GO</pre></div></div>

<h3>Add Triggers</h3>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/*
create triggers to maintain new table
*/</span>
&nbsp;
<span style="color: #0000FF;">use</span> AdventureWorks2012;
go
&nbsp;
<span style="color: #0000FF;">create</span> <span style="color: #0000FF;">trigger</span> t_i_SalesOrderHeader
<span style="color: #0000FF;">on</span> Sales.<span style="color: #202020;">SalesOrderHeader</span>
<span style="color: #0000FF;">after</span> <span style="color: #0000FF;">insert</span>
<span style="color: #0000FF;">as</span>
	<span style="color: #0000FF;">set</span> <span style="color: #0000FF;">identity_insert</span> Sales.<span style="color: #202020;">SalesOrderHeader_new</span> <span style="color: #0000FF;">on</span>;
&nbsp;
	<span style="color: #0000FF;">insert</span> SalesOrderHeader_new<span style="color: #808080;">&#40;</span>SalesOrderID, RevisionNumber, OrderDate, DueDate, ShipDate, <span style="color: #808080;">&#91;</span>Status<span style="color: #808080;">&#93;</span>, OnlineOrderFlag, PurchaseOrderNumber, AccountNumber, CustomerID, SalesPersonID, TerritoryID, BillToAddressID, ShipToAddressID, ShipMethodID, CreditCardID, CreditCardApprovalCode, CurrencyRateID, SubTotal, TaxAmt, Freight, Comment, rowguid, ModifiedDate<span style="color: #808080;">&#41;</span>
	<span style="color: #0000FF;">select</span> SalesOrderID, RevisionNumber, OrderDate, DueDate, ShipDate, <span style="color: #808080;">&#91;</span>Status<span style="color: #808080;">&#93;</span>, OnlineOrderFlag, PurchaseOrderNumber, AccountNumber, CustomerID, SalesPersonID, TerritoryID, BillToAddressID, ShipToAddressID, ShipMethodID, CreditCardID, CreditCardApprovalCode, CurrencyRateID, SubTotal, TaxAmt, Freight, Comment, rowguid, ModifiedDate
	<span style="color: #0000FF;">from</span> inserted
&nbsp;
	<span style="color: #0000FF;">set</span> <span style="color: #0000FF;">identity_insert</span> Sales.<span style="color: #202020;">SalesOrderHeader_new</span> <span style="color: #0000FF;">off</span>;
go
&nbsp;
<span style="color: #0000FF;">create</span> <span style="color: #0000FF;">trigger</span> t_u_SalesOrderHeader
<span style="color: #0000FF;">on</span> Sales.<span style="color: #202020;">SalesOrderHeader</span>
<span style="color: #0000FF;">after</span> <span style="color: #0000FF;">update</span>
<span style="color: #0000FF;">as</span>
	<span style="color: #008080;">-- assuming pk values are never altered.</span>
	<span style="color: #0000FF;">update</span> Sales.<span style="color: #202020;">SalesOrderHeader_new</span>
	<span style="color: #0000FF;">set</span>
		RevisionNumber <span style="color: #808080;">=</span> i.<span style="color: #202020;">RevisionNumber</span>,
		OrderDate  <span style="color: #808080;">=</span> i.<span style="color: #202020;">OrderDate</span>,
		DueDate  <span style="color: #808080;">=</span> i.<span style="color: #202020;">DueDate</span>,
		ShipDate  <span style="color: #808080;">=</span> i.<span style="color: #202020;">ShipDate</span>,
		<span style="color: #808080;">&#91;</span>Status<span style="color: #808080;">&#93;</span>  <span style="color: #808080;">=</span> i.<span style="color: #808080;">&#91;</span>Status<span style="color: #808080;">&#93;</span>,
		OnlineOrderFlag  <span style="color: #808080;">=</span> i.<span style="color: #202020;">OnlineOrderFlag</span>,
		PurchaseOrderNumber  <span style="color: #808080;">=</span> i.<span style="color: #202020;">PurchaseOrderNumber</span>,
		AccountNumber  <span style="color: #808080;">=</span> i.<span style="color: #202020;">AccountNumber</span>,
		CustomerID  <span style="color: #808080;">=</span> i.<span style="color: #202020;">CustomerID</span>,
		SalesPersonID  <span style="color: #808080;">=</span> i.<span style="color: #202020;">SalesPersonID</span>,
		TerritoryID  <span style="color: #808080;">=</span> i.<span style="color: #202020;">TerritoryID</span>,
		BillToAddressID  <span style="color: #808080;">=</span> i.<span style="color: #202020;">BillToAddressID</span>,
		ShipToAddressID  <span style="color: #808080;">=</span> i.<span style="color: #202020;">ShipToAddressID</span>,
		ShipMethodID  <span style="color: #808080;">=</span> i.<span style="color: #202020;">ShipMethodID</span>,
		CreditCardID  <span style="color: #808080;">=</span> i.<span style="color: #202020;">CreditCardID</span>,
		CreditCardApprovalCode <span style="color: #808080;">=</span> i.<span style="color: #202020;">CreditCardApprovalCode</span>,
		CurrencyRateID  <span style="color: #808080;">=</span> i.<span style="color: #202020;">CurrencyRateID</span>,
		SubTotal  <span style="color: #808080;">=</span> i.<span style="color: #202020;">SubTotal</span>,
		TaxAmt  <span style="color: #808080;">=</span> i.<span style="color: #202020;">TaxAmt</span>,
		Freight  <span style="color: #808080;">=</span> i.<span style="color: #202020;">Freight</span>,
		Comment  <span style="color: #808080;">=</span> i.<span style="color: #202020;">Comment</span>,
		rowguid  <span style="color: #808080;">=</span> i.<span style="color: #202020;">rowguid</span>,
		ModifiedDate <span style="color: #808080;">=</span> i.<span style="color: #202020;">ModifiedDate</span>
	<span style="color: #0000FF;">from</span> Sales.<span style="color: #202020;">SalesOrderHeader_new</span> s
	join inserted i
		<span style="color: #0000FF;">on</span> s.<span style="color: #202020;">SalesOrderID</span> <span style="color: #808080;">=</span> i.<span style="color: #202020;">SalesOrderID</span>;
go
&nbsp;
<span style="color: #0000FF;">create</span> <span style="color: #0000FF;">trigger</span> t_d_SalesOrderHeader
<span style="color: #0000FF;">on</span> Sales.<span style="color: #202020;">SalesOrderHeader</span>
<span style="color: #0000FF;">after</span> <span style="color: #0000FF;">delete</span>
<span style="color: #0000FF;">as</span>
	<span style="color: #0000FF;">delete</span> Sales.<span style="color: #202020;">SalesOrderHeader_new</span>
	<span style="color: #0000FF;">from</span> Sales.<span style="color: #202020;">SalesOrderHeader_new</span> s
	join deleted d
		<span style="color: #0000FF;">on</span> d.<span style="color: #202020;">SalesOrderID</span> <span style="color: #808080;">=</span> s.<span style="color: #202020;">SalesOrderID</span> ;
go</pre></div></div>

<h3>Move the data over in batches</h3>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">/* 
populate new table in batches
*/</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> <span style="color: #0000FF;">transaction</span> <span style="color: #0000FF;">isolation</span> <span style="color: #0000FF;">level</span> serializable;
&nbsp;
<span style="color: #0000FF;">declare</span> @i <span style="color: #0000FF;">int</span> <span style="color: #808080;">=</span> <span style="color: #000;">0</span>;
<span style="color: #0000FF;">declare</span> @new_i <span style="color: #0000FF;">int</span> <span style="color: #808080;">=</span> <span style="color: #000;">0</span>;
<span style="color: #0000FF;">declare</span> @rowcount <span style="color: #0000FF;">int</span> <span style="color: #808080;">=</span> <span style="color: #808080;">-</span><span style="color: #000;">1</span>;
<span style="color: #0000FF;">declare</span> @minBatchSize <span style="color: #0000FF;">int</span> <span style="color: #808080;">=</span> <span style="color: #000;">5000</span>
&nbsp;
<span style="color: #0000FF;">set</span> <span style="color: #0000FF;">identity_insert</span> Sales.<span style="color: #202020;">SalesOrderHeader_new</span> <span style="color: #0000FF;">on</span>;
&nbsp;
<span style="color: #0000FF;">while</span> @rowcount <span style="color: #808080;">&lt;&gt;</span> <span style="color: #000;">0</span>
<span style="color: #0000FF;">begin</span>
	<span style="color: #0000FF;">select</span> <span style="color: #0000FF;">top</span> <span style="color: #808080;">&#40;</span>@minBatchSize<span style="color: #808080;">&#41;</span> @new_i <span style="color: #808080;">=</span> SalesOrderID
	<span style="color: #0000FF;">from</span> Sales.<span style="color: #202020;">SalesOrderHeader</span>
	<span style="color: #0000FF;">where</span> SalesOrderID <span style="color: #808080;">&gt;</span> @i
	<span style="color: #0000FF;">order</span> <span style="color: #0000FF;">by</span> SalesOrderID <span style="color: #0000FF;">asc</span>;
&nbsp;
	merge Sales.<span style="color: #202020;">SalesOrderHeader_new</span> <span style="color: #0000FF;">as</span> target
	<span style="color: #0000FF;">using</span> <span style="color: #808080;">&#40;</span>
			<span style="color: #0000FF;">select</span> SalesOrderID, RevisionNumber, OrderDate, DueDate, ShipDate, <span style="color: #808080;">&#91;</span>Status<span style="color: #808080;">&#93;</span>, OnlineOrderFlag, PurchaseOrderNumber, AccountNumber, CustomerID, SalesPersonID, TerritoryID, BillToAddressID, ShipToAddressID, ShipMethodID, CreditCardID, CreditCardApprovalCode, CurrencyRateID, SubTotal, TaxAmt, Freight, Comment, rowguid, ModifiedDate
			<span style="color: #0000FF;">from</span> Sales.<span style="color: #202020;">SalesOrderHeader</span>
			<span style="color: #0000FF;">where</span> SalesOrderID <span style="color: #808080;">&gt;</span> @i
			and SalesOrderID <span style="color: #808080;">&lt;=</span> @new_i
		<span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">as</span> source <span style="color: #808080;">&#40;</span>SalesOrderID, RevisionNumber, OrderDate, DueDate, ShipDate, <span style="color: #808080;">&#91;</span>Status<span style="color: #808080;">&#93;</span>, OnlineOrderFlag, PurchaseOrderNumber, AccountNumber, CustomerID, SalesPersonID, TerritoryID, BillToAddressID, ShipToAddressID, ShipMethodID, CreditCardID, CreditCardApprovalCode, CurrencyRateID, SubTotal, TaxAmt, Freight, Comment, rowguid, ModifiedDate<span style="color: #808080;">&#41;</span>
	<span style="color: #0000FF;">on</span> target.<span style="color: #202020;">SalesOrderID</span> <span style="color: #808080;">=</span> source.<span style="color: #202020;">SalesOrderID</span>
	<span style="color: #0000FF;">when</span> not matched <span style="color: #0000FF;">then</span>
		<span style="color: #0000FF;">insert</span> <span style="color: #808080;">&#40;</span>SalesOrderID, RevisionNumber, OrderDate, DueDate, ShipDate, <span style="color: #808080;">&#91;</span>Status<span style="color: #808080;">&#93;</span>, OnlineOrderFlag, PurchaseOrderNumber, AccountNumber, CustomerID, SalesPersonID, TerritoryID, BillToAddressID, ShipToAddressID, ShipMethodID, CreditCardID, CreditCardApprovalCode, CurrencyRateID, SubTotal, TaxAmt, Freight, Comment, rowguid, ModifiedDate<span style="color: #808080;">&#41;</span>
		<span style="color: #0000FF;">values</span> <span style="color: #808080;">&#40;</span>source.<span style="color: #202020;">SalesOrderID</span>, source.<span style="color: #202020;">RevisionNumber</span>, source.<span style="color: #202020;">OrderDate</span>, source.<span style="color: #202020;">DueDate</span>, source.<span style="color: #202020;">ShipDate</span>, source.<span style="color: #808080;">&#91;</span>Status<span style="color: #808080;">&#93;</span>, source.<span style="color: #202020;">OnlineOrderFlag</span>, source.<span style="color: #202020;">PurchaseOrderNumber</span>, source.<span style="color: #202020;">AccountNumber</span>, source.<span style="color: #202020;">CustomerID</span>, source.<span style="color: #202020;">SalesPersonID</span>, source.<span style="color: #202020;">TerritoryID</span>, source.<span style="color: #202020;">BillToAddressID</span>, source.<span style="color: #202020;">ShipToAddressID</span>, source.<span style="color: #202020;">ShipMethodID</span>, source.<span style="color: #202020;">CreditCardID</span>, source.<span style="color: #202020;">CreditCardApprovalCode</span>, source.<span style="color: #202020;">CurrencyRateID</span>, source.<span style="color: #202020;">SubTotal</span>, source.<span style="color: #202020;">TaxAmt</span>, source.<span style="color: #202020;">Freight</span>, source.<span style="color: #202020;">Comment</span>, source.<span style="color: #202020;">rowguid</span>, source.<span style="color: #202020;">ModifiedDate</span><span style="color: #808080;">&#41;</span>;
&nbsp;
	<span style="color: #0000FF;">set</span> @rowcount <span style="color: #808080;">=</span> <span style="color: #FF00FF;">@@ROWCOUNT</span>
&nbsp;
	<span style="color: #0000FF;">set</span> @i <span style="color: #808080;">=</span> @new_i
&nbsp;
<span style="color: #0000FF;">end</span>
&nbsp;
<span style="color: #0000FF;">set</span> <span style="color: #0000FF;">identity_insert</span> Sales.<span style="color: #202020;">SalesOrderHeader_new</span> <span style="color: #0000FF;">off</span>;</pre></div></div>

<h3>Do The Switch</h3>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">-- rename pks and indexes from original table</span>
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.PK_SalesOrderHeader_SalesOrderID'</span>, N<span style="color: #FF0000;">'PK_SalesOrderHeader_old_SalesOrderID'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.SalesOrderHeader.AK_SalesOrderHeader_rowguid'</span>, N<span style="color: #FF0000;">'AK_SalesOrderHeader_old_rowguid'</span>, N<span style="color: #FF0000;">'INDEX'</span>
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.SalesOrderHeader.AK_SalesOrderHeader_SalesOrderNumber'</span>, N<span style="color: #FF0000;">'AK_SalesOrderHeader_old_SalesOrderNumber'</span>, N<span style="color: #FF0000;">'INDEX'</span>
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.SalesOrderHeader.IX_SalesOrderHeader_CustomerID'</span>, N<span style="color: #FF0000;">'IX_SalesOrderHeader_old_CustomerID'</span>, N<span style="color: #FF0000;">'INDEX'</span>
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.SalesOrderHeader.IX_SalesOrderHeader_SalesPersonID'</span>, N<span style="color: #FF0000;">'IX_SalesOrderHeader_old_SalesPersonID'</span>, N<span style="color: #FF0000;">'INDEX'</span>
&nbsp;
<span style="color: #008080;">-- rename checks and defaults</span>
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.CK_SalesOrderHeader_Status'</span>, <span style="color: #FF0000;">'CK_SalesOrderHeader_old_Status'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.CK_SalesOrderHeader_DueDate'</span>, <span style="color: #FF0000;">'CK_SalesOrderHeader_old_DueDate'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.CK_SalesOrderHeader_ShipDate'</span>, <span style="color: #FF0000;">'CK_SalesOrderHeader_old_ShipDate'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.CK_SalesOrderHeader_SubTotal'</span>, <span style="color: #FF0000;">'CK_SalesOrderHeader_old_SubTotal'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.CK_SalesOrderHeader_TaxAmt'</span>, <span style="color: #FF0000;">'CK_SalesOrderHeader_old_TaxAmt'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.CK_SalesOrderHeader_Freight'</span>, <span style="color: #FF0000;">'CK_SalesOrderHeader_old_Freight'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_RevisionNumber'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_old_RevisionNumber'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_OrderDate'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_old_OrderDate'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_Status'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_old_Status'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_OnlineOrderFlag'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_old_OnlineOrderFlag'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_SubTotal'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_old_SubTotal'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_TaxAmt'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_old_TaxAmt'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_Freight'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_old_Freight'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_rowguid'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_old_rowguid'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_ModifiedDate'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_old_ModifiedDate'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
&nbsp;
<span style="color: #008080;">-- drop fks from original table</span>
<span style="color: #0000FF;">alter</span> <span style="color: #0000FF;">table</span> Sales.<span style="color: #202020;">SalesOrderHeader</span>
	<span style="color: #0000FF;">drop</span> <span style="color: #0000FF;">constraint</span>
	FK_SalesOrderHeader_Address_BillToAddressID,
	FK_SalesOrderHeader_Address_ShipToAddressID,
	FK_SalesOrderHeader_CreditCard_CreditCardID,
	FK_SalesOrderHeader_CurrencyRate_CurrencyRateID,
	FK_SalesOrderHeader_Customer_CustomerID,
	FK_SalesOrderHeader_SalesPerson_SalesPersonID,
	FK_SalesOrderHeader_ShipMethod_ShipMethodID,
	FK_SalesOrderHeader_SalesTerritory_TerritoryID
&nbsp;
<span style="color: #008080;">-- drop fks to original table</span>
<span style="color: #0000FF;">alter</span> <span style="color: #0000FF;">table</span> Sales.<span style="color: #202020;">SalesOrderDetail</span>
	<span style="color: #0000FF;">drop</span> <span style="color: #0000FF;">constraint</span> FK_SalesOrderDetail_SalesOrderHeader_SalesOrderID;
&nbsp;
<span style="color: #0000FF;">alter</span> <span style="color: #0000FF;">table</span> Sales.<span style="color: #202020;">SalesOrderHeaderSalesReason</span>
	<span style="color: #0000FF;">drop</span> <span style="color: #0000FF;">constraint</span> FK_SalesOrderHeaderSalesReason_SalesOrderHeader_SalesOrderID;
&nbsp;
<span style="color: #008080;">-- drop triggers on original table</span>
<span style="color: #0000FF;">drop</span> <span style="color: #0000FF;">trigger</span> Sales.<span style="color: #202020;">t_i_SalesOrderHeader</span>;
<span style="color: #0000FF;">drop</span> <span style="color: #0000FF;">trigger</span> Sales.<span style="color: #202020;">t_u_SalesOrderHeader</span>;
<span style="color: #0000FF;">drop</span> <span style="color: #0000FF;">trigger</span> Sales.<span style="color: #202020;">t_d_SalesOrderHeader</span>;
&nbsp;
<span style="color: #008080;">-- drop uSalesOrderHeader (but remember its definition)</span>
<span style="color: #0000FF;">declare</span> @triggersql <span style="color: #0000FF;">nvarchar</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">max</span><span style="color: #808080;">&#41;</span>;
<span style="color: #0000FF;">select</span> @triggersql <span style="color: #808080;">=</span> OBJECT_DEF<span style="color: #808080;">IN</span>ITION<span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">object_id</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">from</span> sys.<span style="color: #202020;">triggers</span> <span style="color: #0000FF;">where</span> name <span style="color: #808080;">=</span> <span style="color: #FF0000;">'uSalesOrderHeader'</span>;
<span style="color: #0000FF;">drop</span> <span style="color: #0000FF;">trigger</span> Sales.<span style="color: #202020;">uSalesOrderHeader</span>; 
&nbsp;
<span style="color: #008080;">-- rename original table to &quot;old&quot;</span>
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.SalesOrderHeader'</span>, N<span style="color: #FF0000;">'SalesOrderHeader_old'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
&nbsp;
<span style="color: #008080;">--rename the new indexes</span>
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.PK_SalesOrderHeader_new_SalesOrderID'</span>, N<span style="color: #FF0000;">'PK_SalesOrderHeader_SalesOrderID'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.SalesOrderHeader_new.AK_SalesOrderHeader_new_rowguid'</span>, N<span style="color: #FF0000;">'AK_SalesOrderHeader_rowguid'</span>, N<span style="color: #FF0000;">'INDEX'</span>
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.SalesOrderHeader_new.AK_SalesOrderHeader_new_SalesOrderNumber'</span>, N<span style="color: #FF0000;">'AK_SalesOrderHeader_SalesOrderNumber'</span>, N<span style="color: #FF0000;">'INDEX'</span>
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.SalesOrderHeader_new.IX_SalesOrderHeader_new_CustomerID'</span>, N<span style="color: #FF0000;">'IX_SalesOrderHeader_CustomerID'</span>, N<span style="color: #FF0000;">'INDEX'</span>
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.SalesOrderHeader_new.IX_SalesOrderHeader_new_SalesPersonID'</span>, N<span style="color: #FF0000;">'IX_SalesOrderHeader_SalesPersonID'</span>, N<span style="color: #FF0000;">'INDEX'</span>
&nbsp;
<span style="color: #008080;">-- rename the new checks and defaults</span>
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.CK_SalesOrderHeader_new_Status'</span>, <span style="color: #FF0000;">'CK_SalesOrderHeader_Status'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.CK_SalesOrderHeader_new_DueDate'</span>, <span style="color: #FF0000;">'CK_SalesOrderHeader_DueDate'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.CK_SalesOrderHeader_new_ShipDate'</span>, <span style="color: #FF0000;">'CK_SalesOrderHeader_ShipDate'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.CK_SalesOrderHeader_new_SubTotal'</span>, <span style="color: #FF0000;">'CK_SalesOrderHeader_SubTotal'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.CK_SalesOrderHeader_new_TaxAmt'</span>, <span style="color: #FF0000;">'CK_SalesOrderHeader_TaxAmt'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.CK_SalesOrderHeader_new_Freight'</span>, <span style="color: #FF0000;">'CK_SalesOrderHeader_Freight'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_new_RevisionNumber'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_RevisionNumber'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_new_OrderDate'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_OrderDate'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_new_Status'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_Status'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_new_OnlineOrderFlag'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_OnlineOrderFlag'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_new_SubTotal'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_SubTotal'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_new_TaxAmt'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_TaxAmt'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_new_Freight'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_Freight'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_new_rowguid'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_rowguid'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.DF_SalesOrderHeader_new_ModifiedDate'</span>, <span style="color: #FF0000;">'DF_SalesOrderHeader_ModifiedDate'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
&nbsp;
<span style="color: #008080;">-- rename &quot;new&quot; table</span>
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.SalesOrderHeader_new'</span>, N<span style="color: #FF0000;">'SalesOrderHeader'</span>, N<span style="color: #FF0000;">'OBJECT'</span>;
&nbsp;
<span style="color: #008080;">--rename fks pointing out</span>
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.FK_SalesOrderHeader_new_Address_BillToAddressID'</span>, N<span style="color: #FF0000;">'FK_SalesOrderHeader_Address_BillToAddressID'</span>, N<span style="color: #FF0000;">'OBJECT'</span>
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.FK_SalesOrderHeader_new_Address_ShipToAddressID'</span>, N<span style="color: #FF0000;">'FK_SalesOrderHeader_Address_ShipToAddressID'</span>, N<span style="color: #FF0000;">'OBJECT'</span>
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.FK_SalesOrderHeader_new_CreditCard_CreditCardID'</span>, N<span style="color: #FF0000;">'FK_SalesOrderHeader_CreditCard_CreditCardID'</span>, N<span style="color: #FF0000;">'OBJECT'</span>
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.FK_SalesOrderHeader_new_CurrencyRate_CurrencyRateID'</span>, N<span style="color: #FF0000;">'FK_SalesOrderHeader_CurrencyRate_CurrencyRateID'</span>, N<span style="color: #FF0000;">'OBJECT'</span>
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.FK_SalesOrderHeader_new_Customer_CustomerID'</span>, N<span style="color: #FF0000;">'FK_SalesOrderHeader_Customer_CustomerID'</span>, N<span style="color: #FF0000;">'OBJECT'</span>
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.FK_SalesOrderHeader_new_SalesPerson_SalesPersonID'</span>, N<span style="color: #FF0000;">'FK_SalesOrderHeader_SalesPerson_SalesPersonID'</span>, N<span style="color: #FF0000;">'OBJECT'</span>
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.FK_SalesOrderHeader_new_ShipMethod_ShipMethodID'</span>, N<span style="color: #FF0000;">'FK_SalesOrderHeader_ShipMethod_ShipMethodID'</span>, N<span style="color: #FF0000;">'OBJECT'</span>
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_rename</span> N<span style="color: #FF0000;">'Sales.FK_SalesOrderHeader_new_SalesTerritory_TerritoryID'</span>, N<span style="color: #FF0000;">'FK_SalesOrderHeader_SalesTerritory_TerritoryID'</span>, N<span style="color: #FF0000;">'OBJECT'</span>
&nbsp;
<span style="color: #008080;">-- re-add fks pointing in (without checks for now)</span>
<span style="color: #0000FF;">alter</span> <span style="color: #0000FF;">table</span> Sales.<span style="color: #202020;">SalesOrderDetail</span> <span style="color: #0000FF;">with</span> <span style="color: #0000FF;">nocheck</span> <span style="color: #0000FF;">add</span>
<span style="color: #0000FF;">constraint</span> FK_SalesOrderDetail_SalesOrderHeader_SalesOrderID <span style="color: #0000FF;">foreign</span> <span style="color: #0000FF;">key</span> <span style="color: #808080;">&#40;</span>SalesOrderId<span style="color: #808080;">&#41;</span>
	<span style="color: #0000FF;">references</span> Sales.<span style="color: #202020;">SalesOrderHeader</span><span style="color: #808080;">&#40;</span>SalesOrderId<span style="color: #808080;">&#41;</span> 
&nbsp;
<span style="color: #0000FF;">alter</span> <span style="color: #0000FF;">table</span> Sales.<span style="color: #202020;">SalesOrderHeaderSalesReason</span> <span style="color: #0000FF;">with</span> <span style="color: #0000FF;">nocheck</span> <span style="color: #0000FF;">add</span>
<span style="color: #0000FF;">constraint</span> FK_SalesOrderHeaderSalesReason_SalesOrderHeader_SalesOrderID <span style="color: #0000FF;">foreign</span> <span style="color: #0000FF;">key</span> <span style="color: #808080;">&#40;</span>SalesOrderId<span style="color: #808080;">&#41;</span>
	<span style="color: #0000FF;">references</span> Sales.<span style="color: #202020;">SalesOrderHeader</span><span style="color: #808080;">&#40;</span>SalesOrderId<span style="color: #808080;">&#41;</span>
&nbsp;
<span style="color: #008080;">-- re-add trigger</span>
<span style="color: #0000FF;">exec</span> <span style="color: #AF0000;">sp_executesql</span> @triggersql;</pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://michaeljswart.com/2012/04/modifying-tables-online-part-2-implementation-example/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://michaeljswart.com/2012/04/modifying-tables-online-part-2-implementation-example/</feedburner:origLink></item>
		<item>
		<title>Modifying Tables Online – Part 1: Migration Strategy</title>
		<link>http://feedproxy.google.com/~r/TheDatabaseWhisperer/~3/Mhc-8SRbLVs/</link>
		<comments>http://michaeljswart.com/2012/04/modifying-tables-online-part-1-migration-strategy/#comments</comments>
		<pubDate>Mon, 16 Apr 2012 16:00:08 +0000</pubDate>
		<dc:creator>Michael J. Swart</dc:creator>
				<category><![CDATA[SQLServerPedia Syndication]]></category>
		<category><![CDATA[Technical Articles]]></category>
		<category><![CDATA["sql server"]]></category>
		<category><![CDATA[online schema changes]]></category>
		<category><![CDATA[table migrations]]></category>

		<guid isPermaLink="false">http://michaeljswart.com/?p=2665</guid>
		<description><![CDATA[I want to describe a way to modify the definition of very large tables while keeping the table available for other queries.]]></description>
			<content:encoded><![CDATA[<div style="background: #e9f4d9; border: 1px solid #587E25; display: block; height: auto; max-width: 96%; margin: 4px; padding: 10px;">
<p><strong>SERIES: Modifying Tables Online</strong></p>
<p>In the next few days I want to describe a way to modify the definition of very large tables while keeping the table available for other queries. Some table changes are already <em>online</em> operations. But <em>offline</em> changes need extra work to keep the table available. I explore one way to do that in this series.</p>
<p>This article used to be a single blog post, but I broke it into four parts because it seemed too long. Read Part 1, and understand the strategy I&#8217;m using. Treat Parts 2-4 as appendixes. When you want to use this plan (or one like it), come back and use them as examples. You won&#8217;t be able to make use of the examples by cutting and pasting directly (unless you happen to be running an bike equipment store called Adventureworks), but modifications shouldn&#8217;t be too hard.</p>
<ul>
<li><strong>Part 1: Migration Strategy</strong></li>
<li><a href="http://michaeljswart.com/2012/04/modifying-tables-online-part-2-implementation-example/">Part 2: Implementation Example</a></li>
<li><a href="http://michaeljswart.com/2012/04/modifying-tables-online-part-3-example-with-error-handling/">Part 3: Same Example With Error Handling</a></li>
<li><a href="http://michaeljswart.com/2012/04/modifying-tables-online-part-4-testing/">Part 4: Testing</a></li>
<li><a href="http://michaeljswart.com/2012/04/modifying-tables-online-part-5-just-one-more-thing/">Part 5: Just One More Thing</a></li>
</ul>
</div>
<h3>Database Schema Changes</h3>
<p>Database schema changes are inevitable. Some of these changes can be performed quickly (like altering <em>ntext</em> columns to <em>nvarchar</em> columns). Changes like these don&#8217;t have to process every single row in the table and we say that these quick changes are <strong><em>online</em></strong>.<br />
Of course that means there are also such things as <strong><em>offline </em></strong>changes. These are changes that need to lock the table and process each row (like adding a persisted computed column to a table). Offline changes are sometimes okay when:</p>
<ul>
<li>You have scheduled maintenance window to do work</li>
<li>The table isn&#8217;t that large or</li>
<li>the estimated amount of downtime is tolerable</li>
</ul>
<p>But sometimes the estimated downtime is not tolerable and you want your changes to be <em>online</em>. Microsoft has improved and continue to improve SQL Server&#8217;s online features. For example:</p>
<ul>
<li>Since 2005, we&#8217;ve had online index rebuilds (and even that has <a href="http://michaeljswart.com/2012/01/rebuild-your-indexes-online-when-you-can/">improved in SQL Server 2012</a>)</li>
<li>Remus Rusanu talks about <a href="http://rusanu.com/2011/07/13/online-non-null-with-values-column-add-in-sql-server-11/">adding non-nullable columns</a> as an online operation.</li>
</ul>
<p>There are a few operations that are still not online. Here&#8217;s an example of one of them:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">ALTER</span> <span style="color: #0000FF;">TABLE</span> <span style="color: #808080;">&#91;</span>Tablename<span style="color: #808080;">&#93;</span>
<span style="color: #0000FF;">ADD</span> Rowversion <span style="color: #808080;">&#91;</span>Rowversion<span style="color: #808080;">&#93;</span> <span style="color: #808080;">NOT</span> <span style="color: #808080;">NULL</span></pre></div></div>

<p>The downtime for this table change can last seconds or minutes depending on the size of the table. If your business can&#8217;t tolerate that downtime, what options are there? I&#8217;m going to explain one strategy which helps me with these following goals:</p>
<ul>
<li>I want to add a rowversion column to a table. (But the strategy applies to many other offline changes).</li>
<li>The straightforward alter statement would lock the table for longer than we can tolerate</li>
<li>My change can place an exclusive lock on the table, but only for a short amount of time. This means that the change should work concurrently with quick transactions, but not necessarily with large bulk transactions.</li>
<li>It would be an advantage if this were a database-only solution because while I might understand the applications and processes that query my database, I don&#8217;t necessarily have as much control over when or how these queries are sent.</li>
</ul>
<p>So here&#8217;s something that might work:</p>
<h3>The Strategy</h3>
<p>The strategy is fairly straightforward:</p>
<p><strong>A)</strong> I create a staging table which will store the same data as the original table but with the new rowversion column. The staging table is empty at first:<br />
<img class="alignnone size-full wp-image-2679" title="Create a staging table" src="http://michaeljswart.com/wp-content/uploads/2012/04/Strategy1.png" alt="" width="468" height="189" /><br />
<strong></strong></p>
<p><strong>B)</strong> Then I add triggers to the original table to keep the staging table up to date. Any changes in the original table will also be applied to matching data in the staging table.<br />
<img class="alignnone size-full wp-image-2680" title="Add trggers" src="http://michaeljswart.com/wp-content/uploads/2012/04/Strategy2.png" alt="" width="468" height="189" /><br />
<strong></strong></p>
<p><strong>C)</strong> Fill the staging table a little at a time. This processing may take time, but the original table is still available to others.<br />
<img class="alignnone size-full wp-image-2681" title="Copy data into the staging table in batches" src="http://michaeljswart.com/wp-content/uploads/2012/04/Strategy3.png" alt="" width="468" height="228" /><br />
<strong></strong></p>
<p><strong>D)</strong> Finally remove triggers and rename the tables:<br />
<img class="alignnone size-full wp-image-2682" title="Switch the original table for the staging table" src="http://michaeljswart.com/wp-content/uploads/2012/04/Strategy4.png" alt="" width="468" height="191" /></p>
<h3>Some Notes</h3>
<p><strong>Dependencies </strong>I didn&#8217;t mention it yet, but we also have to worry about table dependencies. Tables can have a lot of dependencies (triggers, constraints, indexes etc&#8230;). You can create dependencies for the <em>staging table</em>, and rename them as well during the switch.</p>
<p><strong>Step D, the Switch:</strong> The last step is the tricky one. It&#8217;s the one that takes a schema modification (Sch-M) lock on the tables. A Sch-M lock on the table is incompatible with every other kind of lock. So that means that no in-flight transactions are allowed to use the table during the switch. SQL Server handles it pretty well, but if there are long running queries on this table, there will be blocking.</p>
<p><img class="alignnone size-full wp-image-2663" title="If you get this wrong, SQL Server actually crushes you with a huge boulder." src="http://michaeljswart.com/wp-content/uploads/2012/04/Indiana.png" alt="" width="500" height="300" /></p>
<h3>What&#8217;s next?</h3>
<ul>
<li>In part 2, I implement this strategy for Adventureworks&#8217; Sales.SalesOrderHeader table which seems to demonstrate every kind of table dependency SQL Server allows.</li>
<li>In part 3, I throw in error handling code to make the script more robust. So that if things go wrong, the application doesn&#8217;t notice and I don&#8217;t lose data.</li>
<li>In part 4, I explain the testing I do. It gives me more confidence that I don&#8217;t miss an update or a delete somehow.</li>
</ul>
<h3>Thanks</h3>
<p>I <a href="http://dba.stackexchange.com/questions/15350/">posted a question on dba.stackexchange.com</a> to look for some strategies. The answer I got there (thanks Brent!) is slightly different than the solution I&#8217;m describing here. Brent described a solution which used a view that UNION&#8217;s the staging table and the original table. It uses less space than the solution I describe, but it&#8217;s got some extra gotchas.</p>
<p>Some of this work was done in the course of my regular job. So thanks to Desire2Learn for letting me share some of the lessons I learned there. By the way, <a href="http://desire2learn.com/careers/">we&#8217;re hiring</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://michaeljswart.com/2012/04/modifying-tables-online-part-1-migration-strategy/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://michaeljswart.com/2012/04/modifying-tables-online-part-1-migration-strategy/</feedburner:origLink></item>
		<item>
		<title>Portrait Contest (results)</title>
		<link>http://feedproxy.google.com/~r/TheDatabaseWhisperer/~3/L0g7Jau7iLE/</link>
		<comments>http://michaeljswart.com/2012/04/portrait-contest-results/#comments</comments>
		<pubDate>Wed, 11 Apr 2012 03:08:58 +0000</pubDate>
		<dc:creator>Michael J. Swart</dc:creator>
				<category><![CDATA[Miscelleaneous SQL]]></category>

		<guid isPermaLink="false">http://michaeljswart.com/?p=2658</guid>
		<description><![CDATA[A couple weeks ago, I challenged you to identify two people based on my sketches of them.]]></description>
			<content:encoded><![CDATA[<p>A couple weeks ago, I challenged you to <a href="http://michaeljswart.com/2012/03/ill-draw-your-portrait/">identify two people</a> based on my sketches of them. Luckily, I didn&#8217;t do so bad and the illustrations were easy to identify. (Unlike <a href="http://michaeljswart.com/2012/03/sending-query-results-to-others/">last week&#8217;s rush job</a> on Tom Cruise and Cuba Gooding Jr.)</p>
<p>But 60 percent of you were able to correctly identify both portraits. The keen person might have noticed that the images were named buck.png and scott png. Here are those pictures.</p>
<h3>Buck Woody</h3>
<p><a href="http://michaeljswart.com/wp-content/uploads/2012/03/buck.png"><img class="alignnone size-medium wp-image-2592" title="Buck Woody" src="http://michaeljswart.com/wp-content/uploads/2012/03/buck-300x180.png" alt="Buck Woody" width="300" height="180" /></a></p>
<p>Buck Woody (<a href="http://blogs.msdn.com/b/buckwoody/">Blog</a> | <a href="https://twitter.com/#!/buckwoody">@buckwoody</a>) works at Microsoft and to me he&#8217;s Mr. Cloud, Mr. Azure. Everyone who entered knew who this was.</p>
<h3>Scott Stauffer</h3>
<p><a href="http://michaeljswart.com/wp-content/uploads/2012/03/Scott.png"><img class="alignnone size-medium wp-image-2593" title="Scott Stauffer" src="http://michaeljswart.com/wp-content/uploads/2012/03/Scott-300x225.png" alt="Scott Stauffer" width="300" height="225" /></a></p>
<p>Scott Stauffer (<a href="https://twitter.com/#!/sqlsocialite">@SQLSocialite</a>) For as long as I can remember, PASS + Canada = Scott. He&#8217;s a SSIS specialist and is super keen on community. He&#8217;s a super cool guy and was way too polite to point out that I drew his ears way way too big (I swear they grow bigger every time I look at this picture).</p>
<h3>The Winner</h3>
<p>So the winner is Jamie Thomson. Congratulations Jamie! He correctly identified both people from their photos. Jamie is another SSIS pro. I was actually lucky enough to meet him earlier this year.</p>
<p>I don&#8217;t know if you&#8217;ve noticed, but his blog has been on fire lately. Just lately he&#8217;s helped <a href="http://sqlblog.com/blogs/jamie_thomson/archive/2012/03/27/adventureworks2012-now-available-to-all-on-sql-azure.aspx">bring AdventureWorks to Azure</a>. So thanks for everything Jamie!</p>
<p><img class="alignnone size-full wp-image-2655" title="Jamie Thomson" src="http://michaeljswart.com/wp-content/uploads/2012/04/Jamie.png" alt="Jamie Thomson" width="500" height="300" /></p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://michaeljswart.com/2012/04/portrait-contest-results/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://michaeljswart.com/2012/04/portrait-contest-results/</feedburner:origLink></item>
		<item>
		<title>Sending Query Results to Others</title>
		<link>http://feedproxy.google.com/~r/TheDatabaseWhisperer/~3/Jm7gJq15g3o/</link>
		<comments>http://michaeljswart.com/2012/03/sending-query-results-to-others/#comments</comments>
		<pubDate>Wed, 28 Mar 2012 16:00:17 +0000</pubDate>
		<dc:creator>Michael J. Swart</dc:creator>
				<category><![CDATA[Miscelleaneous SQL]]></category>
		<category><![CDATA[SQLServerPedia Syndication]]></category>
		<category><![CDATA[Technical Articles]]></category>

		<guid isPermaLink="false">http://michaeljswart.com/?p=2585</guid>
		<description><![CDATA[I think most of you have all been here before. You want to know the results of a query, but you have to do it through email or some other proxy:]]></description>
			<content:encoded><![CDATA[<p>I think most of you have all been here before. You want to know the results of a query, but you have to get it from a colleague through email or some other proxy:</p>
<p><img class="alignnone size-full wp-image-2620" title="The human head weighs eight pounds" src="http://michaeljswart.com/wp-content/uploads/2012/03/JerryM1.png" alt="Jerry Maguire is asked to &quot;Show Me The Data&quot;" width="500" height="300" /></p>
<p>So how do you usually do it? How do you ask someone to send you the results of a query? There&#8217;s a million ways to answer that question and I&#8217;ve discovered that none of them are perfect. Depending on the situation, different ways are better than others. <strong>So let&#8217;s pick a situation and explore the best way to ask for those query results.</strong></p>
<h3>The Situation</h3>
<p>The facts were these&#8230;</p>
<ul>
<li><strong>Goal:</strong> I want the results of the following query. It retrieves the top 20 cached queries and plans based on total consumed cpu.</li>
<li>I have to rely on my friend to run the query for me.</li>
<li>My friend is not a database administrator but is comfortable around SQL Server Management Studio</li>
<li>I want to minimize or simplify instructions.</li>
<li>I don&#8217;t want any truncated results.</li>
<li>I want to assure my friend that these queries are safe.</li>
<li>For this situation, I&#8217;m not worried how my friend gets the data to me (email, ftp, etc&#8230;). I only care that my friend is able to persist the data to some file.</li>
</ul>
<p>And to complete the situation, here&#8217;s that query I&#8217;m curious about&#8230;</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #008080;">-- TOP 20 queries (by CPU)</span>
<span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">TOP</span> <span style="color: #808080;">&#40;</span><span style="color: #000;">20</span><span style="color: #808080;">&#41;</span>
    <span style="color: #808080;">&#91;</span>TotalCPU<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> total_worker_time,
    <span style="color: #808080;">&#91;</span>TotalElapsedTime<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> total_elapsed_time,
    <span style="color: #808080;">&#91;</span>ExecutionCount<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> execution_count,
    <span style="color: #808080;">&#91;</span>AverageCPUInMicroseconds<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> <span style="color: #0000FF;">cast</span><span style="color: #808080;">&#40;</span>total_worker_time <span style="color: #808080;">/</span> <span style="color: #808080;">&#40;</span>execution_count <span style="color: #808080;">+</span> <span style="color: #000;">0.0</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">as</span> <span style="color: #0000FF;">money</span><span style="color: #808080;">&#41;</span>,
    <span style="color: #808080;">&#91;</span>DBName<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> <span style="color: #FF00FF;">DB_NAME</span><span style="color: #808080;">&#40;</span>ST.<span style="color: #202020;">dbid</span><span style="color: #808080;">&#41;</span>,
    <span style="color: #808080;">&#91;</span>ObjectName<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> <span style="color: #FF00FF;">OBJECT_NAME</span><span style="color: #808080;">&#40;</span>ST.<span style="color: #202020;">objectid</span>, ST.<span style="color: #202020;">dbid</span><span style="color: #808080;">&#41;</span>,
    <span style="color: #808080;">&#91;</span>QueryText<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">&#91;</span>processing<span style="color: #808080;">-</span>instruction<span style="color: #808080;">&#40;</span>q<span style="color: #808080;">&#41;</span><span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> <span style="color: #0000FF;">CASE</span>
            <span style="color: #0000FF;">WHEN</span> <span style="color: #808080;">&#91;</span>sql_handle<span style="color: #808080;">&#93;</span> <span style="color: #0000FF;">IS</span> <span style="color: #808080;">NULL</span> <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">' '</span>
            <span style="color: #0000FF;">ELSE</span> <span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">SUBSTRING</span><span style="color: #808080;">&#40;</span>ST.<span style="color: #0000FF;">TEXT</span>,<span style="color: #808080;">&#40;</span>QS.<span style="color: #202020;">statement_start_offset</span> <span style="color: #808080;">+</span> <span style="color: #000;">2</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">/</span> <span style="color: #000;">2</span>,
                <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">CASE</span>
                        <span style="color: #0000FF;">WHEN</span> QS.<span style="color: #202020;">statement_end_offset</span> <span style="color: #808080;">=</span> <span style="color: #808080;">-</span><span style="color: #000;">1</span> <span style="color: #0000FF;">THEN</span> <span style="color: #FF00FF;">LEN</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">CONVERT</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">MAX</span><span style="color: #808080;">&#41;</span>,ST.<span style="color: #0000FF;">text</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">*</span> <span style="color: #000;">2</span>
                        <span style="color: #0000FF;">ELSE</span> QS.<span style="color: #202020;">statement_end_offset</span>
                        <span style="color: #0000FF;">END</span> <span style="color: #808080;">-</span> QS.<span style="color: #202020;">statement_start_offset</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">/</span> <span style="color: #000;">2</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>
            <span style="color: #0000FF;">END</span>
			<span style="color: #0000FF;">FOR</span> XML <span style="color: #0000FF;">PATH</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>, type<span style="color: #808080;">&#41;</span>,
    <span style="color: #808080;">&#91;</span>QueryPlan<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> qp.<span style="color: #202020;">query_plan</span>
<span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">dm_exec_query_stats</span> QS
<span style="color: #808080;">CROSS</span> APPLY sys.<span style="color: #202020;">dm_exec_sql_text</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#91;</span>sql_handle<span style="color: #808080;">&#93;</span><span style="color: #808080;">&#41;</span> ST
<span style="color: #808080;">CROSS</span> APPLY sys.<span style="color: #202020;">dm_exec_query_plan</span> <span style="color: #808080;">&#40;</span><span style="color: #808080;">&#91;</span>plan_handle<span style="color: #808080;">&#93;</span><span style="color: #808080;">&#41;</span> QP
<span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> total_worker_time <span style="color: #0000FF;">DESC</span></pre></div></div>

<p>Notice that the results of this query contains xml, and that xml might contain commas, spaces, tabs, newlines and all the typical delimiters. That makes my job trickier. So now I&#8217;m going to list a number of methods and their pros and cons. I can think of a number of methods off the top of my head.</p>
<ul>
<li>Method 1: <a href="#method1">Cut and paste into Excel</a></li>
<li>Method 2: <a href="#method2">Store results as tables in a temporary DB and back it up</a></li>
<li>Method 3: <a href="#method3">Using the export data wizard</a></li>
<li>Method 4: <a href="#method4">Use Management Studio&#8217;s results-to-file</a></li>
<li>Method 5: <a href="#method5">Use BCP along with SQLCMD mode</a></li>
<li>Method 6: <a href="#method6">Output the whole thing using FOR XML PATH</a> (Spoiler alert, I like this one best!)</li>
</ul>
<p><a name="method1"></a></p>
<h3>Method 1: Cut and Paste into Excel</h3>
<p>This is most people&#8217;s usual method and it works in 90% of all cases because Excel is so versatile. However in this particular case, the whitespace in the query plans and the sql text mess up some of the rows and formatting, one field in each row. I get something like this, ugh:</p>
<p><a href="http://michaeljswart.com/wp-content/uploads/2012/03/Method1.png"><img class="alignnone size-medium wp-image-2613" title="A jumbled Excel spreadsheet " src="http://michaeljswart.com/wp-content/uploads/2012/03/Method1-300x267.png" alt="A jumbled Excel spreadsheet" width="300" height="267" /></a></p>
<p>But there&#8217;s a better way using Excel. It&#8217;s not too hard to use the Data Connection Wizard. So it&#8217;s not too much work to guide my friend through it either. If I can, then this is a really useful nice way to pass around data. That wizard is accessed like this:</p>
<p><a href="http://michaeljswart.com/wp-content/uploads/2012/03/Method1-2.png"><img class="alignnone size-medium wp-image-2615" title="Using Excel to query the data" src="http://michaeljswart.com/wp-content/uploads/2012/03/Method1-2-300x127.png" alt="Using Excel to query the data" width="300" height="127" /></a><br />
<a name="method2"></a></p>
<h3>Method 2: Store Results As Tables in a Temporary DB and Back It Up</h3>
<p>That can be done with a single T-SQL script which my friend should be able to run no problem. The script looks 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;">database</span> myresults
go
<span style="color: #008080;">-- TOP 20 queries (by CPU)</span>
<span style="color: #0000FF;">SELECT</span> <span style="color: #0000FF;">TOP</span> <span style="color: #808080;">&#40;</span><span style="color: #000;">20</span><span style="color: #808080;">&#41;</span>
    <span style="color: #808080;">&#91;</span>TotalCPU<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> total_worker_time,
    <span style="color: #808080;">&#91;</span>TotalElapsedTime<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> total_elapsed_time,
    <span style="color: #808080;">&#91;</span>ExecutionCount<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> execution_count,
    <span style="color: #808080;">&#91;</span>AverageCPUInMicroseconds<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> <span style="color: #0000FF;">cast</span><span style="color: #808080;">&#40;</span>total_worker_time <span style="color: #808080;">/</span> <span style="color: #808080;">&#40;</span>execution_count <span style="color: #808080;">+</span> <span style="color: #000;">0.0</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">as</span> <span style="color: #0000FF;">money</span><span style="color: #808080;">&#41;</span>,
    <span style="color: #808080;">&#91;</span>DBName<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> <span style="color: #FF00FF;">DB_NAME</span><span style="color: #808080;">&#40;</span>ST.<span style="color: #202020;">dbid</span><span style="color: #808080;">&#41;</span>,
    <span style="color: #808080;">&#91;</span>ObjectName<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> <span style="color: #FF00FF;">OBJECT_NAME</span><span style="color: #808080;">&#40;</span>ST.<span style="color: #202020;">objectid</span>, ST.<span style="color: #202020;">dbid</span><span style="color: #808080;">&#41;</span>,
    <span style="color: #808080;">&#91;</span>QueryText<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">&#91;</span>processing<span style="color: #808080;">-</span>instruction<span style="color: #808080;">&#40;</span>q<span style="color: #808080;">&#41;</span><span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> <span style="color: #0000FF;">CASE</span>
            <span style="color: #0000FF;">WHEN</span> <span style="color: #808080;">&#91;</span>sql_handle<span style="color: #808080;">&#93;</span> <span style="color: #0000FF;">IS</span> <span style="color: #808080;">NULL</span> <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">' '</span>
            <span style="color: #0000FF;">ELSE</span> <span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">SUBSTRING</span><span style="color: #808080;">&#40;</span>ST.<span style="color: #0000FF;">TEXT</span>,<span style="color: #808080;">&#40;</span>QS.<span style="color: #202020;">statement_start_offset</span> <span style="color: #808080;">+</span> <span style="color: #000;">2</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">/</span> <span style="color: #000;">2</span>,
                <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">CASE</span>
                        <span style="color: #0000FF;">WHEN</span> QS.<span style="color: #202020;">statement_end_offset</span> <span style="color: #808080;">=</span> <span style="color: #808080;">-</span><span style="color: #000;">1</span> <span style="color: #0000FF;">THEN</span> <span style="color: #FF00FF;">LEN</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">CONVERT</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">MAX</span><span style="color: #808080;">&#41;</span>,ST.<span style="color: #0000FF;">text</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">*</span> <span style="color: #000;">2</span>
                        <span style="color: #0000FF;">ELSE</span> QS.<span style="color: #202020;">statement_end_offset</span>
                        <span style="color: #0000FF;">END</span> <span style="color: #808080;">-</span> QS.<span style="color: #202020;">statement_start_offset</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">/</span> <span style="color: #000;">2</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>
            <span style="color: #0000FF;">END</span>
			<span style="color: #0000FF;">FOR</span> XML <span style="color: #0000FF;">PATH</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>, type<span style="color: #808080;">&#41;</span>,
    <span style="color: #808080;">&#91;</span>QueryPlan<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> qp.<span style="color: #202020;">query_plan</span>
<span style="color: #0000FF;">INTO</span> myresults.<span style="color: #202020;">dbo</span>.<span style="color: #202020;">myresultset</span>
<span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">dm_exec_query_stats</span> QS
<span style="color: #808080;">CROSS</span> APPLY sys.<span style="color: #202020;">dm_exec_sql_text</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#91;</span>sql_handle<span style="color: #808080;">&#93;</span><span style="color: #808080;">&#41;</span> ST
<span style="color: #808080;">CROSS</span> APPLY sys.<span style="color: #202020;">dm_exec_query_plan</span> <span style="color: #808080;">&#40;</span><span style="color: #808080;">&#91;</span>plan_handle<span style="color: #808080;">&#93;</span><span style="color: #808080;">&#41;</span> QP
<span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> total_worker_time <span style="color: #0000FF;">DESC</span>
go
&nbsp;
<span style="color: #0000FF;">backup</span> <span style="color: #0000FF;">database</span> myresults <span style="color: #0000FF;">to</span> <span style="color: #0000FF;">disk</span> <span style="color: #808080;">=</span> <span style="color: #FF0000;">'C:\Users\Michael Swart\Desktop\Output.bak'</span>
go
&nbsp;
<span style="color: #0000FF;">drop</span> <span style="color: #0000FF;">database</span> myresults
go</pre></div></div>

<p>The best part of this is that the data is backed up perfectly, the data captures all the data with no truncation. Xml fields are stored as xml fields and once restored, it&#8217;s easy to access the resultset exactly as it was on the target computer.</p>
<p>The bad news is that although it should be fairly safe, it&#8217;s not as easy to assure my friend that the query above changes nothing. It does! It creates a whole database and backs it up. It then drops that database.</p>
<p>Hang on a second, if my friend can use this method, that means my friend (the non-dba) is authorized to drop databases. Yikes! What&#8217;s up with that?<a name="method3"></a></p>
<h3>Method 3: Using the Export Data Wizard</h3>
<p>It seems like SQL Server&#8217;s &#8220;Export Data&#8221; wizard was just built for this job. That can be accessed here:</p>
<p><a href="http://michaeljswart.com/wp-content/uploads/2012/03/Method3.png"><img class="alignnone size-medium wp-image-2614" title="SSMS's Export Data..." src="http://michaeljswart.com/wp-content/uploads/2012/03/Method3-300x169.png" alt="SSMS's Export Data..." width="300" height="169" /></a></p>
<p>But I don&#8217;t recommend it, not one bit. It launches a wizard which takes me through a set of choices, and no matter what I choose, it always seems to choke on the xml column.</p>
<p>It&#8217;s clear that this <em>Export Data Wizard</em> is using SQL Server Integration Services (SSIS) under the covers. How do I know it&#8217;s SSIS under the covers? Well if the clumsy data type handling weren&#8217;t a giveaway (zing!), the wizard can save the job I specified as an SSIS package.</p>
<p>The SSIS shows through too much to recommend to my friend, who has no dreams of becoming a B.I. Maestro.</p>
<p>So it seems like this method is <em>only</em> appropriate for those situations when cutting and pasting to Excel would be just as appropriate. And it&#8217;s kind of hard to write instructions simpler than <em>&#8220;Cut and paste into Excel&#8221;</em>.<a name="method4"></a></p>
<h3>Method 4: Use Management Studio&#8217;s Results-To-File</h3>
<p>Most people use the query window&#8217;s default setting, Results-To-Grid. Sometimes there&#8217;s a use for Results-To-Text (like when using sp_helptext for example). But what about Results-To-File? I can set that using the Query window&#8217;s context menu here:</p>
<p><a href="http://michaeljswart.com/wp-content/uploads/2012/03/Method4.png"><img class="alignnone size-medium wp-image-2616" title="The context menu used to access &quot;results to file&quot;" src="http://michaeljswart.com/wp-content/uploads/2012/03/Method4-300x149.png" alt="The context menu used to access &quot;results to file&quot;" width="300" height="149" /></a></p>
<p>I can also enable results to file with Ctrl+Shift+F. I had to look that up though. There&#8217;s a reason I haven&#8217;t learned that shortcut by heart. It&#8217;s because results-to-file doesn&#8217;t work very well. As far as I can tell, it&#8217;s like specifying results-to-text and then pasting that into a text file.</p>
<p>The biggest problem here is that depending on the results, the data gets truncated easily <em>and</em> the newlines and tabs in the data get mixed up with the rest of the formatting. By the way, I&#8217;m also out of luck (and for the same reason) if I use SSMS to save grid results.<br />
<a name="method5"></a></p>
<h3>Method 5: Use BCP, along with SQLCMD mode</h3>
<p>If I can instruct my friend to use a query window in <a href="http://msdn.microsoft.com/en-us/library/ms174187.aspx">SQLCMD</a> mode, then I can write a script which will get a bcp script to export data. Enable SQLCMD mode by choosing it from the Query menu in SSMS:</p>
<p><a href="http://michaeljswart.com/wp-content/uploads/2012/03/Method5.png"><img class="alignnone size-medium wp-image-2617" title="Selecting SQLCMD Mode from the Query Menu" src="http://michaeljswart.com/wp-content/uploads/2012/03/Method5-300x256.png" alt="Selecting SQLCMD Mode from the Query Menu" width="300" height="256" /></a></p>
<p>And the script I would have my friend run looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="tsql" style="font-family:monospace;"><span style="color: #808080;">!!</span>bcp <span style="color: #FF0000;">&quot;Select 'query omitted' as [BigLongQuery]&quot;</span> queryout <span style="color: #FF0000;">&quot;c:\temp\desktop\output5.dat&quot;</span> <span style="color: #808080;">-</span>SSWARTLAPTOP <span style="color: #808080;">-</span>T <span style="color: #808080;">-</span>n</pre></div></div>

<p>which I could then get back on my side using bcp or using OPENROWSET.</p>
<p>This method is okay. It&#8217;s kind of awkward (and any instructions to my friend will be equally as awkward) and it always takes some work to get the syntax just right. But BCP is kind of like Rob Lowe, he hasn&#8217;t changed in years and he&#8217;s really not that bad.<a name="method6"></a></p>
<h3>Method 6: Output the Whole Thing Using FOR XML PATH</h3>
<p>Hey! Now I&#8217;m getting somewhere! XML was built for this kind of thing. All I do is take the query, and append FOR XML PATH to it and send the query to my friend saying &#8220;Run this and paste the results into notepad.&#8221; Here&#8217;s the whole query:</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: #808080;">&#40;</span><span style="color: #000;">20</span><span style="color: #808080;">&#41;</span>
    <span style="color: #808080;">&#91;</span>TotalCPU<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> total_worker_time,
    <span style="color: #808080;">&#91;</span>TotalElapsedTime<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> total_elapsed_time,
    <span style="color: #808080;">&#91;</span>ExecutionCount<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> execution_count,
    <span style="color: #808080;">&#91;</span>AverageCPUInMicroseconds<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> <span style="color: #0000FF;">cast</span><span style="color: #808080;">&#40;</span>total_worker_time <span style="color: #808080;">/</span> <span style="color: #808080;">&#40;</span>execution_count <span style="color: #808080;">+</span> <span style="color: #000;">0.0</span><span style="color: #808080;">&#41;</span> <span style="color: #0000FF;">as</span> <span style="color: #0000FF;">money</span><span style="color: #808080;">&#41;</span>,
    <span style="color: #808080;">&#91;</span>DBName<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> <span style="color: #FF00FF;">DB_NAME</span><span style="color: #808080;">&#40;</span>ST.<span style="color: #202020;">dbid</span><span style="color: #808080;">&#41;</span>,
    <span style="color: #808080;">&#91;</span>ObjectName<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> <span style="color: #FF00FF;">OBJECT_NAME</span><span style="color: #808080;">&#40;</span>ST.<span style="color: #202020;">objectid</span>, ST.<span style="color: #202020;">dbid</span><span style="color: #808080;">&#41;</span>,
    <span style="color: #808080;">&#91;</span>QueryText<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">&#91;</span>processing<span style="color: #808080;">-</span>instruction<span style="color: #808080;">&#40;</span>q<span style="color: #808080;">&#41;</span><span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> <span style="color: #0000FF;">CASE</span>
            <span style="color: #0000FF;">WHEN</span> <span style="color: #808080;">&#91;</span>sql_handle<span style="color: #808080;">&#93;</span> <span style="color: #0000FF;">IS</span> <span style="color: #808080;">NULL</span> <span style="color: #0000FF;">THEN</span> <span style="color: #FF0000;">' '</span>
            <span style="color: #0000FF;">ELSE</span> <span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">SUBSTRING</span><span style="color: #808080;">&#40;</span>ST.<span style="color: #0000FF;">TEXT</span>,<span style="color: #808080;">&#40;</span>QS.<span style="color: #202020;">statement_start_offset</span> <span style="color: #808080;">+</span> <span style="color: #000;">2</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">/</span> <span style="color: #000;">2</span>,
                <span style="color: #808080;">&#40;</span><span style="color: #0000FF;">CASE</span>
                        <span style="color: #0000FF;">WHEN</span> QS.<span style="color: #202020;">statement_end_offset</span> <span style="color: #808080;">=</span> <span style="color: #808080;">-</span><span style="color: #000;">1</span> <span style="color: #0000FF;">THEN</span> <span style="color: #FF00FF;">LEN</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">CONVERT</span><span style="color: #808080;">&#40;</span><span style="color: #0000FF;">NVARCHAR</span><span style="color: #808080;">&#40;</span><span style="color: #FF00FF;">MAX</span><span style="color: #808080;">&#41;</span>,ST.<span style="color: #0000FF;">text</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">*</span> <span style="color: #000;">2</span>
                        <span style="color: #0000FF;">ELSE</span> QS.<span style="color: #202020;">statement_end_offset</span>
                        <span style="color: #0000FF;">END</span> <span style="color: #808080;">-</span> QS.<span style="color: #202020;">statement_start_offset</span><span style="color: #808080;">&#41;</span> <span style="color: #808080;">/</span> <span style="color: #000;">2</span><span style="color: #808080;">&#41;</span><span style="color: #808080;">&#41;</span>
            <span style="color: #0000FF;">END</span>
			<span style="color: #0000FF;">FOR</span> XML <span style="color: #0000FF;">PATH</span><span style="color: #808080;">&#40;</span><span style="color: #FF0000;">''</span><span style="color: #808080;">&#41;</span>, type<span style="color: #808080;">&#41;</span>,
    <span style="color: #808080;">&#91;</span>QueryPlan<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> qp.<span style="color: #202020;">query_plan</span>
<span style="color: #0000FF;">FROM</span> sys.<span style="color: #202020;">dm_exec_query_stats</span> QS
<span style="color: #808080;">CROSS</span> APPLY sys.<span style="color: #202020;">dm_exec_sql_text</span><span style="color: #808080;">&#40;</span><span style="color: #808080;">&#91;</span>sql_handle<span style="color: #808080;">&#93;</span><span style="color: #808080;">&#41;</span> ST
<span style="color: #808080;">CROSS</span> APPLY sys.<span style="color: #202020;">dm_exec_query_plan</span> <span style="color: #808080;">&#40;</span><span style="color: #808080;">&#91;</span>plan_handle<span style="color: #808080;">&#93;</span><span style="color: #808080;">&#41;</span> QP
<span style="color: #0000FF;">ORDER</span> <span style="color: #0000FF;">BY</span> total_worker_time <span style="color: #0000FF;">DESC</span>
<span style="color: #0000FF;">FOR</span> XML <span style="color: #0000FF;">PATH</span></pre></div></div>

<p>And the results that are sent back are immediately accessible without any processing.</p>
<p>I think this method works best for this particular situation. It hits my goals perfectly. Now if you dear reader want to use this method in your situation, there&#8217;s just some extra caveats:</p>
<ul>
<li>SSMS restricts XML data results to 2 megabytes, although that&#8217;s configurable.</li>
<li>If you query binary fields (say query plan handles for example), then you might be surprised if the results come back in base64 encoding rather than hex which is a bit of a pain.</li>
</ul>
<h3>Other methods</h3>
<p><strong>Powershell</strong> I know you powershell pros are eager to give a one line script that does everything here. So lets hear it the comments! I know that powershell treats sets of objects (rather than unix&#8217;s cshell which deals with text). So I&#8217;m curious how well it serializes objects to a file.</p>
<p><strong>SQL Server Integration Services</strong> I haven&#8217;t forgotten about SSIS either, it&#8217;s the tool that was <em>built</em> for moving data from here to there in some format (any here, any there, any format). But I just couldn&#8217;t get the instructions simple enough for this scenario.</p>
]]></content:encoded>
			<wfw:commentRss>http://michaeljswart.com/2012/03/sending-query-results-to-others/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		<feedburner:origLink>http://michaeljswart.com/2012/03/sending-query-results-to-others/</feedburner:origLink></item>
		<item>
		<title>I’ll Draw Your Portrait</title>
		<link>http://feedproxy.google.com/~r/TheDatabaseWhisperer/~3/YiyxVZo_Z0Q/</link>
		<comments>http://michaeljswart.com/2012/03/ill-draw-your-portrait/#comments</comments>
		<pubDate>Mon, 19 Mar 2012 22:19:52 +0000</pubDate>
		<dc:creator>Michael J. Swart</dc:creator>
				<category><![CDATA[Miscelleaneous SQL]]></category>
		<category><![CDATA[contest]]></category>
		<category><![CDATA[illustration]]></category>

		<guid isPermaLink="false">http://michaeljswart.com/?p=2594</guid>
		<description><![CDATA[A lot of people have mentioned that they like my cartoon illustrations. And those are great comments. I have a lot of fun drawing them!]]></description>
			<content:encoded><![CDATA[<p><strong>Update April 10, 2012: <a href="http://michaeljswart.com/2012/04/portrait-contest-results/">Results are here!</a></strong></p>
<p>Hey I&#8217;m back after taking a &#8220;me&#8221; week. And you can look forward to some real technical SQL stuff very soon. But first a contest!</p>
<p>A lot of people have mentioned that they like my cartoon illustrations. And those are great comments. I have a lot of fun drawing them! For example here are a couple of the illustrations that I&#8217;ve done for some friends:</p>
<p><strong>Friend 1:</strong><br />
<img class="alignnone size-full wp-image-2592" title="Friend 1" src="http://michaeljswart.com/wp-content/uploads/2012/03/buck.png" alt="Friend 1" width="500" height="300" /></p>
<p><strong>Friend 2:</strong><br />
<img class="alignnone size-full wp-image-2593" title="Friend 2" src="http://michaeljswart.com/wp-content/uploads/2012/03/Scott.png" alt="Friend 2" width="400" height="300" /></p>
<h3>I&#8217;ll Draw You Too</h3>
<p>So I&#8217;ll draw you for first prize in a contest! Take a look at the faces of my friends above, guess their names and fill in the form below. I&#8217;m accepting submissions until Friday, March 23 at 12:00 noon, Eastern time. I&#8217;ll select one random winner from correct responses (spelling counts!) and if you&#8217;re that winner, I&#8217;ll contact you to do a picture for you (or even a loved one).</p>
<p><em><strong>Thanks to everyone who submitted! I&#8217;ll announce the winner shortly</strong></em></p>
<p>Good luck!</p>
]]></content:encoded>
			<wfw:commentRss>http://michaeljswart.com/2012/03/ill-draw-your-portrait/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://michaeljswart.com/2012/03/ill-draw-your-portrait/</feedburner:origLink></item>
	</channel>
</rss><!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using disk: enhanced
Object Caching 519/521 objects using disk: basic

Served from: michaeljswart.com @ 2012-05-24 09:35:13 -->

