I need to delete a record form a database, but I don't want to lose
that record. I was told I could set a flag, so the question is how do
you do that?
There are two ways to set up a logical delete.
1. Add a field in the table called IsDeleted. This will be a bit type (SQL
Server) or a Boolean type (Access - hopefully you are not using Access).
The addition is:
ALTER TABLE Table1
ADD
IsDeleted bit default 0 NOT NULL
GO
You then have to alter your SQL so it respects this:
AND IsDeleted = 0
Except on the page where you can "undelete" an item, which would look for
deleted items only.
AND IsDeleted = 1
To delete, the command is like this:
UPDATE Table1
SET IsDeleted = 1
WHERE ID = @id
2. Create a trigger that archives the "deleted file" To do this, you create
a table exactly like the original table, but you call it _History.
CREATE TABLE Table1_History
(
-- Fields go here
)
GO
You can then set up a trigger:
CREATE TRIGGER trgTable1Delete ON Table1
FOR DELETE
AS
INSERT INTO Table1_History
(
-- Field names here
)
SELECT *
FROM deleted
This will completely remove the record, but will make a copy in a
"history" table, so it is a better option if you have already heavily
invested in queries against this table.
You can restore by reversing the delete (ie, deleting from history and
inserting into the original table).