Software Development
Blogs and Discussion
developer.*
Books Articles Blogs Subscribe d.* Gear About Home

Using an INSTEAD OF DELETE Trigger to Prevent Row Deletions

I learned a nice trick today that works in versions of Microsoft SQL Server starting with SQL Server 2000, which introduces the INSTEAD OF triggers. In short, an INSTEAD OF trigger fires in place of the actual event, be it INSERT, UPDATE, or DELETE. That is pretty cool.

One of my clients had a table that has been mysteriously losing rows. This is a table that does not have any official applications written to delete rows from it, and rows should never be deleted from it. No one can figure out how the missing rows are being deleted. So I added an INSTEAD OF DELETE trigger that raises an error if someone tries to delete a row. It seems to work great.

As an example, I created one for the UnitMeasure table in the AdventureWorks sample database:

CREATE TRIGGER test_unit_measure_del_prevent
ON Production.UnitMeasure INSTEAD OF DELETE
AS
BEGIN
RAISERROR ('Deletions not allowed from this table (source = instead of)', 16, 1)
END

GO

I found this nice MSDN Magazine article about INSTEAD OF triggers helpful and interesting.

Dan

thanks

just exactly what i'm looking for. very, very useful info. not really easy to find it in the db docs

Source of row loss

If you open an ADO recordset on a view or select that includes the table, any deletion can result in a cascaded delete on joined tables, even if the view is "not updateable". Try it in Enterprise Manager. MS access also does this with linked tables.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

User login

About our advertising.

Atom Feed

developer.* Blogs also has an Atom feed, located at this url.

Click here for more information about Atom.

A Jolt Award Finalist
Software Creativity 2.0
Foreword by Tom DeMarco

Recent Posters

Based on most recent 60 days, sorted by # of posts and name.

Google
Web developer.*

Who's online

There are currently 1 user and 21 guests online.

Online users

Syndicate

Syndicate content
All views expressed by authors, bloggers, and commentors are their own and do not necessarily reflect the views of developer.* or its proprietors.
Click to read the Copyright Notice.

All content copyright ©2000-2005 by the individual specified authors (and where not specified, copyright by Read Media, LLC). Reprint or redistribute only with written permission from the author and/or developer.*.

www.developerdotstar.com