1 Oracle PL/SQL TRIGGERS iSQLplus:

Slides:



Advertisements
Presentaciones similares
 Making complete sentences How to make complete sentences in Spanish. The following presentation is designed to help you learn how to do the following:
Advertisements

Editing Slides With Polaris Office, you can create new .ppt and .pptx presentations or edit your presentation with ease.
Negatives and Questions. Negatives Consider the following sentences: Juan estudia mucho. Marta y Antonio viven en Georgia. Rita y el chico necesitan.
WALT: talking about dates and saying when your birthday is WILF: To be able to write & understand months and dates in Spanish to get to a Level 2 To be.
Stem-changing verbs.
VOCABULARIO #2.4 ¡Aprenda! Forming Questions Señora Sequin.
Spanish –er and –ir verbs. Verbs in General English and Spanish both conjugate verbs. They can be organized as 1rst, 2 nd, and 3 rd person. If you need.
UNITA - IBARRA TRIGGERS
Telling Time.
What time is it? DLT: I can tell time in Spanish..
1 – 999,999,999.
TRIGGERS EN ORACLE 8 J. Iriarte S. España
Objective: I can recognize and accurately use gender agreement. Do Now: Match the following Spanish and English words: 1. Pelirroja a. Good-looking 2.
DIRECT OBJECT PRONOUNS. DIRECT OBJECTS The object that directly receives the action of the verb is called the direct object. Mary kicked the ball. "Ball"
How to Conjugate Regular –AR – Er - IR Verbs in the Present Tense.
La hora. The traditional way to tell time in Spanish is by dividing the clock in half. The right side uses “y” to add minutes to the hour. Once the minute.
DIRECT OBJECT PRONOUNS. DIRECT OBJECTS The object that directly receives the action of the verb is called the direct object. Mary kicked the ball. "Ball"
Unit 2A: Lesson 2 How to Talk About Your Schedule Gramática- Present tense of –ar verbs.
¿Qué haces en la escuela? Question words, objects, yo-go’s.
Indirect Object Pronouns
La hora. The traditional way to tell time in Spanish is by dividing the clock in half. The right side uses “y” to add minutes to the hour. Once the minute.
CONJUGATION.
JUEVES, EL 10 DE SEPTIEMBRE LT: I WILL RECOGNIZE SOME NEW VOCABULARY WORDS. Go over tests & retake procedures Interpretive Assessment: numbers & alphabet.
unas frases increíblemente útiles some incredibly useful phrases (for dodging conjugation)
I can… Listen and respond to questions in L2 Review concepts from Spanish 1 Recognize when to use SER or ESTAR Use SER/ESTAR in context Recognize when.
Indirect Object Pronouns Original PowerPoint was by Ms. Martin of Tri-Center Community Schools.
ECOM-6030 PASOS PARA LA INSTALACIÓN DE EASYPHP Prof. Nelliud D. Torres © - Derechos Reservados.
Un juego de adivinanzas: ¿Dónde está el tesoro? A1B1C1D1E1F1 A4B4C4D4E4F4 A2B2C2D2E2F2 A5B5C5D5E5F5 A3B3C3D3E3F3 A6B6C6D6E6F6 Inténtalo de nuevo Inténtalo.
LOS VERBOS REFLEXIVOS. WRITE: What is a reflexive verb? A reflexive verb describes when a person doing an action is also receiving the action.
English Language II (2). English Language I (2) Warm-up.
6 Triggers ORACLE - II Bases de datos II I-2014 Universidad del Cauca Ing. Wilson Ortega Bases de datos II I-2014 Universidad del Cauca Ing. Wilson Ortega.
¡BIENVENIDOS! ALPHABET, COGNATES.. DO NOW Take five minutes to Silently and Independently fill out the calendar on your desk. Every Calendar should have:
6 Triggers ORACLE - III Bases de datos II I-2014 Universidad del Cauca Ing. Wilson Ortega Bases de datos II I-2014 Universidad del Cauca Ing. Wilson Ortega.
Spanish III Honors Week 31. Para Empezar 20 de abril In English, what is happening in this comic?
Present Tense of AR Verbs Las clases de Sra. Schwarz Realidades 1.
Martes, 4 de octubre WALT: how to tell the time in Spanish WILF: to be able to understand and begin to say the time in Spanish Can you match these times.
Haz ahora el 27 de octubre de 2015 Complete each sentence with the correct form of ser and estar: 1.Mi cuarto ________ al lado de la sala. 2.Manuel y Fernando.
© Copyright Showeet.com E XAMPLE 1 A BSTRACT 3D P APER I NFOGRAPHICS Your own text goes here.
Welcome! Conversation Classes. Remembering Names Everyone Stand! Introduce yourself to class and give your name an action! Go around the class and try.
¿Qué son los verbos irregulares?
Los Adjetivos Posesivos
Present Tense of –ar Verbs
Las clases de Sra. Schwarz Realidades 1
Direct object pronouns
Double Object Pronouns
PREGUNTAS: Questions and Question Words
Español 1 11 de mayo de 2017 Good morning, thank you for taking my classes today. For the most part the kids are really great. Here is my schedule for.
Getting to know you more!
First Grade Dual High Frequency Words
El Imperfecto Español 2.
More sentences that contain if…
Warm-up Fill in the blank with the correct form of the verb “ser” for each subject (p. 35): 1. Yo _______________ de Savannah. 2. Mis amigas ________.
Language Objective: I will learn how to utilize direct object pronouns
Ser y Estar To be or….to be?
Gramática (pg 9 del paquete rosado)
PREGUNTAS: Questions and Question Words
Recetas 3 Objetivo: Hacer preguntas Hablar sobre la comida
Quasimodo: Tienes que hacer parte D de la tarea..
El subjuntivo en cláusulas adverbiales:
UNIVERSIDAD TECNICA DE MACHALA UNIDAD ACADEMICA DE CIENCIAS EMPRESARIALES CARRERA DE ECONOMIA ESTUDENTS: FIRST CONDITIONAL SENTENCES TEACHER: - Calvache.
Telling Time (La hora).
Miranda Rights El Aviso Miranda
The Windows File System and Windows Explorer To move around the file system and examine your files or get to one you want (say, to modify, delete or copy.
Indirect Questions First Day on the Job 11 Focus on Grammar 4 Part X, Unit 28 By Ruth Luman, Gabriele Steiner, and BJ Wells Copyright © Pearson Education,
Teach me how to conjugate
Gustar, Interesar, Aburrir
Development of the concert programme
Welcome to PowerPoint gdskcgdskfcbskjc. Designer helps you get your point across PowerPoint Designer suggests professional designs for your presentation,
How to write my report. Checklist – what I need to include Cover page Contents page – with sections Introduction - aims of project - background information.
Transcripción de la presentación:

1 Oracle PL/SQL TRIGGERS iSQLplus:

2 What is a trigger? A block of code that is attached to an event. When that event occurs the trigger code is fired. A stored block with [Declare], Begin, End. Associated with a database table or action Fires automatically when certain DML action is carried out on the table – Before or after an event – Change may be INSERT, DELETE, UPDATE – Do we want to perform on multiple rows? – If not, then Statement level trigger fires once only – If so, then Row level trigger fires for each affected row

3 Trigger Uses 1. Auditing – Write information about (sensitive) data modifications to an audit table – May include old and new values, user, timestamp – E.g. new and old salary 2. Data Integrity – Implement checks on data against business rules – Can compare with live database values – NEW and OLD values can be compared – E.g. prices must not go down

4 Trigger Uses 3. Referential integrity – Allows implementation of a "cascade update" – E.g. if author ID (aID) is changed, appropriately change authID in foreign key 4. Derived data – Update any stored derived data when base data changes – E.g. if total number of employees is stored, add 1 if new employee added

5 Trigger Uses 5. Security Logging of database access E.g. date and time each user logs on E.g. deny access at weekend 6. Maintaining synchronous replicates In a distributed database 7. Generating statistics on table access

6 Types of Trigger and Naming Statement or Row triggers So 4 types can be triggered: – Before Statement, Before Row – After Statement, After Row Naming them – Must be unique within a schema – Can have same name as table on which it is defined but this may be confusing to developers

7 Statement Triggers CREATE OR REPLACE TRIGGER trig_testTable AFTER INSERT or UPDATE ON Personnel BEGIN If Inserting Then INSERT into testTable values ('insert done', SYSDATE) ; Else INSERT into testTable values ('update done', SYSDATE) ; End If; END; The statement level trigger is useful for INSERT as it only involves a single row whereas DELETE and UPDATE often deal with many rows at once Inserting, Deleting and Updating can be used to find out which event is occurring Test_trigger_1 tests this trigger

8 Row trigger Operates on many rows potentially CREATE OR REPLACE TRIGGER trig_test AFTER UPDATE OF SNUM ON PERSONNEL FOR EACH ROW BEGIN null;-- write operations here END; A Row trigger fires once for every row affected by the DML operation

9 :OLD and :NEW When a DML statement changes a column the old and new values are visible to the executing code This is done by prefixing the table column with :old or :new :new is useful for INSERT and UPDATE :old is useful for DELETE and UPDATE triggers may fire other triggers in which case they are CASCADING. Try not to create too many interdependencies with triggers!

10

11 Referential integrity trigger example CREATE OR REPLACE TRIGGER author_trg AFTER UPDATE OF aID ON author FOR EACH ROW BEGIN UPDATE Book SET authID = :new.aID WHERE authID= :old.aID; END; UPDATE author SET aID='9' WHERE aID='5'; 1 row updated. UPDATE author SET aID='9' WHERE aID='5'; ERROR at line 1: ORA-02292: integrity constraint (MCTPL.BOOK_FK) violated - child record found Without trigger – referential integrity prevents changes to aID With trigger – changes to aID are now allowed! Trigger automatically applies corresponding changes to aID in child table

12 Referring to Values which fire the trigger So remember …………. While trigger is running, it knows the old and the new values of the record you're updating You need to specify which you want to refer to Prefix column name with :new. or :old. … AFTER UPDATE OF name ON publisher … INSERT INTO publish_audit VALUES(SYSDATE, :new.name, :old.name); … A record of what has changed

13 Example trigger: business rules CREATE OR REPLACE TRIGGER publish_trg BEFORE INSERT OR UPDATE ON book FOR EACH ROW DECLARE how_many NUMBER; BEGIN SELECT COUNT(*) INTO how_many FROM book WHERE publisher = :new.publisher; IF how_many >= 3 then Raise_application_error(-20000,'Publisher' || :new.publisher || 'already has 3 books'); END IF; END; Trigger header PL/SQL Block

14 Example explained Creates a trigger called publish_trg Executes before data in book table is added/updated – Can prevent the change if necessary – Not fired if deleting from book table Following block will execute once for each row – Whenever book table data is changed or added CREATE OR REPLACE TRIGGER publish_trg BEFORE INSERT OR UPDATE ON book FOR EACH ROW

15 Example explained Count how many records already exist with the same publisher value as the new record (the one being added or updated) If count is 3 or more, error fires - Output message and abort transaction DECLARE how_many NUMBER; BEGIN SELECT COUNT(*) INTO how_many FROM book WHERE publisher = :new.publisher; IF how_many >= 3 THEN Raise_application_error(-20000, ('Publisher ' ||:new.publisher || ' already has 3 books')); END IF; END;

16 Raise_application_error Used inside trigger Purpose: – output an error message and – immediately stop the event that fired the trigger – For example, data insertion Can include variables/trigger values, see previous slide E.g. RAISE_APPLICATION_ERROR(-20000,'trigger violated') label Message text

17 The Trigger in use insert into book (ISBN,publisher) values(' ','McGraw-Hill') * ERROR at line 1: ORA-20000: Publisher 4233 already has 3 books ORA-06512: at "MCTPL.PUBLISH_TRG", line 7 ORA-04088: error during execution of trigger 'MCTPL.PUBLISH_TRG' update book set publisher='McGraw-Hill' where ISBN=' ' * ERROR at line 1: ORA-04091: table MCTPL.BOOK is mutating, trigger/function may not see it ORA-06512: at "MCTPL.PUBLISH_TRG", line 4 ORA-04088: error during execution of trigger 'MCTPL.PUBLISH_TRG' This should happen This is a common problem When updating

18 Trigger error: Table is mutating Example: Update to table x fires trigger trigger queries/ modifies table x This is a problem! – happens only for update, not for insert – Can be fixed by using two triggers, or dummy table, but quite tricky (see Casteel, J. (2003). Oracle 9i Developer: PL/SQL Programming. p.318) table trigger

19 WHEN clause Optional additional statement to control the trigger Takes a BOOLEAN SQL expression – Trigger fires if TRUE and not if FALSE Operates on a ROW level trigger – To prevent the trigger from firing in specific row cases WHEN (expression)

20 WHEN Example create or replace trigger only_nulls after update on BOOK for each row when (old.price is null) -- notice the colon with OLD is not used here begin insert into PriceChange values(:old.isbn,:new.price); end;

21 Compilation errors When you create a trigger, Oracle responds – "Trigger created" or – "Warning: Trigger created with compilation errors." Type in the command SHOW ERRORS on its own to make the error messages visible

22 What to think about BEFORE or AFTER? INSERT, DELETE, UPDATE? FOR EACH ROW or once only? Any error conditions/messages? How can I test that the trigger works?

23 What else can we do with triggers DROP TRIGGER trigger_name; – No further firing will occur when dropped ALTER TRIGGER trigger_name DISABLE; ALTER TRIGGER trigger_name ENABLE; ALTER TABLE table_name DISABLE ALL TRIGGERS; ALTER TABLE table_name ENABLE ALL TRIGGERS;

24 Trigger problems Easy to confuse := with = with = :old Compilation errors: use SHOW ERRORS to see them Errors may need to be solved in a different place from where they occur "table is mutating"

25 Reading & References In Safari e-books: Rosenzweig and Silvestrova (2003). Oracle® PL/SQL™ by Example, 3 rd ed. Lots of Oracle/SQL books have sections on PL/SQL, e.g. (in library) – Shah, N. (2002). Database Systems Using Oracle. A simplified guide to SQL and PL/SQL. Ch. 8 onwards – Morris-Murphy chapters 15 & 16 – Earp/Bagui Ch. 12, 13 This goes way beyond our coverage: Casteel, J (2003). Oracle 9i Developer: PL/SQL Programming Connolly/Begg (3 rd ed) Sections 8.2.5, 8.2.7, Elmasri section 24.1

26 Using the Data Dictionary to list stored programs SELECT object_type, object_name FROM user_objects WHERE object_type IN ( 'PROCEDURE','FUNCTION','TRIGGER') ORDER BY object_type; Test_2

27 Getting the code SELECT text FROM user_source WHERE name ='SAL_TRG' ; trigger sal_trg after update on personnel_copy for each row when (old.salary > and old.bonus is not null) begin if inserting then insert into audit_salaries values(null,:new.salary); elsif deleting then insert into audit_salaries values(:old.salary, null); else insert into audit_salaries values(:old.salary,:new.salary); end if; end; Test_3

28 Triggers are in the Data Dictionary Info about your triggers is held in USER_TRIGGERS etc. Trigger_nameName of trigger Triggering_eventINSERT, UPDATE, DELETE Table_ownerOwner of the table attached to Table_nameName of the table attached to Referencing_namesNames used for OLD and NEW StatusDisabled or Enabled DescriptionTrigger description Trigger_bodyStatements executed when fired