Link to home
Create AccountLog in
Avatar of Keef4000
Keef4000

asked on

SQL delete Query

I have a database called "test" that has a table within it called "5Cycle". We have hundreds of thousands of records that I want to archive down. I'd like to do this by year so I need to delete anything older than a certain date. The date column is "TestDate" formatted YYYY-MM-DD   00:00:00:000

How do I select and delete anything older than 1/1/2010?
ASKER CERTIFIED SOLUTION
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
>that I want to archive down
btw 'archive' implies that there would be an insert from the production table to some kind of archive table before the delete.

Assuming a different database on the same server, that would be this block first, then the delete.

INSERT INTO archive_database_name.[5Cycle]
SELECT * FROM prod_database_name
WHERE testdate < '2010-01-01'

Open in new window

Even better would be to throw the whole thing into a transaction
BEGIN TRY
   BEGIN TRAN tr
   -- archive
   INSERT INTO archive_database_name.[5Cycle]
   SELECT * FROM prod_database_name
   WHERE testdate < '2010-01-01'

   -- delete
   DELETE FROM [5cycle] WHERE testdate < '2010-01-01'
   
   -- if code execution makes it here, good to go. 
   COMMIT TRAN tr
END TRY

BEGIN CATCH 
   -- if code execution makes it here, an error occured, so kill the transaction
   ROLLBACK TRAN tr
END CATCH

Open in new window

It might be necessary to use:

WHERE testdate < '2010-01-01 59:59:59.997'

to make sure all testdate values are effected (i.e. '2010-01-01 59:40:00')

You can also use:

WHERE CONVERT(VARCHAR(10), [testdate], 101) < '2010-01-01'

but the query will be slower.


Mike
Avatar of Keef4000
Keef4000

ASKER

Thank you that is exactly what I needed. I like the move the record to an archived database better than just backing up and deleting the record. I'm going to head in that direction instead.
Thanks for the grade.  Good luck with your project.  -Jim