Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

need help coming up with a simple archive script 1

Status
Not open for further replies.

bugulgad

Technical User
Dec 28, 2009
6
US
Seems simple enough, but I can't figure it out.

SQL 2005
Table A
load_date - pk
company_id - pk

Table B
business_date
month_end_flag

I simply need to write something that will copy over data that is greater than 120 days old...but not any month end data. Once copied to another table....table A can then have these rows deleted.
 
Is this what you need?
Code:
BEGIN TRANSACTION;

BEGIN TRY
     INSERT INTO TableA_History 
     SELECT * FROM TableA WHERE DATEDIFF(day, load_date, GETDATE()) >= 120

     DELETE TableA WHERE DATEDIFF(day, load_date, GETDATE()) >= 120

     INSERT INTO TableB_History
     SELECT * FROM TableB WHERE DATEDIFF(day, busindess_date, GETDATE()) >= 120 AND month_end_flag = 0

     DELETE TableB
     WHERE DATEDIFF(day, busindess_date, GETDATE()) >= 120 AND month_end_flag = 0


END TRY
BEGIN CATCH

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;
 
thanks. THat was not quite what I was looking for but you pointed me in the right direction and I have figured it out now.
 
If there is an index on the Date field, it may be better to write these queries in a sargable form (e.g. use DATEADD function instead of DATEDIFF on the right side of the comparison).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top