Presentation is loading. Please wait.

Presentation is loading. Please wait.

SQL Stored Triggers Presented by: Dr. Samir Tartir

Similar presentations


Presentation on theme: "SQL Stored Triggers Presented by: Dr. Samir Tartir"— Presentation transcript:

1 SQL Stored Triggers Presented by: Dr. Samir Tartir
Session - 6 Sequence - 10 SQL Stored Triggers Presented by: Dr. Samir Tartir

2 Outline Trigger Types Design Considerations Column-based Triggers
BEFORE & AFTER Triggers FOR EACH ROW Triggers The WHEN Clause

3 Oracle SQL Triggers Objective: Definition:
To monitor a database and take action when a condition occurs Definition: Stored procedures that execute (fire) automatically when something (event) happens in the database. E.g.: data modification (INSERT, UPDATE or DELETE) schema modification (CREATE, DROP…) system event (user logon/logoff)

4 Usage Automatically generate derived column values
Prevent invalid transactions Enforce complex security authorizations Enforce referential integrity across nodes in a distributed database Enforce complex business rules Provide transparent event logging Provide auditing Maintain synchronous table replicas Gather statistics on table access Modify table data when DML statements are issued against views Publish information about database events, user events, and SQL statements to subscribing applications

5 Triggers Specification
A trigger’s specification includes the following: Event Such as an insert, deleted, or update operation Condition Action To be taken when the condition is satisfied

6 Trigger Types Row-level Statement-level BEFORE and AFTER
INSTEAD OF (used for views) Schema (CREATE, ALTER, DROP) Database-level (SERVERERROR, LOGON, LOGOFF, STARTUP, SHUTDOWN)

7 Coding Triggers PL/SQL trigger body is built like a PL/SQL procedure
Old and new row values are accessible via :old and :new qualifiers If FOR EACH ROW clause is used the trigger will be a row-level one DDL statements are not allowed in the body of a trigger.

8 Trigger Design Considerations
Use triggers to guarantee that when a specific operation is performed, related actions are performed. Do not define triggers that duplicate features already built into the database engine. For example, do not define triggers to reject bad data if you can do the same checking through declarative integrity constraints.

9 Trigger Design Considerations (contd.)
Limit the size of triggers. If the logic for your trigger requires much more than 60 lines of PL/SQL code, it is better to include most of the code in a stored procedure and call the procedure from the trigger. Use triggers only for centralized, global operations that should be fired for the triggering statement, regardless of which user or database application issues the statement.

10 Trigger Design Considerations (contd.)
Do not create recursive triggers. For example, creating an AFTER UPDATE statement trigger on the Emp_tab table that itself issues an UPDATE statement on Emp_tab, causes the trigger to fire recursively until it has run out of memory. Use triggers judiciously, mainly DATABASE triggers, as they can slow the database. They are executed for every user every time the event occurs on which the trigger is created.

11 Trigger Example The following statement creates a trigger for the Emp_tab table. CREATE OR REPLACE TRIGGER Print_salary_changes BEFORE DELETE OR INSERT OR UPDATE ON Employee FOR EACH ROW WHEN (new.SSN > 0) DECLARE sal_diff number; BEGIN sal_diff := :new.salary - :old.salary; dbms_output.put('Old salary: ' || :old.salary); dbms_output.put(' New salary: ' || :new.salary); dbms_output.put_line(' Difference ' || sal_diff); END; /

12 Column-Based Triggers
If a triggering statement includes a column list, the trigger is fired only when one of the specified columns is updated. A column list cannot be specified for INSERT or DELETE triggering statements. The previous example of the PRINT_SALARY_CHANGES trigger could include a column list in the triggering statement. For example: BEFORE DELETE OR INSERT OR UPDATE OF FName ON Employee This trigger would only be fired on updates only if the FName field is updated.

13 BEFORE & AFTER BEFORE AFTER
To modify the row before the row data is written to disk. AFTER To obtain, and perform certain operations, using the row ID.

14 “FOR EACH ROW” Triggers
The FOR EACH ROW option determines whether the trigger is a row trigger or a statement trigger. If you specify FOR EACH ROW, then the trigger fires once for each row of the table that is affected by the triggering statement. If the “FOR EACH ROW” option then the trigger fires only once for each statement.

15 Example CREATE OR REPLACE TRIGGER Log_salary_increase
AFTER UPDATE ON Employee FOR EACH ROW WHEN (new.Salary > 1000) BEGIN INSERT INTO Emp_log (Emp_id, Log_date, New_salary, Action) VALUES (:new.SSN, SYSDATE, :new.Salary, 'NEW SAL'); END; UPDATE Employee SET Salary = Salary WHERE DeptNo = 20;

16 Example (contd.) CREATE OR REPLACE TRIGGER Log_emp_update
AFTER UPDATE ON Employee BEGIN INSERT INTO Emp_log (Log_date, Action) VALUES (SYSDATE, 'Emp_tab COMMISSIONS CHANGED'); END;

17 The “WHEN” Clause A trigger restriction can be included in the definition of a row trigger by specifying a Boolean SQL expression in a WHEN clause. A WHEN clause cannot be included in the definition of a statement trigger. The condition is evaluated for each row that the trigger affects. the trigger body is fired on behalf of that row, only if the expression evaluates to TRUE for a row.

18 Detecting the Firing DML Operation
If more than one type of DML operation can fire a trigger (for example, ON INSERT OR DELETE OR UPDATE OF Emp_tab), the trigger body can use the conditional predicates INSERTING, DELETING, and UPDATING to check which type of statement fire the trigger. For example, you can write: IF INSERTING THEN ... END IF; IF UPDATING THEN ... END IF; In an UPDATE trigger, a column name can be specified with an UPDATING conditional predicate to determine if the named column is being updated. For example: IF UPDATING ('SAL') THEN ... END IF;

19 Errors Like any code, triggers (and other PL/SQL code) can produce errors Examples: Division by zero Running a SELECT statement that returns 0 rows Running a SELECT statement that returns more than one row Violating integrity constraints Etc.

20 Errors, cont’d When an error happens, Oracle produces an error message. Each Oracle error has a number E.g. ORA-01442: Exact Fetch returns more the requested number of rows ORA-0512: at line 4

21 Handling Errors The programmer can take actions when an error happens
E.g. Replace the default error message with a user-friendlier message Insert a record in the error log. This is done using the “EXCEPTION” statement

22 EXCEPTION WHEN Statement
EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE(‘No employees’); WHEN TOO_MANY_ROWS THEN DBMS_OUTPUT.PUT_LINE(‘Many employee returned’); WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE(‘Another error occurred’); Default case

23 Errors CURSOR_ALREADY_OPEN INVALID_CURSOR INVALID_NUMBER LOGIN_DENIED
NO_DATA_FOUND TOO_MANY_ROWS VALUE_ERROR ZERO_DIVIDE Etc.

24 RAISE_APPLICATION_ERROR
A procedure defined by Oracle that allows the developer to raise an exception and associate an error number and message with the procedure This allows the application to raise application errors rather than just Oracle errors. Error numbers are defined between -20,000 and -20,999.

25 Error Example BEGIN IF (nBalance <= 100) THEN Raise_Application_Error (-20343, 'Balance is too low.'); END IF; END;

26 Database-Level Triggers
CREATE [OR REPLACE] TRIGGER trigger_name { BEFORE | AFTER } { SERVERERROR | LOGON | LOGOFF | STARTUP | SHUTDOWN } ON DATABASE BEGIN pl/sql_statements END;

27 Example CREATE OR REPLACE TRIGGER logon_log_trigger AFTER LOGON ON DATABASE BEGIN INSERT INTO session_logon_statistics (user_logged, start_time) VALUES (USER, SYSDATE); END; /

28 DDL-Level Triggers BEFORE / AFTER ALTER BEFORE / AFTER ANALYZE BEFORE / AFTER ASSOCIATE STATISTICS BEFORE / AFTER AUDIT BEFORE / AFTER COMMENT BEFORE / AFTER CREATE BEFORE / AFTER DDL BEFORE / AFTER DISASSOCIATE STATISTICS BEFORE / AFTER DROP BEFORE / AFTER GRANT BEFORE / AFTER NOAUDIT BEFORE / AFTER RENAME BEFORE / AFTER REVOKE BEFORE / AFTER TRUNCATE AFTER SUSPEND

29 Example CREATE OR REPLACE TRIGGER bcs_trigger BEFORE CREATE ON SCHEMA DECLARE oper ddl_log.operation%TYPE; BEGIN INSERT INTO ddl_log SELECT ora_sysevent, ora_dict_obj_owner, ora_dict_obj_name, NULL, USER, SYSDATE FROM DUAL; END bcs_trigger; /

30 SUMMARY Triggers are used to monitor a database and take action when a condition occurs Triggers can be row-level, statement-level, database-level, or schema-level.

31 Resources & References
Dr. Samir Tartir Website: Fundamentals of Database Systems by El Masri & Navathe. Publisher : Addison-Wesley, 5th edition, 2006.


Download ppt "SQL Stored Triggers Presented by: Dr. Samir Tartir"

Similar presentations


Ads by Google