Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Rather than counting the number of rows still to delete, you ought to either use <code>EXISTS</code> (so as soon as it finds a row, it returns):</p> <pre><code>WHILE EXISTS(SELECT * FROM BigTable WHERE DATEDIFF(month,dtmtimestamp, getdate()) &gt; 2) BEGIN </code></pre> <p>Or sneakier:</p> <pre><code>select top 1 * from sysobjects /* Force @@ROWCOUNT &gt; 0 */ WHILE @@ROWCOUNT BEGIN DELETE TOP 10000 FROM BigTable FROM BigTable WHERE dtmtimestamp&lt; DateAdd(month, -2,getdate()) CONTINUE END </code></pre> <p>Where the only searches of the table are ones that are used to do actual deletes.</p> <p>I've also moved around your date logic, in case the dtmtimestamp column has a useful index.</p> <p><em>Edit</em> of course, as Martin points out, neither of these address transaction log usage.</p> <p>The strategy of limiting deletes is a reasonable one to stop horrendous log usage, but needs to also have lots of log backups or truncates happening at the same time, to allow old transaction log space to be reused. Otherwise, it's still going to grow the log.</p> <p>If you know log backups are occurring, say, every fifteen minutes, you might want to pause your loop every "n" iterations, with a WAITFOR DELAY, so that you know that the previous transaction log usage has been backed up/cleared. Whatever happens, as long as you're deleting rather than truncating, a log record for each deleted row is still going to take up space in the log or a log backup.</p> <p>If you're able to take whatever is normally using this system offline, and the volume of rows which you want to keep are vastly dwarfed by the ones to delete, you might want to copy the rows to keep into another table, remove all foreign keys, truncate the table, copy the kept rows back, and rebuild the foreign keys. YMMV.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload