Triggers on Views
Trigger is a special kind of stored procedure that automatically executes when an event occurs in the database server.
CREATE TRIGGER <TriggerName> ON <View_Name or Table Name>
INSTEAD OF INSERT, UPDATE, DELETE
PRINT ‘TRIGGER CALLED’
E.g.2 – DDL Trigger
CREATE TRIGGER PreventDropSP
PRINT ‘Dropping Procedure is not allowed.
Triggers Dos and Don’ts
- Types are: – DML, DDL, or logon trigger in SQL Server 2012.
- Trigger can be created only in the current database, but it can refer objects outside the current database.
- DML trigger cannot be defined on local or global temporary tables
- A view can be referenced only by an INSTEAD OF trigger means we can have only Instead of Trigger on View.
- INSTEAD OF cannot be specified for DDL or logon triggers.
- At most, one INSTEAD OF trigger per INSERT, UPDATE, or DELETE statement can be defined on a table or view. However, you can define views on views where each view has its own INSTEAD OF trigger.
- INSTEAD OF triggers are not allowed on updatable views that use WITH CHECK OPTION. SQL Server raises an error when an INSTEAD OF trigger is added to an updatable view WITH CHECK OPTION specified. The user must remove that option by using ALTER VIEW before defining the INSTEAD OF trigger.
- After triggers cannot be defined on views.
- For Instead if triggers, the Delete option is not allowed on tables that have a referential relationship specifying a cascade action on DELETE.
- Instead of Delete/Update triggers cannot be defined on a table that has a foreign key with a cascade on Delete/Update action defined.
- Truncate table statement does not activate a trigger, because the operation does not log individual rows.
- Triggers can be nested to a maximum of 32 levels to disable nexted triggers set the nested triggers option to 0 (off).
Recursive triggers is also off if nested trigger is off