Sie sind auf Seite 1von 15

1.

All related function and procedure can be grouped together in a single unit called packages.

2.

Package is reliable to granting privileges.

3.

All function and procedure within a package can share variable amoung them.

4.

Package enables to perform "overloading" of functions and procedures.

5.

Package improve performance by loading the multiple object into memory

at once, therefore, subsequent calls to related program do not required physical I/O.

6. 7. 8.

Package is reduce the traffic because all block execute all at once It contains specification and body Specification: It contain the list of various fuctions procedure names which will be a part of the package.

9.

Body: This contains the actual PL/SQL statement code implementing the logics of functions and procedures declared in "specification".

Defining Package Specification

CREATE or REPLACE PACKAGE <Package Name> {is,as} PROCEDURE [Schema..] <ProcedureName> (<argument> {IN,OUT,IN OUT} <Data Type>,..); FUNCTION [Schema..] <Function Name> (<argument> IN <Data Type>,..) RETURN <Data Type>);
Body: This contains the actual PL/SQL statement code implementing the logics of functions and procedures declared in "specification".

Creating Package Body

CREATE or REPLACE PACKAGE BODY <Package Name> {is,as} PROCEDURE [Schema..] <ProcedureName> (<argument> {IN,OUT,IN OUT} <Data Type>,..) {IS, AS} <variable> declarations; <constant> declarations; BEGIN

<PL/SQL subprogram body> EXCEPTION <PL/SQL Exception block> END; FUNCTION [Schema..] <FunctionName>(<argument> IN <Data Type>,..) return <Data Type> {IS,AS} <variable> declarations; <constant> declarations; BEGIN <PL/SQL subprogram body> EXCEPTION <PL/SQL Exception block> END; END;
Specification: It contain the list of various fuctions procedure names which will be a part of the package.

Package Specification Code:

CREATE or REPLACE PACKAGE pkg1 {is,as} PROCEDURE pro1 (no in number, name out varchar2); FUNCTION fun1 (no in number) RETURN varchar2; END; /
Body: This contains the actual PL/SQL statement code implementing the logics of functions and procedures declared in "specification".

Package Body Code

CREATE or REPLACE PACKAGE BODY pkg1 is PROCEDURE pro1(no in number,name our varchar2) is BEGIN SELECT * INTO temp FROM emp1 WHERE eno = no; END; FUNCTION fun1(no in number) return varchar2 is name varchar2(20); begin select ename into name from emp1 where eno = no; return name; END; END; /
Package Block

DECLARE no number := &no; name varchar2(20);

BEGIN pkg1.pro1(no,name); dbms_output.put_line(name); name := pkg1.fun1(no); dbms_output.put_line(name); END; /

PL/SQL Errors are pe-defined and are automatically raised by Oracle whenever an error is encountered. Each error is assigned a unique number and a message. PL/SQL, a warning or error condition is called an exception. Exceptions can be internally defined (by the run-time system) or user defined. Examples of internally defined exceptions include division by zero and out of memory. Some common internal exceptions have predefined names, such as ZERO_DIVIDE and STORAGE_ERROR. The other internal exceptions can be given names. When an error occurs, an exception is raised. That is, normal execution stops and control transfers to the exception-handling part of your PL/SQL block or subprogram. Internal exceptions are raised implicitly (automatically) by the run-time system. Userdefined exceptions must be raised explicitly by RAISE statements, which can also raise predefined exceptions. To handle raised exceptions, you write separate routines called exception handlers. Built-In Exception Syntax:

EXCEPTION WHEN <Buit-in Exception> THEN <User Defined Action to be taken> SQL>edit buitin_exp DECLARE temp enum%rowtype; BEGIN SELEC * INTO temp FROM enum WHERE eno=3; EXCEPTION WHEN no_data_found THEN dbms_output.put_line('Table Does Not Data'); END; / SAVE: builtin_exp.sql
Buit-In Example Result: Buit-In Example Code:

SQL>@buitin_exp Table Doen Not Data

Buit-in Exception List

"DUP_VAL_ON_INDEX LOGIN_DENIED NO_DATA_FOUND NOT_LOGGED_ON PROGRAM_EROOR TIMEOUT_ON_RESOURCE TOO_MANY_ROWS VALUE_ERROR OTHER

PL/SQL warning or error is called an exception. PL/SQL allow you to create your own user define exception. User-Defined Exception Syntax:

DECLARE <Exection Name> EXCEPTION;

BEGIN <SQL Statement> IF <condition> THEN RAISE <Exception Name> END IF; EXCEPTION WHEN <Enception Name> THEN <User Defined Action to be Taken> END;

User-Defined Exception Program Code:

SQL>edit user_exp DECLARE myex EXCEPTION; i NUMBER; BEGIN FOR i IN (SELECT * FROM enum) LOOP IF i.eno = 3 THEN RAISE myex; END IF; END LOOP; EXCEPTION WHEN myex THEN dbms_output.put.line('EMP NO is Filled Already'); END; / SAVE: user_exp

User-Defined Exception Program Result:

SQL>@user_exp EMP NO is Filled Already


User-Named Exception Syntax:

DECLARE <Exection Name> EXCEPTION; PRAGMA EXCEPTION_INIT(Exection Name,-20015); BEGIN <SQL Statement> IF <condition> THEN RAISE <Exception Name> END IF; EXCEPTION WHEN <Enception Name> THEN <User Defined Action to be Taken> END;

User-Named Exception Program Code:

SQL>edit user-named_exp DECLARE myex EXCEPTION; PRAGMA EXCEPTION_INIT(myex,-20015);

n NUMBER := &n; BEGIN FOR i IN 1..n LOOP dbms_output.put.line(i); IF i=n THEN RAISE myex; END IF; END LOOP; EXCEPTION WHEN myex THEN dbms_output.put.line('loop is end'); END; / SAVE: user-named_exp

User-Named Exception Program Result:

SQL>@user-named_exp n number amp;n= 5 1 2 3 4 5 loop is end

What is Trigger? oracle engine allow the definition of procedure that are implicitly executed when an insert, update, delete is issued again a table from sql or thought application the trigger automatically associated DML statement is executed.

Component of Trigger

Triggering SQL statement: The SQL statement on execution of which the defined trigger code file is called Triggering SQL statement. Example INSERT, UPDATE and DELETE issue again.

Trigger Action: The PL/SQL block which gets executed when the triggering SQL statement is executed.

Trigger Restriction: We van specify under what condition the trigger should be fire.

PL/SQL Type of Triggers

Before Triggers: These triggers are fired before the triggering SQL statement (INSERT, UPDATE, DELETE) is executed. The execution of triggering SQL statement is stopped depending on the various conditions to be fulfilled in BEFORE trigger.

After Triggers: These triggers are fired after the triggering SQL statement (INSERT, UPDATE, DELETE) is executed. The triggering SQL statement is executed first followed by the code of trigger.

ROW Trigger: The triggers are fired for each and every record which is inserted or updated or deleted from a table.

Statement Trigger: The Trigger are fired for each row of DML operation being performed on a table. we can not access the column values for records being inserted, updated, deleted on the table and not individual records.

Combination Trigger:

Before Statement Trigger

Before Row Trigger

After Statement Trigger

After Row Trigger

PL/SQL Triggers Syntax Description:

CREATE or REPLACE TRIGGER trigger_name: Creates a trigger with the given name otherwise overwrites an existing trigger with the same name.

{BEFORE , AFTER }: Indicates the where should trigger get fired. BEFORE trigger execute before when statement execute before time or AFTER trigger execute after when statement execute after time.

{INSERT , UPDATE , DELETE}: Determines the performing trigger event. More than one triggering events allow can be used together separated by OR keyword.

ON Table Name: Determine the perform trigger event in selected Table.

[Referencing {old AS old, new AS new}]: Reference the old and new values of the data being changed. :old use to existing row perform and :new use to execute new row to perform. 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.

for each row: Trigger must fire when each row gets Affected (Row Level Trigger) or just once when the entire sql statement is executed(statement level Trigger).

WHEN (condition): Valid only for row level triggers. The trigger is fired only for rows that satisfy the condition specified.

CREATE or REPLACE TRIGGER <Trigger Name> <BEFORE,AFTER> {<DELETE, INSERT, UPDATE [OF COLUMN..]} ON [Scheme] <Table Name> [Referencing {old AS old, new AS new}] [for each row {WHEN Condition}] DECLARE <variable> declaration; <constant> declaration; BEGIN <PL/SQL subprogram body> EXCEPTION <PL/SQL Exception block> END; /
Inserting Trigger in convert the lowercase to uppercase

CREATE or REPLACE TRIGGER trg1 BEFORE INSERT ON emp1 for each row BEGIN :new.ename := upper(:new.ename); END; /
Delete Trigger in Restiction
Delete Trigger Code:

CREATE or REPLACE TRIGGER trg1 AFTER DELETE ON emp1 for each row BEGIN IF :old.eno = 1 THEN raise_application_error(-20015, 'Not Delete this Row');

END IF; END; /


Delete Trigger Result:

SQL>delete from emp1 where eno = 1; Error Code: 20015 Error Name: Not Delete this Row

Before Triggers: These triggers are fired before the triggering SQL statement (INSERT, UPDATE, DELETE) is executed. The execution of triggering SQL statement is stopped depending on the various conditions to be fulfilled in BEFORE trigger.

After Triggers: These triggers are fired after the triggering SQL statement (INSERT, UPDATE, DELETE) is executed. The triggering SQL statement is executed first followed by the code of trigger.

ROW Trigger: The triggers are fired for each and every record which is inserted or updated or deleted from a table.

Statement Trigger: The Trigger are fired for each row of DML operation being performed on a table. we can not access the column values for records being inserted, updated, deleted on the table and not individual records.

Combination Trigger:

Before Statement Trigger

Before Row Trigger

After Statement Trigger

After Row Trigger

Syntax Description:

CREATE or REPLACE TRIGGER trigger_name: Creates a trigger with the given name otherwise overwrites an existing trigger with the same name.

{BEFORE , AFTER }: Indicates the where should trigger get fired. BEFORE trigger execute before when statement execute before time or AFTER trigger execute after when statement execute after time.

{INSERT , UPDATE , DELETE}: Determines the performing trigger event. More than one triggering events allow can be used together separated by OR keyword.

ON Table Name: Determine the perform trigger event in selected Table.

[Referencing {old AS old, new AS new}]: Reference the old and new values of the data being changed. :old use to existing row perform and :new use to execute new row to perform. 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.

for each row: Trigger must fire when each row gets Affected (Row Level Trigger) or just once when the entire sql statement is executed(statement level Trigger).

WHEN (condition): Valid only for row level triggers. The trigger is fired only for rows that satisfy the condition specified.

CREATE or REPLACE TRIGGER <Trigger Name> <BEFORE,AFTER> {<DELETE, INSERT, UPDATE [OF COLUMN..]} ON [Scheme] <Table Name> [Referencing {old AS old, new AS new}] [for each row {WHEN Condition}] DECLARE <variable> declaration; <constant> declaration; BEGIN <PL/SQL subprogram body> EXCEPTION <PL/SQL Exception block> END; /
Inserting Trigger in convert the lowercase to uppercase

CREATE or REPLACE TRIGGER trg1 BEFORE INSERT ON emp1 for each row BEGIN :new.ename := upper(:new.ename);

END; /
Delete Trigger in Restiction
Delete Trigger Code:

CREATE or REPLACE TRIGGER trg1 AFTER DELETE ON emp1 for each row BEGIN IF :old.eno = 1 THEN raise_application_error(-20015, 'Not Delete this Row'); END IF; END; /
Delete Trigger Result:

SQL>delete from emp1 where eno = 1; Error Code: 20015 Error Name: Not Delete this Row

What is Cursor? Cursor is the work area which Oracle reserves for internal processing of SQL statements. This work area is private for oracles reserved are called cursor.

How to Use Cursor


In PL/SQL block SELECT statement can not return more than one row at a time. So Cursor use to some group of rows (more than one row) for implementing certain logic to all the records of group are show.

Classification of CURSORS
Cursors can be classified as:

Implicit Cursor or Internal Cursor - Manage for Oracle itself or Internal Process itself. Explicit Cursor or User-defined Cursor - Manage for User/Programmer or External Processing.

Implicit Cursor
Oracle uses implicit cursors for its internal processing. Even if we execute a SELECT statement Oracle reserves a private SQL area in memory called cursor.

Explicit Cursor
Explicit Cursor which declared by user are called Explicit Cursor. The user has to declare the cursor, open cursor to reserve the memory are and populate data, fetch the records from the active data set one at a time, apply logic and last close the cursor. Step for Using Explicit Cursor 1. 2. 3. 4. 5. Declare Cursor Open Cursor Loop Fetch Record into Cursor Exit Loop

6. 7.

Close Cursor Oracle uses implicit cursors for its internal processing. Even if we execute a SELECT statementOracle reserves a private SQL area in memory called cursor.

8.

Implicit Cursor variables

9.
Cursor Attribute %ISOPEN Cursor Variable SQL%ISOPEN Description Oracle engine automatically open the cursor If cursor open return true otherwise return false. If selected return one or more than one row INSERT, UPDATE, DELETE operation affect If affect return true otherwise return false. If selected return one or more than one row INSERT, UPDATE, DELETE operation not affect If not affect the row return true otherwise return false. Return the number of rows affected by an insert, update, delete or select statement.

%FOUND

SQL%FOUND

%NOTFOUND

SQL%NOTFOUND

%ROWCOUNT

SQL%ROWCOUNT

10. Implicit Cursor Example


11. following one emp_information table:

12.
EMP_NO 1 2 3 4 Jay Ajay Bhavesh Jigar EMP_NAME EMP_DEPT Web Developer Program Developer Program Developer Web Developer 45k 38k 34k 42k EMP_SALARY

13. We update the employee 'bhavesh' department is update to 'web developer'. 14. Example Code:

15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32.

SQL>set serveroutput on SQL>edit implicit_cursor BEGIN UPDATE emp_information SET emp_dept='Web Developer' WHERE emp_name='bhavesh'; IF SQL%FOUND THEN dbms_output.put_line('Updated - If Found'); END IF; IF SQL%NOTFOUND THEN dbms_output.put_line('NOT Updated - If NOT Found'); END IF; IF SQL%ROWCOUNT>0 THEN dbms_output.put_line(SQL%ROWCOUNT||' Rows Updated'); ELSE dbms_output.put_line('NO Rows Updated Found');

33. END; 34. / 35. SAVE: implicit_cursor.sql


36. Example Result:

37. SQL>@implicit_cursor Updated - If Found 1 Rows Updated PL/SQL procedure successfully operation.
Explicit Cursor which declared by user are called Explicit Cursor. User is declare and open the cursor to reserve the memory and fetch the populated data from the active data set one at a time, and last close the cursor. Step for Using Explicit Cursor
1. 2. 3. 4. 5. 6. Declare Cursor Open Cursor Loop Fetch Record into Cursor Exit Loop Close Cursor

Explicit Cursor variables

Cursor Attribute %ISOPEN

Cursor Variable c%ISOPEN

Description Oracle engine automatically open the cursor If cursor open return true otherwise return false. If selected return one or more than one row INSERT, UPDATE, DELETE operation affect If affect return true otherwise return false. If selected return one or more than one row INSERT, UPDATE, DELETE operation not affect If not affect the row return true otherwise return false. Return the number of rows affected by an insert, update, delete or select statement.

%FOUND

c%FOUND

%NOTFOUND

c%NOTFOUND

%ROWCOUNT

c%ROWCOUNT

Step for Using Explicit Cursor:


1. 2. 3. 4. 5. 6. Declare Cursor Open Cursor Loop Fetch Record into Cursor Exit Loop Close Cursor

Explicit Cursor Example


following one emp_information table:

EMP_NO 1 Jay

EMP_NAME

EMP_DEPT Web Developer 45k

EMP_SALARY

2 3 4

Ajay Bhavesh Jigar

Program Developer Program Developer Web Developer

38k 34k 42k

We update the employee 'bhavesh' department is update to 'web developer'. Example Code:

SQL>set serveroutput on SQL>edit explicit_cursor DECLARE cursor c is select * from emp_information where emp_name='bhavesh'; tmp emp_information%rowtype; BEGIN OPEN c; Loop exit when c%NOTFOUND; FETCH c into temp; update emp_information set tmp.emp_dept='Web Developer' where tmp.emp_name='bhavesh'; END Loop; IF c%ROWCOUNT>0 THEN dbms_output.put_line(SQL%ROWCOUNT||' Rows Updated'); ELSE dbms_output.put_line('NO Rows Updated Found'); END IF; CLOSE c; END; / SAVE: explicit_cursor.sql
Example Result:

SQL>@explicit_cursor 1 Rows Updated PL/SQL procedure successfully completed.


PL/SQL cursor for loop is a one of the advantage to the loop continued till row not found. Cursor For Loop is use to procedure by letting PL/SQL do most of the things for us. You have to coding by using Cursor For Loop instead of the OPEN, FETCH, and CLOSE statements.

Explicit Cursor FOR LOOP Example


following one emp_information table:

EMP_NO 1 2 3 4 Jay Ajay Bhavesh Jigar

EMP_NAME

EMP_DEPT Web Developer Program Developer Program Developer Web Developer 45k 38k 34k 42k

EMP_SALARY

display first two emp details in emp number wise. Example Code:

SQL>set serveroutput on

SQL>edit cursor_for_loop DECLARE cursor c is select * from emp_information where emp_no <=2; tmp emp_information%rowtype; BEGIN OPEN c; FOR tmp IN c LOOP FETCH c into tmp; dbms_output.put_line('EMP_No: '||tmp.emp_no); dbms_output.put_line('EMP_Name: '||tmp.emp_name); dbms_output.put_line('EMP_Dept: '||tmp.emp_dept); dbms_output.put_line('EMP_Salary:'||tmp.emp_salary); END Loop; CLOSE c; END; / SAVE: cursor_for_loop.sql
Example Result:

SQL>@cursor_for_loop EMP_No: 1 EMP_Name: Jay EMP_Dept: Web Developer EMP_Salary:45k EMP_No: 2 EMP_Name: Ajay EMP_Dept: Program Developer EMP_Salary:38k PL/SQL procedure successfully completed.
PL/SQL Parameterized cursor pass the parameters into a cursor and use them in to query. Default values is assigned to the Cursor parameters. and scope of the parameters is locally.

Parameterized Explicit Cursor Example


following one emp_information table:

EMP_NO 1 2 3 4 Example Code: Jay Ajay Bhavesh Jigar

EMP_NAME

EMP_DEPT Web Developer Program Developer Program Developer Web Developer 45k 38k 34k 42k

EMP_SALARY

SQL>set serveroutput on SQL>edit parameter_cursor_demo DECLARE cursor c(no number) is select * from emp_information where emp_no = no; tmp emp_information%rowtype; BEGIN OPEN c(4); FOR tmp IN c(4) LOOP

dbms_output.put_line('EMP_No: '||tmp.emp_no); dbms_output.put_line('EMP_Name: '||tmp.emp_name); dbms_output.put_line('EMP_Dept: '||tmp.emp_dept); dbms_output.put_line('EMP_Salary:'||tmp.emp_salary); END Loop; CLOSE c; END; / SAVE: parameter_cursor_demo.sql
Example Result:

SQL>@parameter_cursor_demo EMP_No: 4 EMP_Name: Jigar EMP_Dept: Web Developer EMP_Salary:42k PL/SQL procedure successfully completed.

Das könnte Ihnen auch gefallen