trigerppt

Upload: ansh2003

Post on 04-Apr-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/30/2019 trigerppt

    1/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

    modification 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)

  • 7/30/2019 trigerppt

    2/28

    The general structure of triggers is:CREATE [OR REPLACE]

    TRIGGER trigger name

    BEFORE (or AFTER)

    INSERT OR UPDATE [OF COLUMNS] OR DELETEON table name

    [FOR EACH ROW [WHEN (condition)]]

    BEGIN

    ...

    END;

  • 7/30/2019 trigerppt

    3/28

    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 tofire before the insert take s place.

    CREATE OR REPLACE

    TRIGGER PERSON_INSERT_BEFORE

    BEFORE

    INSERTON PERSON

    FOR EACH ROW

    BEGIN

    DBMS_OUTPUT.PUT_LINE(BEFORE INSERT OF ||

    :NEW.NAME);

    END;

  • 7/30/2019 trigerppt

    4/28

    Now let us test it out:

    INSERT INTO PERSON(ID,NAME,DOB) VALUES (1,JOHN DOE,SYSDATE);

    The single INSERT statement fires 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

    BEGINDBMS_OUTPUT.PUT_LINE(AFTER INSERT OF ||

    :NEW.NAME);

    END;

  • 7/30/2019 trigerppt

    5/28

    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 fired.

    One before the INSERT the other one after

  • 7/30/2019 trigerppt

    6/28

    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)

  • 7/30/2019 trigerppt

    7/28

    Special IF statements

    Inside the P L/SQL block of a trigger we can use if statements to

    determine what statement caused the firing of the trigger. These aregenerally of the form:

    IF inserting THEN...where besides inserting you c an also use

    updating and deleting. An example would be something like:

  • 7/30/2019 trigerppt

    8/28

    CREATE OR REPLACE

    TRIGGER PERSON_BIUD

    BEFORE INSERT OR UPDATE OR DELETE ON PERSON

    FOR EACH ROWBEGIN

    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;

  • 7/30/2019 trigerppt

    9/28

    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

  • 7/30/2019 trigerppt

    10/28

    And finally , 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;

  • 7/30/2019 trigerppt

    11/28

    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 effects (like updating tables). The generalformat of a procedure is :

    PROCEDURE procedure_name IS

    BEGINprocedure_body

    END;

  • 7/30/2019 trigerppt

    12/28

    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();

  • 7/30/2019 trigerppt

    13/28

    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

  • 7/30/2019 trigerppt

    14/28

    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 thevalues you provide ):

    SQL> CALL DISP_AB(17,23);

    A + B = 40

    A * B = 391

  • 7/30/2019 trigerppt

    15/28

    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:

    DECLARER INT;

    BEGIN

    R := 7;

    DBMS_OUTPUT.PUT_LINE(BEFORECALL 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

  • 7/30/2019 trigerppt

    16/28

    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;

  • 7/30/2019 trigerppt

    17/28

    FunctionsFunctions 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_typeIS

    BEGIN

    function_body

    RETURN something_of_return_type;END;

  • 7/30/2019 trigerppt

    18/28

    For example, to write a function that computes the s um of two

    numbers, you might do something like this:

    CREATE OR REPLACEFUNCTION 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

    DBMS_OUTPUT.PUT_LINE(RESULT IS: || ADD_TWO(12,34));END;

    Which procudes the output:

    RESULT IS: 46

  • 7/30/2019 trigerppt

    19/28

    Dropping Functions

    To drop a function, you do it in a similar way to a procedure.

    You simply say:

    DROP FUNCTION function_name;

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

    DECLAREmaxi NUMBER;mini NUMBER;BEGINFind(mini,maxi);

    DBMS_OUTPUT.PUT_LINE('MAXIMUM AND MINIMUM OF rating from sailor '||maxi||','||mini);

    END;/

    Q. write a procedure to find the minimum and maximum rating of

    sailors from sailors table .Display this value in the main program.

  • 7/30/2019 trigerppt

    20/28

    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 )

  • 7/30/2019 trigerppt

    21/28

    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 thatstatement. 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

    SyntaxCURSOR 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.

  • 7/30/2019 trigerppt

    22/28

    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, youinitialize 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.

  • 7/30/2019 trigerppt

    23/28

    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));

    d l

  • 7/30/2019 trigerppt

    24/28

    declarecursor cemp is select empcode,salary from employe where

    deptno=20;strempcode employe.empcode%type;numsalary employe.salary%type;beginopen cemp;loopfetch cemp into strempcode,numsalary;if cemp%found thenupdate employe set salary=numsalary+(numsalary*0.05)where empcode=strempcode;insert into empraise

    values(strempcode,sysdate,numsalary*0.05);elseexit;end if;end loop;commit;close cemp;end;

    /

  • 7/30/2019 trigerppt

    25/28

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

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

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

    salary number(8));

  • 7/30/2019 trigerppt

    26/28

    declareCursor C is select NAME,DEPT,SALARY from employee order

    by salary;n varchar(10);s number(8);d number(8);beginopen c;dbms_output.put_line(' NAME DEPT SALARY');

    loopfetch c into n,d,s;dbms_output.put_line(N||' '||D||' '||S);EXIT when c%rowcount=2;end loop;close c;

    end;/

  • 7/30/2019 trigerppt

    27/28

  • 7/30/2019 trigerppt

    28/28

    CREATE OR REPLACE PROCEDURE FinddetailsIS

    BEGINDECLARECURSOR s_sailors IS SELECT * FROM sailorsWHERE rating >7;

    BEGINDBMS_OUTPUT.PUT_LINE('sid sname age');DBMS_OUTPUT.PUT_LINE('........ ..........

    ..........');for i IN s_sailorsloopDBMS_OUTPUT.PUT_LINE(i.sid||' '||i.sname||'

    '||i.age);end loop;END;END Finddetails;

    beginFinddetails;END;/

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

    than 7