<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>PeterKellner.net &#187; SQL</title>
	<atom:link href="http://peterkellner.net/category/sql/feed/" rel="self" type="application/rss+xml" />
	<link>http://peterkellner.net</link>
	<description>Microsoft Focussed, JavaScript (ExtJS, SenchaTouch &#38; Windows 8 Metro)</description>
	<lastBuildDate>Tue, 07 Feb 2012 21:14:45 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>When Using EF CodeFirst With Visual Studio, How to Live With Cannot drop database because it is in use error.</title>
		<link>http://peterkellner.net/2012/01/15/when-using-ef-codefirst-with-visual-studio-how-to-live-with-cannot-drop-database-because-it-is-in-use-error/</link>
		<comments>http://peterkellner.net/2012/01/15/when-using-ef-codefirst-with-visual-studio-how-to-live-with-cannot-drop-database-because-it-is-in-use-error/#comments</comments>
		<pubDate>Sun, 15 Jan 2012 18:58:50 +0000</pubDate>
		<dc:creator>Peter Kellner</dc:creator>
				<category><![CDATA[CodeFirst]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Sql Server]]></category>
		<category><![CDATA[Sql Server CE]]></category>

		<guid isPermaLink="false">http://peterkellner.net/2012/01/15/when-using-ef-codefirst-with-visual-studio-how-to-live-with-cannot-drop-database-because-it-is-in-use-error/</guid>
		<description><![CDATA[   Problem   So, if you have been doing development with Visual Studio 2010, Entity Framework CodeFirst, SqlServer or SqlServerCE for any amount of time, you’ll quickly run into the problem that the database can not be reinitialized because it is open.&#160; Basically, the scenario is this.  1)&#160; Put in your [...]]]></description>
			<content:encoded><![CDATA[<h2>   <p>Problem</p> </h2>  <p>So, if you have been doing development with <a href="http://www.microsoft.com/visualstudio/en-us/products/2010-editions">Visual Studio 2010</a>, <a href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=8363">Entity Framework</a> <a href="http://msdn.microsoft.com/en-us/data/aa937723">CodeFirst</a>, <a href="http://www.microsoft.com/sqlserver/en/us/default.aspx">SqlServer</a> or <a href="http://en.wikipedia.org/wiki/SQL_Server_Compact">SqlServerCE</a> for any amount of time, you’ll quickly run into the problem that the database can not be reinitialized because it is open.&#160; Basically, the scenario is this.</p>  <p>1)&#160; Put in your <a href="http://msdn.microsoft.com/en-us/library/2027ewzw.aspx">Global.asax.cs</a> file a line that always recreates the database (naturally because you are in a development mode and as you constantly change your model and seed data).&#160; The line is something like this:&#160; Database.SetInitializer(new <a href="http://msdn.microsoft.com/en-us/library/gg679506(v=vs.103).aspx">DropCreateDatabaseAlways</a>&lt;SiteDB&gt;());</p>  <p>2)&#160; Run your application with something like Debug/Run (All is fine)</p>  <p>3)&#160; Go into the database browser (either in Visual Studio or Enterprise Manager)&#160; and look at some data.</p>  <p>4)&#160; Run your application again and you will get this error: “[SqlException (0x80131904): Cannot drop database &quot;NewYorkTimesDb&quot; because it is currently in use.]”.&#160; This is because your database browser has a connection to the database and until it is dropped, you can not drop the catalog.</p>  <p>&#160;</p>  <p><a href="http://peterkellner.net/wp/wp/wp-content/uploads/2012/01/image9.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://peterkellner.net/wp/wp/wp-content/uploads/2012/01/image_thumb7.png" width="574" height="199" /></a></p>  <p>&#160;</p>  <h2>Solutions</h2>  <p>&#160;</p>  <p>The easiest and guaranteed to work solution is just to restart your SqlServer database server (control panel, services).&#160; This is what I use to do but finally got tired of that because it takes about 20 seconds and, well, I’m very impatient.</p>  <p>The other solution <a href="http://stackoverflow.com/questions/11620/how-do-you-kill-all-current-connections-to-a-sql-server-2005-database">I found</a> in the forums (can’t find the link right now) is to execute the following script from the master database catalog:</p>  <pre class="csharpcode"><span class="kwrd">use</span> master
<span class="kwrd">ALTER</span> <span class="kwrd">DATABASE</span> NewYorkTimesDb 
   <span class="kwrd">SET</span> SINGLE_USER <span class="kwrd">WITH</span> <span class="kwrd">ROLLBACK</span> <span class="kwrd">IMMEDIATE</span> 
<span class="kwrd">ALTER</span> <span class="kwrd">DATABASE</span> NewYorkTimesDb <span class="kwrd">SET</span> MULTI_USER</pre>

<p>Basically, just switching from multi-user to single-user and back clears the connections.</p>

<p>HTH’s!<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style></p>]]></content:encoded>
			<wfw:commentRss>http://peterkellner.net/2012/01/15/when-using-ef-codefirst-with-visual-studio-how-to-live-with-cannot-drop-database-because-it-is-in-use-error/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Writing A Transact SQL (TSQL) Procedure For SQL Server 2008 To Delete Rows From Table Safely</title>
		<link>http://peterkellner.net/2010/04/29/sqlserver2008-tsql-storedproc-delete-rows-in-groups-safely/</link>
		<comments>http://peterkellner.net/2010/04/29/sqlserver2008-tsql-storedproc-delete-rows-in-groups-safely/#comments</comments>
		<pubDate>Thu, 29 Apr 2010 23:54:21 +0000</pubDate>
		<dc:creator>Peter Kellner</dc:creator>
				<category><![CDATA[SQL]]></category>
		<category><![CDATA[Sql Server]]></category>
		<category><![CDATA[Sql Server 2008]]></category>
		<category><![CDATA[TSQL]]></category>
		<category><![CDATA[Transaction]]></category>

		<guid isPermaLink="false">http://peterkellner.net/2010/04/29/sqlserver2008-tsql-storedproc-delete-rows-in-groups-safely/</guid>
		<description><![CDATA[In this post, we will show and explain a small TSQL Sql Server 2008 procedure that deletes all rows in a table that are older than some specified date.&#160; That is, say the table has 10,000,000 rows in it the accumulated over the past 2 years.&#160;   Say you want to delete all but [...]]]></description>
			<content:encoded><![CDATA[<p>In this post, we will show and explain a small <a href="http://msdn.microsoft.com/en-us/library/ms189826(SQL.90).aspx">TSQL</a> <a href="http://www.microsoft.com/sqlserver/2008/en/us/">Sql Server 2008</a> procedure that deletes all rows in a table that are older than some specified date.&#160; That is, say the table has 10,000,000 rows in it the accumulated over the past 2 years.&#160; </p>  <p>Say you want to delete all but the last 30 days of activity.&#160; If you just simply say <a href="http://msdn.microsoft.com/en-us/library/ms189835.aspx">DELETE</a> FROM table WHERE id&gt;10000, you will cause this to happen in one transaction and likely, you will get an error.&#160; That’s the best case.&#160; The worst case is your system tries to do this, eventually consumes all the resources in your computer and crashes your server.</p> <span id="more-1285"></span>  <p>&#160;</p>  <div id="codeSnippetWrapper">   <pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">CREATE</span> <span style="color: #0000ff">PROCEDURE</span> dbo.DeleteRowsInGroupsBeforeNdaysLog4NetAll<br />@NoOfRowsToDelete <span style="color: #0000ff">int</span>,<br />@DaysBeforeTodayToDelete <span style="color: #0000ff">int</span><br /><span style="color: #0000ff">AS</span><br /><span style="color: #0000ff">BEGIN</span><br /><br />  <span style="color: #0000ff">DECLARE</span> @DateToDeleteBefore <span style="color: #0000ff">date</span>    <span style="color: #008000">-- Number Of Days To Delete Records From</span><br />  <span style="color: #0000ff">DECLARE</span> @DateToday datetime         <span style="color: #008000">-- To Hold Todays Date</span><br />  <span style="color: #0000ff">DECLARE</span> @PrintMessage <span style="color: #0000ff">varchar</span>(256)  <span style="color: #008000">-- To Hold Print Message        </span><br />  <span style="color: #0000ff">DECLARE</span> @CurrentRowCount <span style="color: #0000ff">int</span>        <span style="color: #008000">-- Scratch Var For Counting Rows</span><br />  <br />  <span style="color: #0000ff">SET</span> @DateToday = GetDate()<br />  <br />  <span style="color: #0000ff">SELECT</span> @CurrentRowCount =<br />         (<br />           <span style="color: #0000ff">SELECT</span> <span style="color: #0000ff">COUNT</span>(*)<br />           <span style="color: #0000ff">FROM</span> dbo.Log4NetAll<br />           <span style="color: #0000ff">WHERE</span> <span style="color: #0000ff">Date</span> &lt;(@DateToday - @DaysBeforeTodayToDelete)<br />         ) <br />  <br />  <span style="color: #0000ff">WHILE</span> (@CurrentRowCount &gt; 0) <span style="color: #0000ff">BEGIN</span><br />      <span style="color: #0000ff">DELETE</span> <span style="color: #0000ff">TOP</span> (@NoOfRowsToDelete)<br />      <span style="color: #0000ff">FROM</span> dbo.Log4NetAll<br />        <span style="color: #0000ff">WHERE</span> Id <span style="color: #0000ff">IN</span> (<br />        <span style="color: #0000ff">SELECT</span> <span style="color: #0000ff">TOP</span> (@NoOfRowsToDelete) Id <br />        <span style="color: #0000ff">FROM</span> Log4NetAll<br />        <span style="color: #0000ff">WHERE</span> <span style="color: #0000ff">Date</span> &lt; (@DateToday - @DaysBeforeTodayToDelete)<br />        <span style="color: #0000ff">ORDER</span> <span style="color: #0000ff">BY</span> Id <span style="color: #0000ff">ASC</span>)<br />      <br />       <span style="color: #008000">-- Count the records again</span><br />       <span style="color: #0000ff">SELECT</span> @CurrentRowCount =<br />         (<br />           <span style="color: #0000ff">SELECT</span> <span style="color: #0000ff">COUNT</span>(*)<br />           <span style="color: #0000ff">FROM</span> dbo.Log4NetAll<br />           <span style="color: #0000ff">WHERE</span> <span style="color: #0000ff">Date</span> &lt;(@DateToday - @DaysBeforeTodayToDelete)<br />         ) <br />       <span style="color: #0000ff">SET</span> @PrintMessage = N<span style="color: #006080">'Deleting This Many Rows: '</span><br />                            + (<span style="color: #0000ff">CAST</span>(@CurrentRowCount <span style="color: #0000ff">AS</span> nvarchar(10)));<br />       <span style="color: #0000ff">PRINT</span> @PrintMessage;<br />  <span style="color: #0000ff">END</span>  <br />END</pre>

  <br /></div>

<div>* Inspired by a <a href="http://www.sqlservercurry.com/2008/04/how-to-delete-records-from-large-table.html">blog post by Suprotim Agarwal</a> </div>

<div>&#160;</div>

<div id="codeSnippetWrapper">Basically, what is happening in the above code is first, we are testing to see if there are any records that meet our criteria to delete.&#160; That is, records older than a certain date.&#160; Next, we have a WHILE loop that continue until there are no more records that meet the criteria.&#160; The <a href="http://msdn.microsoft.com/en-us/library/ms189835.aspx">DELETE SQL command</a> uses TOP, which is very handy because it will delete up to that many.&#160; That way, you don’t have to worry about deleting the last few records with any special case code.</div>

<div>&#160;</div>

<div>The only thing a little tricky that I did was to actually delete the records with <a href="http://msdn.microsoft.com/en-us/library/ms189575.aspx">Subquery</a> that forces a sort of the records before deleting.&#160; That is, by asking for Id IN (Records sorted ascending), I’m forcing my TOP command to delete the oldest records first.&#160; This may not be necessary if your method runs to completion, but if you interrupt it, it might be convenient for the oldest records to be deleted first.</div>

<div>
  <br /></div>

<p>Then, do Execute the Procedure, you would call it as follows assuming you wanted to delete the code in batches.</p>

<p>&#160;</p>

<div id="codeSnippetWrapper">
  <pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #0000ff">DECLARE</span> @NoOfRowsToDelete <span style="color: #0000ff">int</span>;<br /><span style="color: #0000ff">DECLARE</span> @DaysBeforeTodayToDelete <span style="color: #0000ff">int</span>;<br /><br /><span style="color: #0000ff">SET</span> @NoOfRowsToDelete = 100;<br /><span style="color: #0000ff">SET</span> @DaysBeforeTodayToDelete = 30;<br /><br /><span style="color: #0000ff">EXEC</span> [dbo].[DeleteRowsInGroupsBeforeNdaysLog4NetAll] <br />  @NoOfRowsToDelete, @DaysBeforeTodayToDelete ;</pre>

  <br /></div>

<p>The output of calling this might be:</p>

<p>Query execution was canceled by user request. 
  <br />Deleting This Many Rows: 19199 

  <br />Deleting This Many Rows: 19099 

  <br />Deleting This Many Rows: 18999 

  <br />Deleting This Many Rows: 18899 

  <br />Deleting This Many Rows: 18799 

  <br />Deleting This Many Rows: 18699 

  <br />Deleting This Many Rows: 18599… (All the way until 0)</p>

<p>&#160;</p>

<p>Hope this helps!</p>]]></content:encoded>
			<wfw:commentRss>http://peterkellner.net/2010/04/29/sqlserver2008-tsql-storedproc-delete-rows-in-groups-safely/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk
Page Caching using disk (enhanced)
Database Caching 4/11 queries in 0.142 seconds using disk

Served from: peterkellner.net @ 2012-02-08 19:56:56 -->
