Tuesday, 3 July 2007

Archiving Using OUTPUT INTO

SQL Server 2005 has made routine archiving of data alot simpler, we no longer need dump the records into an archive table, and then use an inner join to delete the source records; thats old hat.

Microsoft has introduced the OUTPUT INTO clause, which gives you similar functionality to that of a trigger, the INSERTED and DELETED tables exist, and in the same statement you can pump the records you deleted into a pre-existing archive table; but first lets set up a demonstrative environment, using two tables to simulate the Source and Archive:


create table tblBounce (BounceID int, Email varchar)
create table tblBounceArchive (BounceID int, Email varchar)

insert tblBounce(BounceID, Email) values (1341,'nemo@cultfigures.org')
insert tblBounce(BounceID, Email) values (1341,'shrek@cultfigures.org')
insert tblBounce(BounceID, Email) values (1341,'scooby@cultfigures.org')


I have inserted some dummy records so we can see something happening; the next statement is the clever bit, yet very simple. The statement almost acts like a move command.

DELETE FROM tblBounce
OUTPUT deleted.BounceID, deleted.Email INTO tblBounceArchive


If you check the Source table you will find the records have been removed, and appended to the Archive table, for very large recordsets this statement can be batched in the normal way.