Lecture 4. MS SQL. DML Triggers

1,008 views

Published on

My lecture notes, composed from different open sources from Internet. If you have copyright claims just tell me to remove.

Published in: Education, Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,008
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
49
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Lecture 4. MS SQL. DML Triggers

  1. 1. Database Development in SQL ServerLecture 4Triggers
  2. 2. TriggersAn SQL Server trigger is a T/SQL procedure thatis automatically invoked when a specifieddatabase activity occurs. Usually when a datamanipulation language (DML) event takesplace that affects the table or view defined inthe trigger.DML events include INSERT, UPDATE, orDELETE statements.
  3. 3. Using of Triggers: 1Triggers can be used to:- Enforce business rules- Implement referential integrity actions- Query other tables- Audit changes- Replicate data- Include complex Transact-SQL statements
  4. 4. Using of Triggers: 2SQL Server supports INSTEAD OF and AFTER triggers:- A table may have one or more AFTER triggers- AFTER triggers may not be assigned to views- A view or table may have only one INSTEAD OF trigger foreach triggering actionThe trigger and the statement that fires it are treated as a singletransaction, which can be rolled back from within the trigger.If a severe error is detected (for example, insufficient diskspace), the entire transaction automatically rolls back.
  5. 5. Creating DML TriggersCREATE TRIGGER [ schema_name . ]trigger_nameON { table | view }[ WITH [ ENCRYPTION ]|[ EXECUTE AS Clause ] [ ,...n ] ]{ FOR | AFTER | INSTEAD OF }{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }[ NOT FOR REPLICATION ]AS { sql_statement [ ; ] [ ,...n ] | EXTERNAL NAME<method specifier [ ; ] > }<dml_trigger_option> ::=[ ENCRYPTION ][ EXECUTE AS Clause ]<method_specifier> ::=assembly_name.class_name.method_name
  6. 6. AFTER triggerAFTER triggers are executed after the action of theINSERT, UPDATE, MERGE, or DELETE statement isperformed.AFTER triggers are never executed if a constraintviolation occurs; therefore, these triggers cannot beused for any processing that might prevent constraintviolations.For every INSERT, UPDATE, or DELETE actionspecified in a MERGE statement, the correspondingtrigger is fired for each DML operation.FOR is synonym AFTER.
  7. 7. INSTEAD OF triggerINSTEAD OF triggers override the standard actions ofthe triggering statement. Therefore, they can beused to perform error or value checking on one ormore columns and the perform additional actionsbefore insert, updating or deleting the row or rows.The primary advantage of INSTEAD OF triggers is thatthey enable views that would not be updatable tosupport updates. For example, a view based onmultiple base tables must use an INSTEAD OFtrigger to support inserts, updates, and deletes thatreference data in more than one table.Another advantage of INSTEAD OF triggers is that theyenable you to code logic that can reject parts of abatch while letting other parts of a batch to succeed.
  8. 8. Retrieving data inside triggersDML triggers use the deleted and inserted logical(conceptual) tables. They are structurally similar to the tableon which the trigger is defined, that is, the table on whichthe user action is tried. The deleted and inserted tableshold the old values or new values of the rows that may bechanged by the user action.For example, to retrieve all values in the deleted table, use:SELECT * FROM deletedTables inserted and deleted cannot be modified.
  9. 9. Additional trigger optionsWITH ENCRYPTIONObfuscates the text of the CREATE TRIGGER statement. UsingWITH ENCRYPTION prevents the trigger from being published aspart of SQL Server replication. WITH ENCRYPTION cannot bespecified for CLR triggers.EXECUTE ASSpecifies the security context under which the trigger is executed.Enables you to control which user account the instance of SQLServer uses to validate permissions on any database objects thatare referenced by the trigger.NOT FOR REPLICATIONIndicates that the trigger should not be executed when a replicationagent modifies the table that is involved in the trigger.
  10. 10. ExampleCREATE TRIGGER tr_Products_U ON Products AFTER UPDATEASDECLARE @sProductName NVARCHAR(40),@mOldPrice MONEY,@mNewPrice MONEYIF UPDATE(UnitPrice)BEGINSELECT @sProductName = d.ProductName,@mOldPrice = d.UnitPrice,@mNewPrice = i.UnitPriceFROM inserted iINNER JOIN deleted d ON i.ProductID = d.ProductIDprint (Old price was + @mOldPrice + ; new price is + @mNewPrice);ENDRETURNGO
  11. 11. Nested TriggersTriggers can be nested to a maximum of 32 levels. If atrigger changes a table on which there is another trigger,the second trigger is activated and can then call a thirdtrigger, and so on. If any trigger in the chain sets off aninfinite loop, the nesting level is exceeded and the triggeris canceled.To disable nested triggers, set the nested triggers option ofsp_configure to 0 (off). The default configurationallows for nested triggers.

×