Vous êtes sur la page 1sur 28

Triggers are simply stored procedures that are ran automatically by the database whenever some e vent (usually

a table up date) happens .

Triggers are basically PL/SQL procedure s that are associated with tables, and are called whenever a certain modification (event) occurs. The modication statements may include INSERT, UPDATE, and DELETE.
Trigger: procedure that starts automatically if specified changes occur to the DBMS Three parts: Event (activates the trigger) Condition (tests whether the triggers should run) Action (what happens if the trigger runs)

The general structure of triggers is: CREATE [OR REPLACE] TRIGGER trigger name BEFORE (or AFTER) INSERT OR UPDATE [OF COLUMNS] OR DELETE ON table name [FOR EACH ROW [WHEN (condition)]] BEGIN ... END;

Sample Table to b e Triggered CREATE TABLE PERSON (ID INT, NAME VARCHAR(30), DOB DATE, PRIMARY KEY(ID) ); 1.Before Insert Trigger We write a trigger to re before the insert take s place. CREATE OR REPLACE TRIGGER PERSON_INSERT_BEFORE BEFORE INSERT ON PERSON FOR EACH ROW BEGIN DBMS_OUTPUT.PUT_LINE(BEFORE INSERT OF || :NEW.NAME); END;

Now let us test it out: INSERT INTO PERSON(ID,NAME,DOB) VALUES (1,JOHN DOE,SYSDATE); The single INSERT statement res the trigger. When we run it, we get the print out of BEFORE INSERT OF JOHN DOE. I e:

2. After Insert Trigger CREATE OR REPLACE TRIGGER PERSON_INSERT_AFTER AFTER INSERT ON PERSON FOR EACH ROW BEGIN DBMS_OUTPUT.PUT_LINE(AFTER INSERT OF || :NEW.NAME); END;

And with our 2nd test INSERT

INSERT INTO PERSON(ID,NAME,DOB) VALUES (2,JANE DOE,SYSDATE); For a total result of: INSERT INTO PERSON(ID,NAME,DOB) VALUES (2,JANE DOE,SYSDATE);

BEFORE INSERT OF JANE DOE AFTER INSERT OF JANE DOE

Notice that both triggers have red. One before the INSERT the other one after

3.Before Up date Statement Trigger

Now that we have some data in the table, we can create an up date trigger, that would fire whenever someone tries to up date any person (or persons).
CREATE OR REPLACE TRIGGER PERSON_UPDATE_S_BEFORE BEFORE UPDATE ON PERSON BEGIN DBMS_OUTPUT.PUT_LINE(BEFORE UPDATING SOME PERSON(S)); END;

Now , lets run an up date... UPDATE PERSON SET DOB = SYSDATE; Which produces the result: SQL> UPDATE PERSON SET DOB = SYSDATE; BEFORE UPDATING SOME PERSON(S)

Special IF statements
Inside the P L/SQL block of a trigger we can use if statements to determine what statement caused the ring of the trigger. These are generally of the form: IF inserting THEN...where besides inserting you c an also use updating and deleting. An example would be something like:

CREATE OR REPLACE TRIGGER PERSON_BIUD BEFORE INSERT OR UPDATE OR DELETE ON PERSON FOR EACH ROW BEGIN IF INSERTING THEN DBMS_OUTPUT.PUT_LINE(INSERTING PERSON: || :NEW.NAME); ELSIF UPDATING THEN DBMS_OUTPUT.PUT_LINE(UPDATING PERSON: || :OLD.NAME || TO || :NEW.NAME); ELSIF DELETING THEN DBMS_OUTPUT.PUT_LINE(DELETING PERSON: || :OLD.NAME); END IF; END;

Notice that we only have one TRIGGER, and we are using IF statements to determine what statement invoked it, and display an appropriate message in various cases. For example, when we do an insert:
INSERT INTO PERSON(ID,NAME,DOB) VALUES (3,SUPERMAN,TO_DATE(09/05/1950,MM/DD/YYYY))

Then we get output like: INSERTING PERSON: SUPERMAN


If we go ahead and modify that person: UPDATE PERSON SET NAME = BATMAN WHERE NAME = SUPERMAN; Then we get an output like: UPDATING PERSON: SUPERMAN TO BATMAN

And nally , if we go ahead and delete that person: DELETE PERSON WHERE NAME = BATMAN; Then we would get output like: DELETING PERSON: BATMAN
Dropping Triggers
You c an DROP triggers j us t like anything. The general format would b e something like :
DROP TRIGGER triggername;

In order to disable trigger ALTER TRIGGER PERSON_DOB DISABLE;

Just like any other procedural language, PL/SQL has code fragments that are called PROCEDURES. You can call these PROCEDURES from other code fragments, or directly from SQL*Plus Procedures are code fragments that dont normally return a value, but may have some outside eects (like updating tables). The general format of a procedure is : PROCEDURE procedure_name IS BEGIN procedure_body END;

For example, to create (or re place ) a HELLO procedure, you might do something like this:
CREATE OR REPLACE PROCEDURE HELLO IS BEGIN DBMS_OUTPUT.PUT_LINE(Hello World); END; BEGIN HELLO(); END; Or you can s imply execute it in SQL*Plus by typing: CALL HELLO();

CREATE OR REPLACE PROCEDURE DISPN (N INT) IS BEGIN DBMS_OUTPUT.PUT_LINE(N is || N); END; Which if you c all, will promptly dis play: SQL> CALL DISPN(1234567891); N is 1234567891

You can also have multiple parameters. For example, you can accept A and B and display their sum and product.

CREATE OR REPLACE PROCEDURE DISP_AB (A INT, B INT) IS BEGIN DBMS_OUTPUT.PUT_LINE(A + B = || (A + B)); DBMS_OUTPUT.PUT_LINE(A * B = || (A * B)); END;
Which when ran, displays something like (de p ending on the values you provide ): SQL> CALL DISP_AB(17,23); A + B = 40 A * B = 391

IN, OUT , IN OUT


CREATE OR REPLACE PROCEDURE DOUBLEN (N IN OUT INT) IS BEGIN N := N * 2; END;

To run it, we also create a s mall c o de fragment: DECLARE R INT; BEGIN R := 7; DBMS_OUTPUT.PUT_LINE(BEFORE CALL R IS: || R); DOUBLEN(R); DBMS_OUTPUT.PUT_LINE(AFTER CALL R IS: || R); END; Which w hen ran displays: BEFORE CALL R IS: 7 AFTER CALL R IS: 14

Dropping Procedures
If youre interested in getting rid of a procedure totally, you can DROP it. The general format of a DROP is: DROP PROCEDURE procedure_name;

Functions
Functions are special types of procedure s that have the capability to return a value.
The

general format of a function is very similar to the general format of a procedure: CREATE OR REPLACE FUNCTION function name (functionparams) RETURN return_type IS BEGIN function_body RETURN something_of_return_type; END;

For example, to write a function that computes the s um of two numbers, you might do something like this: CREATE OR REPLACE FUNCTION ADD_TWO (A INT,B INT) RETURN INT IS BEGIN RETURN (A + B); END;

To run it, well w rite a small piece of co de that calls this:


BEGIN RESULT IS: 46 DBMS_OUTPUT.PUT_LINE(RESULT IS: || ADD_TWO(12,34)); END; Which procudes the output:

Dropping Functions To drop a function, you do it in a similar way to a procedure. You simply say: DROP FUNCTION function_name; Q. write a procedure to find the minimum and maximum rating of sailors from sailors table .Display this value in the main program.

CREATE OR REPLACE PROCEDURE Find (mini OUT NUMBER,maxi OUT NUMBER) IS BEGIN SELECT MAX(rating ),MIN(rating ) INTO maxi,mini FROM END Find; /

sailors;

DECLARE maxi NUMBER; mini NUMBER; BEGIN Find(mini,maxi); DBMS_OUTPUT.PUT_LINE('MAXIMUM AND MINIMUM OF rating from sailor '||maxi||',' ||mini); END; /

CREATE TABLE sailors( sid integer not null, sname varchar(32), rating integer, age real, CONSTRAINT PK_sailors PRIMARY KEY (sid) );
INSERT INTO sailors ( sid, sname, rating, age ) VALUES ( 22, 'Dustin', 7, 45.0 )

When we execute an SQL statement from PL/SQL the oracle RDBMS assigns a private work area of for that statement. This work contains information about the SQL statement and the set of data returned or affected by that statement. The PL/SQL cursor is a mechanism by which we can name that work area and manipulate the information within it. In simply way cursor is defined as a pointer into a table in the database Syntax CURSOR cursor name as select from table name; CURSOR are classified into two; Implicit 2. Explicit.

Implicit cursor: When select INTO or any DML statement is issued then ORACLE internally opens the cursor. It is named as sql.

Explicit cursor: When Queries return more than one row, then cursor has to be defined explicitly. The cursor should be declared on declaration part of pl/sql block. You use three commands to control a cursor: OPEN, FETCH, and CLOSE. First, you initialize the cursor with the OPEN statement, which identifies the result set. Then, you use the FETCH statement to retrieve the first row. You can execute FETCH repeatedly until all rows have been retrieved. When the last row has been processed, you release the cursor with the CLOSE statement. We can process several queries in parallel by declaring and opening multiple cursors. Q.The HRD manager has decided to raise the salary for all the employees in deptno 20 by 0.05 whenever any such raise is given to the employee a record for that is maintained in the empraise table it includes the empno,date.

Write a PL/SQL block of code to update the salary of each employee and insert a record in the empraise table. create table employe(empcode varchar(10) primary key,ename varchar(20),deptno number(5),job varchar(20),salary number(8,2)); insert into employe values('C101','vidhya',20,'clerk',5000); insert into employe values('C102','maya',30,'teache',10000); insert into employe values('C103','anjali',40,'teacher',15000); select * from employe; create table empraise(empcode varchar(10),raisedate date, amount number(8,2));

declare cursor cemp is select empcode,salary from employe where deptno=20; strempcode employe.empcode%type; numsalary employe.salary%type; begin open cemp; loop fetch cemp into strempcode,numsalary; if cemp%found then update employe set salary=numsalary+(numsalary*0.05) where empcode=strempcode; insert into empraise values(strempcode,sysdate,numsalary*0.05); else exit; end if; end loop; commit; close cemp; end;
/

Q.Write a PL/SQL block that will display the name, department & salary of the first two employees getting the highest salary

create table employee(name varchar(10),dept number(8), salary number(8));

insert insert insert insert

into into into into

employee employee employee employee

values('anu',20,5250); values('vidya',25,3000); values('anjali',30,5500); values('veena',35,2000);

declare Cursor C is select NAME,DEPT,SALARY from employee order by salary; n varchar(10); s number(8); d number(8); begin open c; dbms_output.put_line(' NAME DEPT SALARY'); loop fetch c into n,d,s; dbms_output.put_line(N||' '||D||' '||S); EXIT when c%rowcount=2; end loop; close c; end; /

Write a function to count the rating and display that value in the main program. CREATE OR REPLACE FUNCTION countrating return number is begin declare countrating number(10); begin select count(*) into countrating from sailors; return countrating; end; end countrating; / declare c number(8); begin c:= countrating ; dbms_output.put_line('the countrating is'||c); end; /

Q. Write a procedure(using cursor) to find the details of sailors whose rating greater than 7

CREATE OR REPLACE PROCEDURE Finddetails IS BEGIN DECLARE CURSOR s_sailors IS SELECT * FROM sailors WHERE rating >7; BEGIN DBMS_OUTPUT.PUT_LINE('sid sname age'); DBMS_OUTPUT.PUT_LINE('........ .......... ..........'); for i IN s_sailors loop DBMS_OUTPUT.PUT_LINE(i.sid||' '||i.sname||' '||i.age); begin end loop; Finddetails; END; END; END Finddetails; /

Vous aimerez peut-être aussi