Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between INSTEAD OF and AFTER trigger in SQL Server?

What is the difference between INSTEAD OF and AFTER trigger in SQL Server?

INSTEAD OF trigger invoked before unique key constraint, will the AFTER trigger invoke after unique key constraint?

like image 340
Venkat Sadasivam Avatar asked Mar 23 '10 01:03

Venkat Sadasivam


People also ask

What is the difference between Instead of trigger and after trigger?

AFTER triggers are fired after an insert, update, or delete operation. INSTEAD OF triggers fire before an insert, update, or delete operation. INSTEAD OF triggers replace the original operation.

What is the use of instead of trigger in SQL Server?

An INSTEAD OF trigger is an SQL trigger that is processed “instead of” an SQL UPDATE, DELETE or INSERT statement. Unlike SQL BEFORE and AFTER triggers, an INSTEAD OF trigger can be defined only on a view, not a table.

What is the difference between before and after trigger in SQL?

A BEFORE triggered action executes before the triggering statement , that is, before the occurrence of the trigger event. An AFTER triggered action executes after the action of the triggering statement is complete. BEFORE and AFTER triggered actions execute even if the triggering statement does not process any rows.

What does instead of trigger do?

An INSTEAD OF trigger is a trigger that allows you to update data in tables via their view which cannot be modified directly through DML statements. When you issue a DML statement such as INSERT , UPDATE , or DELETE to a non-updatable view, Oracle will issue an error.


2 Answers

AFTER trigger fires after a DML operation. INSTEAD OF trigger fires instead of a DML operation.

Big difference. INSTEAD OF allows you to override functionality, or implement functionality that otherwise isn't supported. The common place I use it is to create updateable views. Sometimes a view may not be key preserved, but as the designer you may know which base table(s) you want to update so you can do it by writing specific logic to do the update behind the scenes. An alternative is just to write a stored procedure and force the developers to call those procedures instead of performing DML on a view, but DML on views is a nice abstraction, in my opinion, because developers can treat views like tables. That is how relational design is meant to be.

Regarding "after unique key constraint", the AFTER trigger will happen after the DML succeeds, so it will happen after any violations (which will force a rollback).

like image 58
codenheim Avatar answered Oct 19 '22 05:10

codenheim


After trigger executes after data modification while Instead of trigger executes prior to data modification.

like image 24
Arthi Avatar answered Oct 19 '22 04:10

Arthi