<?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; Transaction</title>
	<atom:link href="http://peterkellner.net/category/transaction/feed/" rel="self" type="application/rss+xml" />
	<link>http://peterkellner.net</link>
	<description>Microsoft Focused, JavaScript,HTML5 (ExtJS, SenchaTouch &#38; Windows 8 Metro)</description>
	<lastBuildDate>Fri, 11 May 2012 16:43:17 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<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/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=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[Transaction]]></category>
		<category><![CDATA[TSQL]]></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 the last [...]]]></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>
<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@NoOfRowsToDelete <span style="color: #0000ff">int</span>,@DaysBeforeTodayToDelete <span style="color: #0000ff">int</span><span style="color: #0000ff">AS</span><span style="color: #0000ff">BEGIN</span>

  <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>  <span style="color: #0000ff">DECLARE</span> @DateToday datetime         <span style="color: #008000">-- To Hold Todays Date</span>  <span style="color: #0000ff">DECLARE</span> @PrintMessage <span style="color: #0000ff">varchar</span>(256)  <span style="color: #008000">-- To Hold Print Message        </span>  <span style="color: #0000ff">DECLARE</span> @CurrentRowCount <span style="color: #0000ff">int</span>        <span style="color: #008000">-- Scratch Var For Counting Rows</span>

  <span style="color: #0000ff">SET</span> @DateToday = GetDate()

  <span style="color: #0000ff">SELECT</span> @CurrentRowCount =         (           <span style="color: #0000ff">SELECT</span> <span style="color: #0000ff">COUNT</span>(*)           <span style="color: #0000ff">FROM</span> dbo.Log4NetAll           <span style="color: #0000ff">WHERE</span> <span style="color: #0000ff">Date</span> &lt;(@DateToday - @DaysBeforeTodayToDelete)         ) 

  <span style="color: #0000ff">WHILE</span> (@CurrentRowCount &gt; 0) <span style="color: #0000ff">BEGIN</span>      <span style="color: #0000ff">DELETE</span> <span style="color: #0000ff">TOP</span> (@NoOfRowsToDelete)      <span style="color: #0000ff">FROM</span> dbo.Log4NetAll        <span style="color: #0000ff">WHERE</span> Id <span style="color: #0000ff">IN</span> (        <span style="color: #0000ff">SELECT</span> <span style="color: #0000ff">TOP</span> (@NoOfRowsToDelete) Id         <span style="color: #0000ff">FROM</span> Log4NetAll        <span style="color: #0000ff">WHERE</span> <span style="color: #0000ff">Date</span> &lt; (@DateToday - @DaysBeforeTodayToDelete)        <span style="color: #0000ff">ORDER</span> <span style="color: #0000ff">BY</span> Id <span style="color: #0000ff">ASC</span>)

       <span style="color: #008000">-- Count the records again</span>       <span style="color: #0000ff">SELECT</span> @CurrentRowCount =         (           <span style="color: #0000ff">SELECT</span> <span style="color: #0000ff">COUNT</span>(*)           <span style="color: #0000ff">FROM</span> dbo.Log4NetAll           <span style="color: #0000ff">WHERE</span> <span style="color: #0000ff">Date</span> &lt;(@DateToday - @DaysBeforeTodayToDelete)         )        <span style="color: #0000ff">SET</span> @PrintMessage = N<span style="color: #006080">'Deleting This Many Rows: '</span>                            + (<span style="color: #0000ff">CAST</span>(@CurrentRowCount <span style="color: #0000ff">AS</span> nvarchar(10)));       <span style="color: #0000ff">PRINT</span> @PrintMessage;  <span style="color: #0000ff">END</span>  END</pre>
<p></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>
  </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>;<span style="color: #0000ff">DECLARE</span> @DaysBeforeTodayToDelete <span style="color: #0000ff">int</span>;

<span style="color: #0000ff">SET</span> @NoOfRowsToDelete = 100;<span style="color: #0000ff">SET</span> @DaysBeforeTodayToDelete = 30;

<span style="color: #0000ff">EXEC</span> [dbo].[DeleteRowsInGroupsBeforeNdaysLog4NetAll]   @NoOfRowsToDelete, @DaysBeforeTodayToDelete ;</pre>
<p></div>
<p>The output of calling this might be:</p>
<p>Query execution was canceled by user request.<br />
  <br />Deleting This Many Rows: 19199 </p>
<p>Deleting This Many Rows: 19099 </p>
<p>Deleting This Many Rows: 18999 </p>
<p>Deleting This Many Rows: 18899 </p>
<p>Deleting This Many Rows: 18799 </p>
<p>Deleting This Many Rows: 18699 </p>
<p>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: basic
Page Caching using disk: enhanced (User agent is rejected)
Database Caching 27/35 queries in 0.006 seconds using disk: basic
Content Delivery Network via Amazon Web Services: S3: PetersBlogCDN.s3.amazonaws.com

Served from: peterkellner.net @ 2012-05-23 00:38:13 -->
