title: Archiving data from table in production db to same table in secondary archive db
body: <p>Hello I was ask to archive some tables in a sql db last week, I new to SQL I see some code in other questions.  Can anyone explain the what the declare @nextid table and the UniqueID int the follow code, the code is not mine and credit is given to the owner. </p>
  
  <p>In my case  I have a primary key call attachmentID, in a table called attachments in a db call prod, the column for the date is attachmentdate.  I can not sure if I am to replace the UniqueID or what?  Please help if you can.</p>
  
  <pre><code>DECLARE @NextIDs TABLE(UniqueID int primary key)
  DECLARE @ThreeYearsAgo datetime
  SELECT @ThreeYearsAgo = DATEADD(d, -(3 * 365), GetDate())
  
  WHILE EXISTS(SELECT 1 
               FROM [ISAdminDB].[dbo].[MyTable] 
               WHERE [MyTable].[DateTime] &lt; @ThreeYearsAgo)
  BEGIN 
      BEGIN TRAN 
         INSERT INTO @NextIDs(UniqueID)
          SELECT TOP 1000 UniqueID 
            FROM [ISAdminDB].[dbo].[MyTable] 
            WHERE [MyTable].[DateTime] &lt; @ThreeYearsAgo
  
         INSERT INTO [ISArchive].[dbo].[MyTable] (&lt;Fields&gt;) 
          SELECT (&lt;Fields&gt;) 
          FROM  [ISAdminDB].[dbo].[MyTable] AS a
          INNER JOIN @NextIDs AS b ON a.UniqueID = b.UniqueID
  
         DELETE [ISAdminDB].[dbo].[MyTable]
         FROM  [ISAdminDB].[dbo].[MyTable] 
         INNER JOIN @NextIDs AS b ON a.UniqueID = b.UniqueID 
  
         DELETE FROM @NextIDs
  
         COMMIT TRAN
  END
  </code></pre>