Beruflich Dokumente
Kultur Dokumente
All related function and procedure can be grouped together in a single unit called packages.
2.
3.
All function and procedure within a package can share variable amoung them.
4.
5.
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".
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".
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.
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".
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
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:
PL/SQL warning or error is called an exception. PL/SQL allow you to create your own user define exception. User-Defined Exception Syntax:
BEGIN <SQL Statement> IF <condition> THEN RAISE <Exception Name> END IF; EXCEPTION WHEN <Enception Name> THEN <User Defined Action to be Taken> END;
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
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;
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
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.
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:
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.
[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');
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:
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.
[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.
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.
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
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');
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
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
EMP_NO 1 Jay
EMP_NAME
EMP_SALARY
2 3 4
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:
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.
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.