Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Скачиваний:
40
Добавлен:
16.04.2013
Размер:
4.96 Mб
Скачать

Examples of Trigger Applications

The following example illustrates how a trigger can be used to derive new column values for a table whenever a row is inserted or updated.

Note: You may need to set up the following data structures for the example to work:

ALTER TABLE Emp99 ADD(

Uppername VARCHAR2(20),

Soundexname VARCHAR2(20));

CREATE OR REPLACE TRIGGER Derived

BEFORE INSERT OR UPDATE OF Ename ON Emp99

/* Before updating the ENAME field, derive the values for the UPPERNAME and SOUNDEXNAME fields. Users should be restricted from updating these fields directly: */

FOR EACH ROW BEGIN

:new.Uppername := UPPER(:new.Ename); :new.Soundexname := SOUNDEX(:new.Ename);

END;

Building Complex Updatable Views Using Triggers: Example

Views are an excellent mechanism to provide logical windows over table data. However, when the view query gets complex, the system implicitly cannot translate the DML on the view into those on the underlying tables. INSTEAD OF triggers help solve this problem. These triggers can be defined over views, and they fire instead of the actual DML.

Consider a library system where books are arranged under their respective titles. The library consists of a collection of book type objects. The following example explains the schema.

CREATE OR REPLACE TYPE Book_t AS OBJECT

(

Booknum

NUMBER,

Title

VARCHAR2(20),

Author

VARCHAR2(20),

Available

CHAR(1)

);

CREATE OR REPLACE TYPE Book_list_t AS TABLE OF Book_t;

Using Triggers 9-47

Examples of Trigger Applications

Assume that the following tables exist in the relational schema:

Table Book_table (Booknum, Section, Title, Author, Available)

Booknum

Section

Title

Author

Available

 

 

 

 

 

121001

Classic

Iliad

Homer

Y

121002

Novel

Gone With the Wind

Mitchell M

N

 

 

 

 

 

Library consists of library_table(section).

Section

Geography

Classic

You can define a complex view over these tables to create a logical view of the library with sections and a collection of books in each section.

CREATE OR REPLACE VIEW Library_view AS

SELECT i.Section, CAST (MULTISET (

SELECT b.Booknum, b.Title, b.Author, b.Available

FROM Book_table b

WHERE b.Section = i.Section) AS Book_list_t) BOOKLIST

FROM Library_table i;

Make this view updatable by defining an INSTEAD OF trigger over the view.

CREATE OR REPLACE TRIGGER Library_trigger INSTEAD OF INSERT ON Library_view FOR EACH ROW

Bookvar BOOK_T; i INTEGER;

BEGIN

INSERT INTO Library_table VALUES (:NEW.Section); FOR i IN 1..:NEW.Booklist.COUNT LOOP

Bookvar := Booklist(i); INSERT INTO book_table

VALUES ( Bookvar.booknum, :NEW.Section, Bookvar.Title, Bookvar.Author, bookvar.Available);

END LOOP; END;

/

9-48 Oracle Database Application Developer's Guide - Fundamentals

Соседние файлы в папке Oracle 10g