LearnItFirst User Forum

SQL Server 2008 DBA Training Videos
Welcome Guest Search | New Posts | Members | Log In | Register

Ghost Deletes - How to Perform Logical Deletes with Instead of Triggers Options
Scott Whigham
Posted: Monday, August 28, 2006 12:11:59 PM


Rank: Super Mod

Joined: 3/20/2006
Posts: 476
Points: 1,053
Where do you live?: Dallas, TX
Code:
/*
    Author: Scott Whigham from http://www.LearnSqlServer.com/

    Description: This script demos how to perform a logical delete/ghost delete/virtual delete with an INSTEAD OF trigger. The INSTEAD OF trigger intercepts the user's request
      to perform a deletion and, instead of deleting the row(s), it marks a "Status" bit column.
   
    Versions: SQL Server 2005, 2000
   
    Creation Date: August 28, 2006

    For more scripts like this one, visit http://forums.learnsqlserver.com/codesamples.aspx
*/
CREATE TABLE Products (
    ProductID INT NOT NULL PRIMARY KEY
    , ProductName VARCHAR(50)
    , Status BIT )
GO
CREATE TRIGGER tr_DELETE_Products
ON Products INSTEAD OF DELETE
AS
UPDATE Products
    SET Status = 0
    FROM Products P JOIN deleted D
    ON P.ProductID = D.ProductID
GO
INSERT Products VALUES (1, 'Muffler', 1)
INSERT Products VALUES (2, 'Carb', 1)
INSERT Products VALUES (3, 'Exhaust pipe', 1)
INSERT Products VALUES (4, 'Tire', 1)

SELECT * FROM Products

--============================================
DELETE FROM Products WHERE ProductID = 4

-- Did it delete? No!
SELECT * FROM Products WHERE ProductId = 4
Users browsing this topic
Guest


Forum Jump
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.