Published on

Published in: Education
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Faculty notes You need to provide each trigger with a name and define it for a particular table or view in a database. You also have an option of encrypting the trigger so that no one (not even the owner) can look at the original code. Triggers can be used to enforce referential integrity: You could create a trigger that, upon the insertion of a record looks for the corresponding value of the foreign key in the parent table. If the value isn’t found, the transaction can be rolled back. Difference between triggers and declarative constraints A declarative integrity constraint applies to the data which is existing in the table and any statement that manipulates the table. A trigger does not apply to the data which was there in the table before the trigger was created. The triggers are used to implement more complex data integrity. The Triggers except InsteadOfTriggers are Reactive. But the declarative constraints are Proactive. When the table is manipulated by using Insert, Update and Delete statements, first the table is updated and the trigger gets executed. But the declarative constraints are checked first and the table is manipulated.
  • Faculty Notes: Setting the triggering order: In SQL Server 7.0, triggers were understood to be fired in no particular order. Since SQL Server 2000, a new stored procedure has been added called sp_settriggerorder.   The purpose of sp_settriggerorder is to set for a particular operation (INSERT, UPDATE, or DELETE) for a particular table which trigger will fire first and/or which trigger will fire last.  Any and all triggers not specified as first or last will fire in no particular order.  Our stored procedure has the following syntax: EXEC sp_settriggerorder <trigger name> , <order> , ' <operation> ‘ For instance: EXEC sp_settriggerorder trig_insert_Employee, first, 'INSERT‘ or EXEC sp_settriggerorder @triggername=‘myTrigger’, @order = ‘first’ We have three choices on order: first, last, and none.  We can use none to toggle a trigger to no longer fire first or last. 
  • Faculty Notes: After you have specified which table or view is to be the beneficiary of the trigger, you need to define the trigger as an AFTER or INSTEAD OF trigger. You cannot define an AFTER trigger for a view.
  • Faculty notes Explanation of the above example : When a new employee is added to the employee table, the no_of_emp column value in the department table for a particular department to which the employee is added, will be incremented by one. For the above example to execute, run the following script. Create the following 2 tables, Employee Table: Create table employee ( emp_code char(4), emp_name varchar(15), city varchar(15), age int, phone char(14), dept_code char(4), doj datetime, salary money, email varchar(20) ) Department table: Create table department ( dept_code char(4), dept_name varchar(15), no_of_emp int ) Execute the below statement to see whether the trigger executes. insert into employee values ('E002','Raghu','Bangalore',45, '(044)-23423434','D002','10-10-2005',150000, '', 'M') Result : check to see if the no_of_emp value of the department ‘D002’ in the department table is incremented by one.
  • Faculty notes When the above query is executed, The row is inserted into the employee table and the same row is inserted into the inserted table. As there are many rows in the employee table, we can get access to the row that is just inserted based on the row in the inserted table. And this row in the inserted table is available only during the execution of the trigger.
  • Faculty notes Use the scripts that are mentioned in the previous slide before you create the trigger mentioned in the above slide. Result : When the above delete statement is executed, check to see whether the value of the no_of_emp column is decremented by 1. for the department of the Employee ‘E002’.
  • Faculty notes We have executed the following query: delete from employee where id=‘E002’ When we delete a record from employee table, the deleted record would be put in the deleted table as shown in the above figure. The deleted table stores copies of the affected rows during DELETE and UPDATE statements. During the execution of a DELETE or UPDATE statement, rows are deleted from the trigger table and moved to the deleted table. The deleted table and the trigger table have no rows in common. In the above figure, employee is acting as a trigger table.
  • Faculty notes When, the below sql Statement is executed, update employee set dept_code = 'D003' where emp_code = 'E001‘ Assuming that the department code of employee ‘E001’ is ‘D001’, when the above update statement is executed, the no_of_emp of the dept_code column for D001 and D003 departments in the department table are decremented and incremented by 1 respectively. Also, initially it checks to see whether the dept_code is getting updated using the statement update(dept_code), by doing so the trigger body gets executed only if the dept_code is updated.
  • Faculty notes Updation is deletion followed by insertion. In the above example, the record is deleted first from the Employee and put into the deleted table, then the record is updated and inserted into to the Employee Table. After inserting the updated record into the Employee table, the record is inserted into the Inserted Table.
  • Faculty notes To turn off nested triggers, use: Exec sp_configure ‘nested triggers’,0 reconfigure To turn on nested triggers, use: Exec sp_configure ‘nested triggers’,1,reconfigure
  • Faculty notes Example of Indirect recursion: An update on table A fires a trigger which causes an update on table B. The update on table B fires a trigger which does an update on table C. Table C has a trigger which causes an update on table A again. Table A’s trigger fires again. Recursive triggers create a lot of problems. As a result, recursive triggers are turned off by default. If you want to check the status of recursive triggers in a particular database, use: Exec sp_dboption ‘<name of database>’,’recursive triggers’ To turn on recursive triggers, use: Exec db_option ‘<name of database>’, ’recursive triggers’, ’true’ To turn off recursive triggers, use: Exec db_option ‘<name of database>’,’recursive triggers’, ‘false’
  • Module06

    1. 1. 6.1: Introduction to Triggers SQL Server 2005
    2. 2. Objectives <ul><li>At the end of this presentation you should be able to: </li></ul><ul><li>Understand the concept of Triggers </li></ul><ul><li>Understand various types of Triggers </li></ul><ul><li>Understand the concept of Magic tables </li></ul><ul><li>Create various types of Triggers </li></ul><ul><li>Understand the concept of Nested Triggers </li></ul><ul><li>Understand the concept of Recursive Triggers </li></ul><ul><li>Perform operations on triggers </li></ul>
    3. 3. <ul><li>Introduction to Triggers </li></ul><ul><li>Types of Triggers </li></ul><ul><li>Magic Tables </li></ul><ul><li>Creating Triggers </li></ul><ul><li>Nested Triggers </li></ul><ul><li>Recursive Triggers </li></ul><ul><li>Operations performed on triggers </li></ul>Contents
    4. 4. Introduction to Triggers <ul><li>A trigger is an object contained within an SQL server database that is used to execute a batch of SQL code whenever a specific event occurs. </li></ul><ul><li>Triggers allow us to execute a batch of code when either an insert, update or delete command is executed. </li></ul><ul><li>As the name suggests, automatically trigger is fired whenever an insert, update or delete SQL command is executed against a specific table. </li></ul>
    5. 5. Introduction to Triggers (Continued) <ul><li>Triggers are associated with a single table. </li></ul><ul><li>One of the most important use of a trigger is to enforce referential integrity. </li></ul><ul><li>You can create multiple triggers on a table per each action. </li></ul><ul><li>You can specify which trigger fires first or fires last using sp_settriggerorder stored procedure. </li></ul>
    6. 6. Types of Triggers <ul><li>Triggers are of the following types: </li></ul><ul><ul><li>After triggers: These are executed after the action of the INSERT,UPDATE, or DELETE statement is performed. These triggers are also known as “FOR” triggers or even simply “triggers”. </li></ul></ul><ul><ul><li>Instead of triggers: These fire instead of the operation that fires the trigger. </li></ul></ul>
    7. 7. Magic Tables <ul><li>The inserted and deleted tables known as Magic Tables </li></ul><ul><li>update () and columns_updated() functions can be used to determine the changes being caused by DML statements. </li></ul><ul><li>The below table explains how the Inserted and Deleted Tables are used for Insert, Update and Delete Operations </li></ul><ul><li>The update() function helps to identify the column updated. </li></ul>Will have the row before updation. Will have the updated row. Update Will have the rows deleted 0 rows Delete 0 rows. Will have the inserted row Insert Deleted Table Inserted Table Operation
    8. 8. <ul><li>A trigger can be created using the CREATE TRIGGER statement. </li></ul><ul><li>The syntax is as under: </li></ul>How To Create Triggers CREATE TRIGGER TRIGGER_NAME ON TABLE_NAME FOR { INSERT | UPDATE | DELETE [, ..]} AS SQL_STATEMENTS [ RETURN ]
    9. 9. Trigger for Insert <ul><li>The below trigger gets executed when a new employee is added to the employee table. </li></ul>create trigger trgInsertEmp on employee for insert as begin declare @dcode char(4) select @dcode = dept_code from inserted update department set no_of_emp = no_of_emp + 1 where dept_code = @dcode print 'The Department updated succesfully' end
    10. 10. Trigger for Insert (Continued…) <ul><li>Suppose we execute the following query: </li></ul><ul><li>insert into employees values ('E003',‘Mary',‘Delhi',33, '(044)-23423434','D002','10-10-2005',150000, ‘', ‘F') </li></ul>Table: inserted Table : Employee .. .. .. D002 33 Delhi Mary E003 .. DeptCode Age City EName ECode .. .. .. D002 33 Delhi Mary E003 .. .. D002 34 Bangalore Ashok E002 .. .. D001 23 Bangalore Raj E001 .. DeptCode Age City EName ECode
    11. 11. Example - Trigger for Delete <ul><li>create trigger t rgUpdateEmp </li></ul><ul><li>on E mployee </li></ul><ul><li>for delete </li></ul><ul><li>as </li></ul><ul><li>begin </li></ul><ul><li>declare @dcode char(4) </li></ul><ul><li>select @dcode = D ept C ode from deleted </li></ul><ul><li>update D epartment set no _ of_emp = no_of_emp - 1 where D ept C ode = @ dcode </li></ul><ul><li>print 'The Department updated succesfully' </li></ul><ul><li>end </li></ul>delete from employee where id= 'E002‘ -------------------------------------------------------- Output (1 row(s) affected) The Department updated succesfully
    12. 12. Trigger for Delete (Continued…) <ul><li>Suppose we execute the following query: </li></ul><ul><li>delete from employee where id= 'E002‘ </li></ul>Id Name Id Name E001 John DeptCode DeptCode D001 Table: deleted Table: Employee Record being deleted from employee table and inserted in deleted table E002 Mike D002 E002 Mike D002
    13. 13. Trigger for Update <ul><li>alter trigger trgUpdateDeptCode </li></ul><ul><li>on Employee </li></ul><ul><li>for update as </li></ul><ul><li>begin </li></ul><ul><li>if update(DeptCode) </li></ul><ul><li>begin </li></ul><ul><li>declare @olddept char(4), @newdept char(4) </li></ul><ul><li>select @olddept = DeptCode from deleted </li></ul><ul><li>select @newdept = DeptCode from inserted </li></ul><ul><li>update Department set no_of_emp = no_of_emp - 1 where DeptCode = @olddept </li></ul><ul><li>update Department set no_of_emp = no_of_emp + 1 where DeptCode = @newdept </li></ul><ul><li>print 'The Employee moved successfully' </li></ul><ul><li>end </li></ul><ul><li>end </li></ul>
    14. 14. Trigger for Update (Continued…) <ul><li>Suppose we execute the following query: </li></ul><ul><li>update employee set DeptCode = 'D003' where ECode = 'E001‘ </li></ul>Table: Employee (Before updation) Table: Employee (After updation) Table: deleted Table: inserted .. .. .. D003 Raj E001 .. DeptCode EName ECode .. .. .. D001 Raj E001 .. DeptCode EName ECode .. .. .. D001 Raj E001 .. DeptCode EName ECode .. .. .. D003 Raj E001 .. DeptCode EName ECode
    15. 15. Instead of Triggers <ul><li>Only the ‘Instead of’ trigger will get fired instead of the operation that fires the trigger. </li></ul><ul><li>Example: </li></ul>Create Trigger trgInsteadInsert On User_Details INSTEAD OF INSERT AS BEGIN Print ('INSTEAD OF Trigger [trgInsteadInsert] – Trigger executed !!') END ------------------------------------------------- INSERT INTO USER_DETAILS(USERID, FNAME,LNAME, MNAME, EMAIL) VALUES(100, 'FName','LName','MName','') INSTEAD OF Trigger [trgInsteadInsert] – Trigger executed !! (1 row(s) affected) Output
    16. 16. Nested Triggers <ul><li>Nested Triggers are triggers that fire due to action of other triggers. </li></ul><ul><li>To check whether nested triggers are allowed on your server, execute the following stored procedure: </li></ul><ul><li>exec sp_configure ‘nested triggers’ </li></ul><ul><li>If run-value is 0, your server is not allowing nested triggers. </li></ul><ul><li>If run-value is 1, your server is allowing nested triggers. </li></ul>
    17. 17. Recursive Triggers <ul><li>When a Trigger is eventually going to call itself. There are two types of recursive triggers: </li></ul><ul><ul><li>Direct Recursion: A direct recursion is the one that performs the same operation on the same table causing the trigger to fire itself again. </li></ul></ul><ul><ul><li>Indirect Recursion: An indirect recursion is the one that fires a trigger on another table and eventually the nested trigger ends up firing the first trigger again. </li></ul></ul>
    18. 18. To Get information about triggers <ul><li>In order to get information about triggers on a particular table, you can use the following stored procedure: </li></ul><ul><li>exec sp_helptrigger TABLE_NAME </li></ul><ul><li>The above command will list the names of triggers along with their types which you have created on a particular table. </li></ul>
    19. 19. Operations on Trigger <ul><li>To Alter a trigger: </li></ul><ul><li>Following statement is used to alter a trigger: </li></ul><ul><li>alter trigger trigger_name </li></ul><ul><li>on table_name </li></ul><ul><li>for { INSERT | UPDATE | DELETE [, ..]} </li></ul><ul><li>As </li></ul><ul><li>SQL_STATEMENTS </li></ul><ul><li>To Drop a trigger: </li></ul><ul><li>Following statement is used to drop a trigger: </li></ul><ul><li>drop trigger trigger_name </li></ul>
    20. 20. Operations on Trigger (continued…..) <ul><li>To View the definition of a trigger: </li></ul><ul><ul><li>Use sp_helptext stored procedure to view a trigger’s definition in the following manner: </li></ul></ul><ul><ul><li>exec sp_helptext trigger_name </li></ul></ul><ul><ul><li>Trigger’s definition comprises of the statements which we used at the time of creation of that trigger. </li></ul></ul>
    21. 21. Key points <ul><li>Triggers allow us to execute a batch of SQL code when either an insert,update or delete command is executed. </li></ul><ul><li>There are mainly two types of triggers: After and Instead of triggers. </li></ul><ul><li>The inserted and deleted tables are popularly known as Magic tables </li></ul><ul><li>You can create a trigger using CREATE TRIGGER statement. </li></ul><ul><li>Nested Triggers are triggers that fire due to action of other triggers. </li></ul>
    22. 22. Key points (Continued) <ul><li>Recursive triggers are of two types: Direct and Indirect recursion. </li></ul><ul><li>You can alter a trigger using alter trigger trigger_name statement. </li></ul><ul><li>You can drop a trigger using drop trigger trigger_name statement. </li></ul><ul><li>You can view the definition of a trigger using sp_helptext stored procedure </li></ul>
    23. 23. Activity Time (45 minutes) <ul><li>Activity: 6.1 </li></ul><ul><li>Create a trigger to update the NoOfEmployees when an Employee is added to the Employee table. </li></ul><ul><li>Activity: 6.2 </li></ul><ul><li>Create a trigger to restrict the user from deleting the department from the Department table. And print a message that the record cannot be deleted. </li></ul><ul><li>Activity: 6.3 </li></ul><ul><li>Create a trigger to restrict the user to update the salary value in the Employee table. </li></ul>
    24. 24. Questions & Comments