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?
Microsoft SQL Server 2005Microsoft SQL Server 2008Microsoft SQL Server

Avatar of undefined
Last Comment
Jim Horn

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Jim Horn

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Jim Horn

>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

Mike Eghtebas

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
ASKER
Keef4000

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.
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
Jim Horn

Thanks for the grade.  Good luck with your project.  -Jim