Thursday, March 12, 2015

Triggers III

         A trigger is a special kind of stored procedure that automatically executes when an event occurs in the database server. These triggers fire when any valid event is fired, regardless of whether or not any table rows are affected.

DML triggers are frequently used for enforcing business rules and data integrity. SQL Server provides declarative referential integrity (DRI) through the ALTER TABLE and CREATE TABLE statements. However, DRI does not provide cross-database referential integrity. 

If constraints exist on the trigger table, they are checked after the INSTEAD OF trigger execution and before the AFTER trigger execution. If the constraints are violated, the INSTEAD OF trigger actions are rolled back and the AFTER trigger is not fired.

The first and last AFTER triggers to be executed on a table can be specified by using sp_settriggerorder. Only one first and one last AFTER trigger for each INSERT, UPDATE, and DELETE operation can be specified on a table. If there are other AFTER triggers on the same table, they are randomly executed.

 If a trigger is defined as an INSTEAD OF INSERT trigger for a table, and the trigger executes an INSERT statement on the same table, the INSERT statement executed by the INSTEAD OF trigger does not call the trigger again. The INSERT executed by the trigger starts the process of performing constraint actions and firing any AFTER INSERT triggers defined for the table.

UPDATE () tests for UPDATE or INSERT tries on one column. COLUMNS_UPDATED tests for UPDATE or INSERT actions that are performed on multiple columns and returns a bit pattern that indicates which columns were inserted or updated.

When a trigger fires, results are returned to the calling application, just like with stored procedures. To prevent having results returned to an application because of a trigger firing, do not include either SELECT statements that return results or statements that perform variable assignment in a trigger.  If variable assignment must occur in a trigger, use a SET NOCOUNT statement at the start of the trigger to prevent the return of any result sets.

While writing a trigger, keep an eye on the following points:

·                  If you write a single trigger for multiple events, be very careful to ensure that your trigger does not execute for unwanted events.
·                  When writing update trigger, always check if your desired column is updated by using IF UPDATE(ColumnName).
·                  Be very careful in querying INSERTED and DELETED table.
·                  Try to avoid cursor from the trigger.
·                  Ensure that your trigger is not creating any deadlock/Infinite loop on your database.




No comments:

Post a Comment