Your SlideShare is downloading. ×

Module06

860

Published on

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

  • Be the first to like this

No Downloads
Views
Total Views
860
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
25
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
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, 'raghu@abc.com', '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’
  • Transcript

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

    ×