patternsqlMinor
Soft delete: Copy row data to archive table when deleting
Viewed 0 times
deletingdeletearchivesoftwhenrowdatatablecopy
Problem
How can I move data from my current table to an archive table when a delete is called on the table?
My current table and archive table needs to be in sync in their schema too.
Can someone help me?
Edit:
I am using MySql
My current table and archive table needs to be in sync in their schema too.
Can someone help me?
Edit:
I am using MySql
Solution
(This answer is assuming SQL Server)
This would result in an audit table of a copy of the deleted records. I would recommend putting a
-- create the audit table
select *
into YourTableDeleteAudit
from YourTable
where 1 = 2
go
-- create the trigger
create trigger YourTableDeletes
on YourTable
after delete
as
insert into YourTableDeleteAudit
select *
from deleted
goThis would result in an audit table of a copy of the deleted records. I would recommend putting a
datetime stamp on that (and maybe more fields for typical auditing). You could do that like this:-- create the audit table
select *
into YourTableDeleteAudit
from YourTable
where 1 = 2
go
alter table YourTableDeleteAudit
add DeleteDate datetime null
go
-- create the trigger
create trigger YourTableDeletes
on YourTable
after delete
as
insert into YourTableDeleteAudit
select *, getdate()
from deleted
goCode Snippets
-- create the audit table
select *
into YourTableDeleteAudit
from YourTable
where 1 = 2
go
-- create the trigger
create trigger YourTableDeletes
on YourTable
after delete
as
insert into YourTableDeleteAudit
select *
from deleted
go-- create the audit table
select *
into YourTableDeleteAudit
from YourTable
where 1 = 2
go
alter table YourTableDeleteAudit
add DeleteDate datetime null
go
-- create the trigger
create trigger YourTableDeletes
on YourTable
after delete
as
insert into YourTableDeleteAudit
select *, getdate()
from deleted
goContext
StackExchange Database Administrators Q#14338, answer score: 4
Revisions (0)
No revisions yet.