29-10-2013(plsql functions,packages,triggers).docx

Embed Size (px)

Citation preview

  • 8/14/2019 29-10-2013(plsql functions,packages,triggers).docx

    1/21

    ===================================================================================

    ================================================

    PLSQL FUNCTION

    ===================================================================================

    ================================================

    PLSQL FUNCTION TO DISPALY THE CURRENT DATE

    create or replace function today

    return date is

    vday date; --local variable

    begin

    select sysdate into vday from dual;

    return vday; --return the value for vday

    end;

    /

    --EXECUTION 1

    select today from dual;

    --EXECUTION 2

    begin

    dbms_output.put_line('Today is:'||today);

    end;

    ======================================================================

  • 8/14/2019 29-10-2013(plsql functions,packages,triggers).docx

    2/21

    WRITE A PLSQL FUNCTION TO INCREMENT THE SALARY BY 10% FOR ALL EMPLOYEES

    OF DEPARTMENT 40

    create or replace function salary1

    return number is --(return datatype)

    sal number; --(variablename date)

    begin

    select salary into sal from employees where department_id=40;

    return(sal*1.1);

    end;

    /

    begin

    dbms_output.put_line('new salary is:='||salary1);

    end;

    =====================================================================

    WRITE A PLSQL FUNCTION TO ACCEPT AN EMPLOYEE CODE AND RETURN THE TOTAL

    SALARY(SALARY+COMMISSION) OF THE EMOLOYEE. IN CASE THE COMMISSION IS NULL

    THEN THROW THE EXCEPTION NO_COMMISSION.

    create or replace function get_totalsalary(empid IN employees.employee_id%type)

    return number IS

    sal number;

    com number;

  • 8/14/2019 29-10-2013(plsql functions,packages,triggers).docx

    3/21

    --custom exception is declared

    no_commission exception;

    begin

    --write business logic

    --if commission is null

    --exception raised

    select salary,commission_pct into sal,com from employees where employee_id=&emp_id;

    if com is null then

    RAISE no_commission;

    end if;

    return(sal+com);

    exception

    --exception handled

    when no_commission then

    raise_application_error(-20401,'commission not found');

    end;

    begin

    dbms_output.put_line('total salary='||get_totalsalary(&empid));

    end;

    ===================================================================================

    =================================================

    STORED PACKAGES

  • 8/14/2019 29-10-2013(plsql functions,packages,triggers).docx

    4/21

    ===================================================================================

    =================================================

    A package is a database object which encapsulate realted procedure, functions, associated cursors

    and variables together as logical unit in the database.

    create or replace package emp_operations

    is

    procedure hire_employee;

    procedure fire_employee(empid virtusa_employees.employee_id%type);

    function get_totalsalary(empid employees.employee_id%type) return number;

    end;

    -----------------------------------------------------------------------------------

    --------------

    create or replace package body emp_operations

    is

    procedure hire_employee is

    begin

    insert into virtusa_employees(employee_id,first_name,last_name,project_id)

    values(904,'neerav','thacker',805);

    end hire_employee;

    procedure fire_employee(empid virtusa_employees.employee_id%type)

    is

    begin

    delete from virtusa_employees where employee_id=empid;

    exception

  • 8/14/2019 29-10-2013(plsql functions,packages,triggers).docx

    5/21

    when no_data_found then

    raise_application_error(-20409,'Employee doesnot exist!');

    end fire_employee;

    function get_totalsalary(empid employees.employee_id%type) return number IS

    sal number;

    com number;

    no_commission exception;

    begin

    select salary,commission_pct into sal,com from employees where employee_id=empid;

    if com is null then

    RAISE no_commission;

    end if;

    return(sal+com);

    exception

    when no_commission then

    raise_application_error(-20401,'commission not found');

    end get_totalsalary;

    end;

    --exceution

    select emp_operations.get_totalsalary(&empid) from employees;

  • 8/14/2019 29-10-2013(plsql functions,packages,triggers).docx

    6/21

    ===================================================================================

    ================================

    WRITE A PACKAGED PROCEDURE TO UPDATE THE COMMISSION OF THOSE EMPLOYEES

    WHO DONOT HAVE COMMISSION .

    IF SALARY < 10K,COMMISSION % IS 25%

    IF SALARY 25K, COMMISION IS 12%

    create or replace package salary_operations

    as

    procedure salary_increment;

    end;

    create or replace package body salary_operations

    is

    procedure salary_increment is

    cursor salary_list

    is

    select * from employees where commission_pct is null;

    emp employees%rowtype;

    begin

    for emp in salary_list

    loop

  • 8/14/2019 29-10-2013(plsql functions,packages,triggers).docx

    7/21

    if emp.salary

  • 8/14/2019 29-10-2013(plsql functions,packages,triggers).docx

    8/21

    create or replace package salary_sal40

    as

    procedure increment_s40;

    end;

    create or replace package body salary_sal40

    is

    procedure increment_s40 is

    cursor salary_list

    is

    select * from employees where department_id=40;

    emp employees%rowtype;

    begin

    for emp in salary_list

    loop

    update employees

    set salary=salary+(0.1*salary);

    end loop;

    end increment_s40;

    end;

    /

    begin

  • 8/14/2019 29-10-2013(plsql functions,packages,triggers).docx

    9/21

    dbms_output.put_line('new salary is:='||emp.salary);

    end;

    ===================================================================================

    ==========================================

    TRIGGERS

    ===================================================================================

    ==========================================

    What is a Trigger?

    A trigger is a pl/sql block structure which is fired when a DML statements like Insert, Delete,

    Update is executed on a database table. A trigger is triggered automatically when an associated

    DML statement is executed.

    Syntax of Triggers

    Syntax for Creating a Trigger:

    CREATE [OR REPLACE ] TRIGGER trigger_name

    {BEFORE | AFTER | INSTEAD OF }

    {INSERT [OR] | UPDATE [OR] | DELETE} update[of[some specific fields]]

  • 8/14/2019 29-10-2013(plsql functions,packages,triggers).docx

    10/21

    [OF col_name]

    ON table_name

    [REFERENCING OLD AS o NEW AS n]

    [FOR EACH ROW]

    WHEN (condition)

    BEGIN

    --- sql statements

    END;

    1. CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a trigger with the given

    name or overwrites an existing trigger with the same name.

    2. {BEFORE | AFTER | INSTEAD OF } - This clause indicates at what time should the trigger getfired. i.e for example: before or after updating a table. INSTEAD OF is used to create a trigger on a

    view. before and after cannot be used to create a trigger on a view.

    3. {INSERT [OR] | UPDATE [OR] | DELETE} - This clause determines the triggering event. More

    than one triggering events can be used together separated by OR keyword. The trigger gets fired at

  • 8/14/2019 29-10-2013(plsql functions,packages,triggers).docx

    11/21

    all the specified triggering event.

    4. [OF col_name] - This clause is used with update triggers. This clause is used when you want to

    trigger an event only when a specific column is updated.

    5. CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a trigger with the given

    name or overwrites an existing trigger with the same name.

    6. [ON table_name] - This clause identifies the name of the table or view to which the trigger is

    associated.

    7. [REFERENCING OLD AS o NEW AS n] - This clause is used to reference the old and new

    values of the data being changed. By default, you reference the values as :old.column_name

    or :new.column_name. The reference names can also be changed from old (or new) to any other

    user-defined name. You cannot reference old values when inserting a record, or new values when

    deleting a record, because they do not exist.

    8. [FOR EACH ROW] - This clause is used to determine whether a trigger must fire when each row

    gets affected ( i.e. a Row Level Trigger) or just once when the entire sql statement is

    executed(i.e.statement level Trigger).

    9. WHEN (condition) - This clause is valid only for row level triggers. The trigger is fired only for

    rows that satisfy the condition specified.

    --------------------------

    For Example: The price of a product changes constantly. It is important to maintain the history of

    the prices of the products.

    We can create a trigger to update the 'product_price_history' table when the price of the product is

    updated in the 'product' table.

  • 8/14/2019 29-10-2013(plsql functions,packages,triggers).docx

    12/21

    1) Create the 'product' table and 'product_price_history' table

    CREATE TABLE product_price_history

    (product_id number(5),

    product_name varchar2(32),

    supplier_name varchar2(32),

    unit_price number(7,2) );

    CREATE TABLE product

    (product_id number(5),

    product_name varchar2(32),

    supplier_name varchar2(32),

    unit_price number(7,2) );

  • 8/14/2019 29-10-2013(plsql functions,packages,triggers).docx

    13/21

    2) Create the price_history_trigger and execute it.

    CREATE or REPLACE TRIGGER price_history_trigger

    BEFORE UPDATE OF unit_price

    ON product

    FOR EACH ROW

    BEGIN

    INSERT INTO product_price_history

    VALUES

    (:old.product_id,

    :old.product_name,

    :old.supplier_name,

    :old.unit_price);

  • 8/14/2019 29-10-2013(plsql functions,packages,triggers).docx

    14/21

    END;

    /

    3) Lets update the price of a product.

    UPDATE PRODUCT SET unit_price = 800 WHERE product_id = 100

    Once the above update query is executed, the trigger fires and updates the

    'product_price_history' table.

    4)If you ROLLBACK the transaction before committing to the database, the data inserted to

    the table is also rolled back.

    -----------------------------------------------------------------------------------

    -------------------------------------------

    create table temp_employee as select * from employees;

    CREATE TABLE Emp_log8888

    (

    Emp_id NUMBER,

    Log_date DATE,

    New_salary NUMBER,

    Action VARCHAR2(20)

    );

    CREATE TABLE DILEEP AS SELECT * FROM EMPLOYEES;

  • 8/14/2019 29-10-2013(plsql functions,packages,triggers).docx

    15/21

    SELECT * FROM DILEEP;

    CREATE OR REPLACE TRIGGER Log_salary_increase12

    AFTER UPDATE ON temp_employee

    FOR EACH ROW

    WHEN (NEW.Salary > 1000)

    BEGIN

    INSERT INTO Emp_log8888(Emp_id, Log_date, New_salary, Action) VALUES (:NEW.Employee_id,

    SYSDATE, :NEW.salary, 'UPDATED SALARY');

    END;

    update temp_employee

    set salary=salary+1000.0

    where department_id=20;

    create or replace trigger change_comm

    after insert or delete or update of commission_pct on temp_employees

    for each row

    when(new.commission_pct>1000)

    begin

    insert into emp_log8888(Emp_id, Log_date, New_salary, Action) values(:NEW.Employee_id,

    SYSDATE, :NEW.commission_pct, 'new commission');

    end;

  • 8/14/2019 29-10-2013(plsql functions,packages,triggers).docx

    16/21

    update temp_employees

    set commission_pct=commission_pct+1000 where department_id=&deptid;

    -----------------------------------------------------------------------------------

    -------

    --create table and audit table

    CREATE TABLE myTable (Name VARCHAR(50) PRIMARY KEY, PhoneNo VARCHAR(15));

    CREATE TABLE myTableAudit

    (

    Operation VARCHAR(10),

    RecordedOn DATE DEFAULT SysDate,

    OldName VARCHAR(50),

    NewName VARCHAR(50),

    OldPhone VARCHAR(15),

    NewPhone VARCHAR(15)

    );

  • 8/14/2019 29-10-2013(plsql functions,packages,triggers).docx

    17/21

    CREATE OR REPLACE TRIGGER myTableAuditTrigger

    AFTER INSERT OR DELETE OR UPDATE ON myTable

    FOR EACH ROW

    BEGIN

    IF INSERTING THEN

    INSERT INTO myTableAudit (Operation, NewName, NewPhone)VALUES ('Insert

    ', :NEW.Name, :NEW.PhoneNo);

    end if;

    IF DELETING THEN

    INSERT INTO myTableAudit (Operation, OldName, OldPhone)VALUES ('Delete', :OLD.Name, :OLD.PhoneNo);

    end if;

    if UPDATING THEN

    INSERT INTO myTableAudit (Operation, OldName, OldPhone, NewName, NewPhone)VALUES

    ('Update ', :OLD.Name, :OLD.PhoneNo, :NEW.Name, :NEW.PhoneNo);

    END IF;

    END;

    insert into mytable values('DILEEP',9030614858);

  • 8/14/2019 29-10-2013(plsql functions,packages,triggers).docx

    18/21

  • 8/14/2019 29-10-2013(plsql functions,packages,triggers).docx

    19/21

  • 8/14/2019 29-10-2013(plsql functions,packages,triggers).docx

    20/21

  • 8/14/2019 29-10-2013(plsql functions,packages,triggers).docx

    21/21