Академический Документы
Профессиональный Документы
Культура Документы
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.
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
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 ...
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;
10
6/22/2011
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
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
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 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
21
6/22/2011
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
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
Contd
23
6/22/2011
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