title: SQL Server 2008 Job error 1204 Lock
body: <p>I'm having some trouble with some ancient database i have to maintain. It's been around for ages (No, i did not design it, no, it's not possible to make any changes on it)</p>
  
  <p>it goes like this: There are 2 tables, "Documents" and "Versions". Documents is a pretty simple table, just a primary key, a varchar storing the document name and the user who created that document.Versions has a foreign key to the document it belongs to, an image field where the actual document is stored (mainly word documents and pdfs), the extension, and another field that keeps the version number.</p>
  
  <p>Whenever the application (an ANCIENT VB6 application) consumes a document, a new version is generated.</p>
  
  <p>Every night, a job is run on the database, in order to delete all versions except the 5 latest ones of each document. This has been working like, forever. </p>
  
  <pre><code>DELETE FROM t_ad_Versions WHERE VersionNumber &lt; dbo.MaxVersion(codDocument)-4
  </code></pre>
  
  <p>Problem is, eventhough everyday the versions table has this job running in order to discar the oldest entries, the database is reaching an alarming size (Currently 300+ GB).</p>
  
  <p>In order to reduce said size, someone eventually realized that there's no need to keep versioning pdf elements. So, i was commanded to apply a simple modification: </p>
  
  <p>the job will delete older versions of word docs, preserving the latest 5 versions. For any other kind of file, ALL versions except the latest one will be deleted. So, i changed the stored procedure the job is associated to to this:</p>
  
  <pre><code>DELETE FROM t_ad_Versions WHERE VersionNumber &lt; dbo.MaxVersion(codDocument)-4 
  AND extension  LIKE 'do%';
  
  DELETE FROM t_ad_Versions WHERE VersionNumber &lt; dbo.MaxVersion(codDocument) 
  AND extension  NOT LIKE 'do%';
  </code></pre>
  
  <p>However, after applying the change, the following day the job history notified the following error</p>
  
  <p>"The instance of the SQL Server Database Engine cannot obtain a LOCK resource at this time. Rerun your statement when there are fewer active users. Ask the database administrator to check the lock and memory configuration for this instance, or to check for long-running transactions. [SQLSTATE HY000] (Error 1204).  The step failed."</p>
  
  <p>I'm kinda lost now, any ideas?</p>