Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fire a trigger BEFORE a delete in T-SQL 2005?

How can I fire a trigger BEFORE a delete in T-SQL 2005? The FOR actually fires AFTER an event and they seems no BEFORE argument in the TRIGGER function. The INSTEAD OF is not what I want. I need to fire before I delete a record. Any ideas?

like image 328
Fet Avatar asked Feb 05 '09 14:02

Fet


People also ask

How do you write before a delete trigger?

In this syntax: First, specify the name of the trigger which you want to create after the CREATE TRIGGER keywords. Second, use BEFORE DELETE clause to specify that the trigger is invoked right before a delete event. Third, specify the name of the table that the trigger is associated with after the ON keyword.

How do I create a trigger for delete?

First, specify the name of the trigger that you want to create in the CREATE TRIGGER clause. Second, use AFTER DELETE clause to specify the time to invoke the trigger. Third, specify the name of the table, which the trigger is associated with, after the ON keyword.

What is instead of delete trigger?

INSTEAD OF DELETE TRIGGERS are used, to delete records from a view. Introduction. INSTEAD OF DELETE triggers are used to delete records from a View that is based on multiple tables. Description. An INSTEAD OF DELETE trigger gets executed in place of the DELETE event on a table or a View.

Is trigger a delete?

Deleting a table automatically deletes any triggers on the table. A trigger is enabled by default when it is created. Disabling a trigger does not drop it.


2 Answers

You can use the INSTEAD OF option, just explicitly delete the rows at the end. For example:

CREATE TRIGGER dbo.My_Table_Delete_Instead_Of_Trigger
ON dbo.My_Table
INSTEAD OF DELETE
AS
BEGIN

     -- Do some stuff here

     DELETE T
     FROM DELETED D
     INNER JOIN dbo.My_Table T ON T.PK_1 = D.PK_1 AND T.PK_2 = D.PK_2
END

This assumed a primary key made up of columns PK_1 and PK_2.

like image 191
Tom H Avatar answered Sep 19 '22 21:09

Tom H


You can't. But you can perform a rollback in an AFTER DELETE trigger.

like image 23
Mitch Wheat Avatar answered Sep 21 '22 21:09

Mitch Wheat