Advertisement
Advertisement

More Related Content

Advertisement

triggers.pptx

  1. Triggers
  2. Triggers • A trigger is a set of SQL statements that reside in system memory with unique names. It is a specialized category of stored procedure that is called automatically when a database server event occurs. Each trigger is always associated with a table. • A trigger is called a special procedure because it cannot be called directly like a stored procedure. The key distinction between the trigger and procedure is that a trigger is called automatically when a data modification event occurs against a table. A stored procedure, on the other hand, must be invoked directly. • The following are the main characteristics that distinguish triggers from stored procedures: • Triggers have no chance of receiving parameters. • A transaction cannot be committed or rolled back inside a trigger.
  3. Syntax of Triggers • Create [or replace] Trigger trigger- name • {before | after} • { insert [or] | update [or] |delete } • On table_name • [for each row] • DECLARE • Declaration statements • Begin • Executable-statements • END; • Create or replace an existing trigger with the trigger name • This specifies when the trigger will be executed • This specifies the DML operations • This specifies the name of the table associated with the trigger • This specifies the row level trigger, i.e the trigger will be executed for each row being affected. Otherwise the trigger will execute just once when the sql statement is executed, which is called a table level trigger.
  4. When we use triggers? • Triggers will be helpful when we need to execute some events automatically on certain desirable scenarios. For example, we have a constantly changing table and need to know the occurrences of changes and when these changes happen. If the primary table made any changes in such scenarios, we could create a trigger to insert the desired data into a separate table
  5. Types of SQL Server Triggers • We can categorize the triggers in SQL Server in mainly three types: • Data Definition Language (DDL) Triggers • Data Manipulation Language (DML) Triggers • Logon Triggers Following are types of trigger • Statement-level triggers • A statement-level trigger is fired whenever a trigger event occurs on a table regardless of how many rows are affected. In other words, a statement-level trigger executes once for each transaction. • Row-level Triggers • Row-level triggers fires once for each row affected by the triggering event such as INSERT, UPDATE, or DELETE.
  6. DDL Triggers • DDL triggers are fired in response to the DDL events, such as CREATE, ALTER, and DROP statements. We can create these triggers at the database level or server level, depending on the type of DDL events. It can also be executed in response to certain system-defined stored procedures that do DDL-like operations. • The DDL triggers are useful in the following scenario: • When we need to prevent the database schema from changing • When we need to audit changes made in the database schema • When we need to respond to a change made in the database schema
  7. DML Triggers • DML triggers are fired in response to DML events like INSERT, UPDATE, and DELETE statements in the user's table or view. It can also be executed in response to DML-like operations performed by system-defined stored procedures. • The DML triggers can be classified into two types: • After Triggers • Instead Of Triggers
  8. After Triggers • After trigger fires, when SQL Server completes the triggering action successfully, that fired it. Generally, this trigger is executed when a table completes an insert, update or delete operations. It is not supported in views. Sometimes it is known as FOR triggers.
  9. Instead of Triggers • Instead of Trigger fires before SQL Server begins to execute the triggering operation that triggered it. It means that no condition constraint check is needed before the trigger runs. As a result, even if the constraint check fails, this trigger will fire. It is the opposite of the AFTER trigger. We can create the INSTEAD OF triggers on a table that executes successfully but doesn't contain the table's actual insert, update, or delete operations. • We can classify this trigger further into three types: • INSTEAD OF INSERT Trigger • INSTEAD OF UPDATE Trigger • INSTEAD OF DELETE Trigger
  10. Logon Triggers • Logon triggers are fires in response to a LOGON event. The LOGON event occurs when a user session is generated with an SQL Server instance, which is made after the authentication process of logging is completed but before establishing a user session. As a result, the SQL Server error log will display all messages created by the trigger, including error messages and the PRINT statement messages. If authentication fails, logon triggers do not execute. These triggers may be used to audit and control server sessions, such as tracking login activity or limiting the number of sessions for a particular login.
  11. Advantages • The following are the advantages of using triggers in SQL Server: • Triggers set database object rules and roll back if any change does not satisfy those rules. The trigger will inspect the data and make changes if necessary. • Triggers help us to validate data before inserted or updated. • Triggers help us to keep a log of records. • Triggers increase SQL queries' performance because they do not need to compile each time they are executed. • Triggers reduce the client-side code that saves time and effort. • Triggers are easy to maintain.
  12. Disadvantages • The following are the disadvantages of using triggers in SQL Server: • Triggers only allow using extended validations. • Triggers are invoked automatically, and their execution is invisible to the user. Therefore, it isn't easy to troubleshoot what happens in the database layer. • Triggers may increase the overhead of the database server. • We can define the same trigger action for multiple user actions such as INSERT and UPDATE in the same CREATE TRIGGER statement. • We can create a trigger in the current database only, but it can reference objects outside the current database.
  13. DML before triggers • SET linesize 300; • DROP Table emp; • CREATE TABLE emp ( • Id INT PRIMARY KEY, • Name VARCHAR(15), • Salary NUMBER(8, 2), • ); • INSERT INTO emp (Id, Name, Salary) VALUES (1001, 'John', 30000); • INSERT INTO emp (Id, Name, Salary,) VALUES (1002, 'Smith', 31000); • INSERT INTO emp (Id, Name, Salary,) VALUES (1003, 'James', 42000); • INSERT INTO emp (Id, Name, Salary) VALUES (1004, 'John', 43000); • INSERT INTO emp (Id, Name, Salary,) VALUES (1005, 'Smith', 45000); • INSERT INTO emp (Id, Name, Salary,) VALUES (1006, 'James', 23000);
  14. • Create trigger salary_difference • Before insert or delete or update on emp • For each row • Declare salary_difference number; • Begin • salary_difference := :new.salary – old.salary; • dbms_output.put_line(‘Old salary: ‘ || :old.salary); • dbms_output.put_line(‘New salary: ‘ || :new.salary); • dbms_output.put_line(‘Salary difference: ‘ || : salary_difference); • end; • /
  15. • Sql> insert into emp values(1007, ’rahul’, 34000); • Sql> delete from emp where id = 1007; • Sql> update emp set salary = 35000 where id=1001;
  16. DML after triggers • SET linesize 300; • DROP Table Employee; • CREATE TABLE employee ( • Id INT PRIMARY KEY, • Name VARCHAR(15), • Salary NUMBER(8, 2), • ); • INSERT INTO employee (id, Name, Salary) VALUES (1001, 'John', 30000); • INSERT INTO employee (id, Name, Salary,) VALUES (1002, 'Smith', 31000); • INSERT INTO employee (id, Name, Salary,) VALUES (1003, 'James', 42000); • INSERT INTO employee (id, Name, Salary) VALUES (1004, 'John', 43000); • INSERT INTO employee (id, Name, Salary,) VALUES (1005, 'Smith', 45000); • INSERT INTO employee (id, Name, Salary,) VALUES (1006, 'James', 23000); • SET linesize 300; • DROP Table Employee; • CREATE TABLE employeelog ( • Id INT PRIMARY KEY, • Name VARCHAR(15), • Salary NUMBER(8, 2), • );
  17. DML after triggers • Create trigger employeelogtrigger • After insert or delete or update on employee • For each row • Begin • If inserting then • Insert into employeelog values (:new.id, ‘ insert command fired’); • elsif updating then • Insert into employeelog values (:new.id, ‘ update command fired’); • elsif deleting then • Insert into employeelog values (:new.id, ‘ delete command fired’); • End if; • end; • /
  18. • Update employee set salary = 45000 where Id=1001; • Select * from employee; • Select * from employeelog; • INSERT INTO employee (id, Name, Salary,) VALUES (1007, ‘anaya', 64000); • Select * from employee; • Select * from employeelog; • Delete from employee where id=1007; • Select * from employee; • Select * from employeelog;
  19. Instead off triggers • You can control the default behavior of DML commands on Views but not on tables. • Syntax Create [or replace] Trigger trigger-name Instead of operation { insert [or] | update [or] |delete [or] |Merge } On view_name [for each row] Begin Executable-statements END; /
  20. • SET linesize 300; • DROP Table Employee; • CREATE TABLE employee ( • Id INT, • Name VARCHAR(15), • Salary NUMBER(8, 2), • ); • INSERT INTO employee (id, Name, Salary) VALUES (1001, 'John', 30000); • INSERT INTO employee (id, Name, Salary) VALUES (1002, 'Smith', 31000); • INSERT INTO employee (id, Name, Salary) VALUES (1003, 'James', 42000); • SET linesize 300; • CREATE TABLE employeelog ( • Id INT, • Salary NUMBER(8, 2), • location VARCHAR(15), • ); • INSERT INTO employee (id, salary, location) VALUES (1004, ‘ali', fsd); • INSERT INTO employee (id, salary, location) VALUES (1005, ‘saba', lhr); • CREATE VIEW vw_dragon As • Select id, name, salary, location FROM employee, employeelog; Instead of insert INSERT INTO vw_dragon values (1006, ronaldo, 65000, portugal); • Create trigger tr_insert • Instead of insert on vw_dragon • For each row • Begin • Insert into employee (id, Name, Salary) values (:new.id, :new. Name, :new. Salary ); • Insert into employeelog (id, salary, location) values (:new.id, :new. Salary, :new. location ); • end; • / • INSERT INTO vw_dragon values (1006, ronaldo, 65000, portugal);
  21. • Instead of update • Update vw_dragon set name = messi where location=‘portugal’; Create trigger tr_update Instead of update on vw_dragon For each row Begin update employee set name= :new.name Where name= :old.name; update employeelog set location= :new.location Where location= :old. location; end; / • Instead of delete Create trigger tr_delete Instead of delete on vw_dragon For each row Begin Delete from employee Where name= :old.name; Delete from employeelog Where location= :old. location; end; / Delete from vw_dragon where name= ali;
  22. System level trigger • Comes into action when some system event occur e.g. database log on, log off, start up, or shut down, server error (used for monitoring activities for system events) • Syntax Create or replace Trigger trigger-name before | after database _event on database/schema Begin PL/SQL code END; /
  23. Compound triggers • Combination of both row level and statement level triggers.
  24. Write output of the following code ? • Monster (table 1 name) • Create table mo_audit ( • new_name varchar2(30), • Old_name varchar2(30), • user_name varchar2(30), • entry_date varchar2(30), • operation varchar2(30) • ); Create or replace Trigger monster_audit Before insert update delete On monster for each row Enable Declare • v_uservarchar2(30); • v_date varchar2(30); Begin Select user, To_char(sysdate, ‘DD/MM/YYYY HH24:MI:SS’) into v_user, v_date from dual; If inserting then Insert into mo_audit (new_name, old_name, user_name, entry_date, opeartion ) Values(: New. mo_name, Null, v_user, v_date, ‘Insert’); Elsif deleting then Insert into mo_audit (new_name, old_name, user_name, entry_date, opeartion ) Values(Null, :Old.mo_name, v_user, v_date, ‘delete’); Elsif updating then Insert into mo_audit (new_name, old_name, user_name, entry_date, opeartion ) Values(:New. mo_name, Old.mo_name, v_user, v_date, ‘update’); END; /
  25. Write output for the following codes?
Advertisement