Вы находитесь на странице: 1из 24

6/22/2011

Oracle

PL/SQL PART II

Topics
Subprograms Procedures Functions Stored Procedures Stored Functions

6/22/2011

Subprograms
Subprograms are named PL/SQL blocks that can take parameters and be invoked.

PL/SQL has two types of subprograms called procedures and functions.


Generally, you use a procedure to perform an action and a function to compute a value.

Procedures
Procedures are subprograms, that allow you to decompose your program into logical units. The structure is as below Header declaration section types, cursors, constants, variables, exceptions execution section exception section Accept and return parameter values

6/22/2011

Procedures
PROCEDURE name [(parameter,parameter...)] IS [declaration statements] BEGIN executable statements; [ EXCEPTION exception handler statements; ] END; Procedure Body Procedure Spec

Procedure Header
Parameter consists of Parameter Name [IN|OUT] datatype [:= |DEFAULT value ] Example of header: PROCEDURE testProc( empNo IN int :=0, grade OUT) IS BEGIN ...

6/22/2011

Declaration
PROCEDURE account_debit ( acct_id CHAR(5) ) IS ... -- illegal constrain for the datatype of a parameter is NOT allowed

Alternate way: Declare v_num number(5); Procedure sal_increment (emp_no v_num%TYPE) is -----

PROCEDURE raise_salary (emp_id INTEGER, amount REAL) IS current_salary REAL; salary_missing EXCEPTION; Procedures BEGIN SELECT sal INTO current_salary FROM emp WHERE empno = emp_id; IF current_salary IS NULL THEN RAISE salary_missing; ELSE UPDATE emp SET sal = sal + amount WHERE empno = emp_id; END IF; EXCEPTION WHEN NO_DATA_FOUND THEN INSERT INTO emp_audit VALUES (emp_id, 'No such number'); WHEN salary_missing THEN INSERT INTO emp_audit VALUES (emp_id, 'Salary is null'); END raise_salary; * Formal Parameters

6/22/2011

PROCEDURE debit_account (acct_id INTEGER, amount REAL) IS old_balance REAL; new_balance REAL; overdrawn EXCEPTION; BEGIN SELECT bal INTO old_balance FROM accts WHERE acct_no = acct_id; new_balance := old_balance - amount; IF new_balance < 0 THEN RAISE overdrawn; ELSE UPDATE accts SET bal = new_balance WHERE acct_no = acct_id;

Procedures

END IF;
EXCEPTION WHEN overdrawn THEN ... END debit_account;

Calling a Procedure
DECLARE v_emp_id NUMBER := 100 ; v_amount REAL := 10000 ; PROCEDURE raise_salary (emp_id INTEGER, amount REAL) IS current_salary REAL; salary_missing EXCEPTION; BEGIN ----END raise_salary BEGIN ... raise_salary(v_emp_id, v_amount); EXCEPTION * Actual Parameters --END

procedure

6/22/2011

Procedures-Some Points

Temporal Exist only during execution of the block Different from Stored Procedures which are

permanently available

Functions
A function is also a subprogram which can be used in expressions Functions also have header,declaration,executable and exception sections The only difference is in the header section A function has an additional return clause in the header

6/22/2011

Functions
FUNCTION name(param1,param2,...) RETURN data-type IS

Spec

[declarations] BEGIN [executable-statements] EXCEPTION [exception handlers] END;

Body

Function

FUNCTION sal_ok (salary REAL, title REAL) RETURN BOOLEAN IS min_sal REAL; max_sal REAL; BEGIN SELECT losal, hisal INTO min_sal, max_sal FROM sals WHERE job = title; RETURN (salary >= min_sal) AND (salary <= max_sal); END sal_ok;

6/22/2011

Calling a function
DECLARE new_sal REAL; new_title VARCHAR2(15); BEGIN ... IF sal_ok(new_sal, new_title) THEN ...

Note: Attach the function declaration also

IN Mode
IN Allows you to pass values to the subprogram being called. The IN parameters function like constants Can be initialised to a default value (in the spec) Value cannot be assigned in the body

6/22/2011

OUT Mode
OUT Let you return value to the caller of the subprogram(or to the calling PL/SQL block) Inside the ( body of the )subprogram, an OUT formal parameter acts like another variable So the value of the formal out parameter can be changed The actual parameter that corresponds to an OUT formal parameter must be a variable; it cannot be a constant or an expression. An OUT actual parameter can have a value before the subprogram is called

IN - OUT Mode
IN OUT An IN OUT parameter lets you pass initial values to the subprogram being called and return updated values to the caller Inside the subprogram, an IN OUT parameter acts like an initialized variable it can be assigned a value its value can be assigned to another variable

6/22/2011

PROCEDURE calc_bonus (emp_id IN INTEGER, bonus OUT REAL) IS IN / OUT hire_date DATE; bonus_missing EXCEPTION; BEGIN SELECT sal * 0.10, hiredate INTO bonus, hire_date FROM emp WHERE empno = emp_id; IF bonus IS NULL THEN RAISE bonus_missing; END IF; IF MONTHS_BETWEEN(SYSDATE, hire_date) > 60 THEN bonus := bonus + 500; END IF; ... EXCEPTION Functiondemo WHEN bonus_missing THEN ... How to call ? END calc_bonus;

Stored Procedures & Functions


Stored procedures/functions can be accessed from multiple applications/programs The Stored procedures and Stored functions are stored as part of the database The procedures and functions you create will be stored as part of your schema. These cannot be accessed by another user unless you explicitly grant execute permission to him/her

10

6/22/2011

Advantages of stored Procedures/Functions


Sharability Better Performance Memory savings Application integrity Tighter security

Stored Procedure
CREATE [OR REPLACE ] PROCEDURE procedurename(parameter1, parameter2,...) IS --- (or AS) [declarations] BEGIN [executable stmts] EXCEPTION [exception handlers] END;

Storedprocedure

call

11

6/22/2011

Compiling a Stored Procedure

Code the procedure in a text file Run the file at the SQL > Prompt If compilation errors obtained, type Show Errors at the SQL> Prompt Correct errors and run the file again EXEC Procedurename(Parameters)

Stored Functions
CREATE [OR REPLACE ] FUNCTION functionName(parameter1, parameter2,...) RETURN function data-type IS [declarations] BEGIN [executable stmts] EXCEPTION [exception handlers] END;

Storedfunction

call

12

6/22/2011

Packages

Group of related PL/SQL procedures and functions Has Package specification and Package body Can be application specific/group common procedures and functions that provide a common service

Package Specification
Create or replace demoPack IS

type empRecType IS RECORD (eNo Number, eName varchar2(12)); cursor empCur return empRecType; procedure Get_Max_Salary( eGrade Number, sal OUT Number); function Get_New_EmpNo( eNo Number, eName varchar2, grade number,salary number) return Number;
end demoPack;

13

6/22/2011

Package Body
Create or replace package body demoPack IS cursor empCur return empRecType IS select empno, salary from employee where grade >=3 ; procedure get_max_salary(egrade number,sal OUT number ) is begin [procedure body] exception [handlers] end; Contd

Package Body(contd)
function get_new_empno(eno number,ename varchar2,egrade number,esalary number ) return number is begin [function body] exception [handlers] end;

14

6/22/2011

Invoking a Procedure/Function in a Package


DECLARE BEGIN demoPack.Get_Max_Salary(egrade, max_sal); newNo := demoPack.Get_New_EmpNo(num,nm,egrade,sal); EXCEPTION END;

Database Triggers
A stored PL/SQL procedure that is implicitly fired when an INSERT,UPDATE or DELETE statement is issued against an associated table Constrain what transactions can do A declarative integrity constraint is a statement about the database that is always true

15

6/22/2011

Advantages of DB triggers
Verify data integrity Implement delete cascades Log events transparently Enforce complex business rules Initiate business processes Derive column values automatically Enforce complex security rules

Database Triggers

Enforce transitional constraints, at the time when data changes Cannot contain COMMIT/ROLLBACK/SAVEPOINT/DDL statements

16

6/22/2011

Creating a Trigger
CREATE [OR REPLACE] TRIGGER trigger-name [BEFORE | AFTER] {DELETE|INSERT|UPDATE [OF column [, column]} [OR {DELETE|INSERT|UPDATE [OF column [,column]}]... ON table [REFERENCING {OLD [AS] old | NEW [AS] new}] [FOR EACH ROW] [WHEN (condition)]

PL/SQL Block

Parts of a Trigger

A trigger has three basic parts: a triggering event or statement a trigger restriction a trigger action

17

6/22/2011

Database Triggers

Triggering event or statement SQL statement that causes a trigger to be defined. INSERT , UPDATE OR DELETE statement for a specific table

Database Triggers

Trigger restriction specifies a boolean expression that must be true for the trigger to fire. Specified using WHEN clause

18

6/22/2011

Database Triggers

Trigger action

not executed if trigger restriction evaluates to false Procedure that contains the sql statements executed when the triggering statement is issued and the trigger restriction evaluates to true

Types of Triggers
Row Level Triggers

FOR EACH ROW Fired every time the table is affected by the SQL statement Can access Old and New column values processed by the SQL statement

19

6/22/2011

Row Level Triggers(contd)

Row Level Triggers Access column values as follows :new.column-name [only for INSERT/UPDATE] :old.column-name [for INSERT/UPDATE/DELETE]

Types of Triggers(contd)

Statement Level Triggers Fired only once on behalf of triggering statement irrespective of how many rows in the table are affected Cannot access column values Used to process information about the SQL statement that caused the trigger to fire

20

6/22/2011

Triggers Timing

When defining a trigger, timing of trigger can be specified BEFORE INSERT AFTER INSERT BEFORE UPDATE AFTER UPDATE BEFORE DELETE AFTER DELETE

Database Triggers - Example 1


CREATE TRIGGER reordertrig AFTER UPDATE OF parts_on_hand ON inventory FOR EACH ROW WHEN(:new.parts_on_hand < :new.reorder_point)

21

6/22/2011

Database Triggers - Example 1


DECLARE number x; BEGIN SELECT count(*) INTO x FROM pending_orders WHERE part_no=:new.part_no; IF x=0 then INSERT INTO pending_orders VALUES(:new.part_no, :new.reorder, quantity, sysdate) END IF; END; Trigger1 Trigger1fire

Triggers - Example 2
create trigger prochange before insert or delete or update on products declare dummy integer; nosundays exception; noholidays exception; noworkhours exception;

Contd

22

6/22/2011

Triggers - Example 2 contd.

begin if (to_char(sysdate,day) = SUNDAY then raise nosundays; end if; select count(*) into dummy from companyhols where day = sysdate; if dummy > 0 then raise noholidays; end if; Contd

Triggers - Example 2 contd.


if (to_char(sysdate,HH24) < 8 or to_char(sysdate,HH24) > 18) then raise noworkhours; end if; exception when nosundays then raise_application_error(-20344, Cannot change on sundays);

Contd

23

6/22/2011

Triggers - Example 2 contd.


when noholidays then raise_application_error(-20345, Cannot change on holidays); when noworkhours then raise_application_error(-20346, Cannot change beyond working hours); end;

RAISE_APPLICATION_ERROR
Procedure in DBMS_Standard package Return application-specific error messages to caller Reserved error code range: -20000 to -20999 Passes back error code and the associated error message

24

Вам также может понравиться