Oracle PL SQL
Oracle PL SQL
Introduction:
PL/SQL provides programming facility to the users in
Oracle to implement complex business logic.
Objective:
After completing this module, you will be able to,
1 .PL/SQL Features
2. PL/SQL Block Structures
3. Identifiers
4. Variables
5. Data Types
2.0 PL/SQL Fundamentals : Overview
6. Composite Types
7. PL/SQL Statements
8. PL/SQL statements
9. Oracle Supplied Packages
10. Expressions and Operators
11. Conditional and Loop Constructs
PL/SQL Features
Features of PL/SQL
SQL Statement
SQL> SELECT sysdate FROM DUAL;
PL/SQL Statement
DECLARE
l_date DATE;
BEGIN
SELECT sysdate into l_date from dual;
END;
PL/SQL Features
Need of PL/SQL
Procedural Language/Structured Query Language
is an extension to SQL
PL/SQL Architecture
PL/SQL Features
PL/SQL Architecture
PL/SQL Block Structure
Syntax
DECLARE
/*Declarative Section - PL/SQL variables,
cursors and types */
BEGIN
/* Executable section - procedural and SQL statements */
EXCEPTION
/* Exception handling section - error handling statements */
END;
PL/SQL Block Structure
Anonymous Blocks
Declare
/* variables*/
Begin
/*SQL statements */
Exception
/* Error handling */
End;
PL/SQL Block Structure
Named Block
Replace DECLARE keyword with CREATE OR REPLACE
Example
Create or Replace Procedure Validate_Date AS
/* variables*/
Begin
/*SQL statements */
Exception
/* Error handling */
End Validate_Date;
Identifiers
Variable Declarations
Declaration Syntax
variable_name type [CONSTANT][NOT NULL][:=value]
Example
DECLARE
v_Description VARCHAR2(50);
v_NumberSeats NUMBER := 45;
v_Counter BINARY_INTEGER DEFAULT 0;
Variables
Variable Scope
DECLARE
v_number NUMBER(3,2);
BEGIN
…
Scope of DECLARE
v_number v_Character VARCHAR2(10);
Scope of
BEGIN
v_Character
…
END;
END;
Data Types
PL/SQL Record
PL/SQL Record
Following declarative section can be replaced by PL/SQL
Record
Example
DECLARE
v_StudentID NUMBER(5);
v_FirstName VARCHAR2(20);
v_LastName VARCHAR2(20);
DECLARE
TYPE t_studentRec IS RECORD (
StudentID NUMBER(5),
FirstName VARCHAR2(20),
LastName VARCHAR2(20));
v_studentInfo t_StudentRec;
Composite Type
PL/SQL Record
PL/SQL Table
Example
TYPE string_name IS
TABLE OF VARCHAR2(30)
INDEXED BY BINARY_INTEGER;
employee_name_table string_name;
Composite Type
PL/SQL Table
The number of rows in a Pl/SQL table can
increase dynamically
Statements in PL/SQL
IF-THEN-ELSE
LOOPS
WHILE LOOPS
FOR LOOPS
Conditional and Loop Constructs
IF-THEN-ELSE
Syntax
IF boolean_statements1 THEN
sequence_of_statements1;
ELSIF boolean_statements2 THEN
sequence_of_statements2;
ELSE
sequence_of_statements3;
END IF;
Conditional and Loop Constructs
Example
DECLARE
v_NumberSeats rooms.number_seats%TYPE;
v_Comment VARCHAR2(35);
BEGIN
/* Retrieve the number of seats in the room
identified by ID 99999.
Store the result in v_NumberSeats. */
SELECT number_seats
INTO v_NumberSeats
FROM rooms
WHERE room_id = 99999;
Conditional and Loop Constructs
LOOPS
Syntax
LOOP
sequence_of_statements;
END LOOP;
sequence of statements will be executed infinitely,since the loop has no
stopping condition. So, to break the loop the syntax is:
EXIT [WHEN condition];
Conditional and Loop Constructs
WHILE Loop
Syntax
WHILE condition LOOP
sequence_of_statements;
END LOOP;
Conditional and Loop Constructs
FOR Loop
Syntax
FOR loop_counter IN [REVERSE] low_bound .. high_bound LOOP
sequence_of_statements;
END LOOP;
Example
BEGIN
FOR v_counter IN 1 .. 50 LOOP
INSERT INTO temp_table values (v_counter,’Loop Index’);
END LOOP;
END;
PL/SQL Fundamentals : Summary
A table is like a ‘C’ array. A Table can have only one primary
key(BINARY_INTEGER) and a column
: Quiz
Introduction:
A SQL cursor is a private Oracle SQL working area. The implicit cursor
is used by Oracle server to test and parse the SQL statements and the
explicit cursors are declared by the programmers. Oracle exceptions
handlers are used to trap runtime errors.
Objective:
After completing this module, you will be able to,
1 .Understand Cursors
2. Open Cursors
3. Fetch Cursor
4. Close Cursor
5. Cursor Attributes
3.0 Cursors and Exceptions : Overview
6. Examples of Cursors
7. Understand Exceptions
8. Pre-defined Exception
9 User-defined Exceptions
10. PRAGMA EXCEPTION_INIT
11. RAISE_APPLICATION_ERROR
Cursors
Parameterized Cursors
When a Cursor is opened, PL/SQL executes the query for the cursor
Syntax
OPEN cursor_name;
Thus, each FETCH will return successive rows in the active set, until the
entire set is returned.
The %NOTFOUND attribute is used to determine when the active set has
been retrieved.
Closing a Cursor
DECLARE
/* Output variables to hold the results of the query */
v_StudentID students.id%TYPE;
v_FirstName students.first_name%TYPE;
v_LastName students.last_name%TYPE;
/* Cursor declaration */
CURSOR c_Students IS
SELECT id, first_name, last_name
FROM students
WHERE major = v_Major;
Cursor Example
BEGIN
/* Identify the rows in the active set, and prepare for further
processing of the data */
OPEN c_Students;
LOOP
/* Retrieve each row of the active set into PL/SQL variables
*/
FETCH c_Students INTO v_StudentID, v_FirstName, v_LastName;
Exceptions types,
Predefined Exception
These exceptions are already defined in the STANDARD package (an Oracle
supplied package)
LOGIN_DENIED(ORA-1017) TOO_MANY_ROWS(ORA-01422)
NO_DATA_FOUND(ORA-01403) VALUE_ERRORS(ORA_06502)
NOT_LOGGED_ON(ORA-01012) ZERO_DIVIDE(ORA-01476)
Predefined Exceptions
Exception Functions
SQLCODE : Returns the numeric value for the error code
Example
DECLARE
V_ERR_CODE NUMBER;
V_ERR_TEXT VARCHAR2(255)
EXCEPTION
WHEN NO_DATA_FOUND THEN
V_ERR_CODE := SQLCODE;
V_ERR_TEXT := SQLERRM;
Predefined Exceptions
Example
DECLARE
MEMNAME EMP.ENAME%TYPE;
BEGIN
SELECT ENAME INTO MEMNAME FROM EMP
WHERE EMPNO = &INPUT_EMPNO;
DBMS_OUTPUT.PUT_LINE(MEMNAME);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE(‘No Such Employee’);
END;
User Defined Exception
Syntax
DECLARE
e_TooManyStudents EXCEPTION;
User Defined Exception
Example
DECLARE
EX1 EXCEPTION;
N NUMBER(3);
BEGIN
N:=#
IF N > 10 THEN
RAISE EX1;
ELSE
DBMS_OUTPUT.PUT_LINE(‘No Exception’);
END_IF;
EXCEPTION
WHEN EX1 THEN
DBMS_OUTPUT.PUT_LINE(‘Exception Raised’);
END;
PRAGMA EXCEPTION_INIT
Syntax
PRAGMA EXCEPTION_INIT( EXCEPTION, ERROR_NUMBER);
Example
DECLARE
MYEXP EXCEPTION;
PRAGMA EXCEPTION_INIT(MYEXP, -1422);
RAISE_APPLICATION_ERROR
Syntax
RAISE_APPLICATION_ERROR( error_number in NUMBER,
error_msg in VARCHAR2);
Example
IF age < 18 THEN
RAISE_APPLICATION_ERROR (-20001, ‘Must be
eighteen years of age.');
END IF;
Cursors and Exceptions : Summary
The implicit cursor is used by Oracle server to test and parse the SQL
statements
Introduction:
PL/SQL procedures and functions are compiled database objects. Functions returns a scalar value and
PL/SQL procedures return nothing. Both can take zero or more number of parameters as input or output. A
package is a database object that groups logically related PL/SQL types, objects, and subprograms
Objective:
After completing this module, you will be able to,
1 . Understand Procedures
2. Creating Parameters
3. Passing Parameters
4. Creating Functions
5. Implement Packages
Procedures
Features
Syntax
CREATE OR REPLACE PROCEDURE <PROCEDURE_NAME>
(<PARAMETER> [MODE] <DATA TYPE>,)
IS/AS
[LOCAL VARIABLE DECLARATION]
BEGIN
PL/SQL EXECUTABLE STATEMENT
[EXCEPTION]
[EXCEPTION HANDLERS]
END [PROGRAM UNIT NAME];
Creating Procedures
Example
CREATE OR REPLACE PROCEDURE AddStudent (
i_first_name student.first_name%type;
i_last_name student.last_name%type;
i_major student.major%type) AS
BEGIN
INSERT INTO student (id,first_name,last_name,major,credits)
values (student_sequence.nextval,i_first_name,i_last_name
,i_major,0);
commit;
END AddStudent;
Passing Parameters
IN
Default mode
Takes the value inside the program
Cannot be changed inside the sub- program
OUT
Takes the value out of the sub- program
Can be changed inside
INOUT
Takes the value inside a sub- program and brings it out of the sub-
program
Passing Parameters
END;
/
Passing Parameters
Syntax
CREATE OR REPLACE FUNCTION< FUNCTION NAME>
[ARGUMENT]
RETURN DATATYPE IS[<LOCAL DECLARATION>]
BEGIN
EXECUTABLE STATEMENTS
[EXCEPTION] [EXCEPTION HANDLERS]
END [FUNCTION_NAME];
Creating Functions
Example
FUNCTION student_type (stud_code IN VARCHAR2)
RETURN VARCHAR2
IS
BEGIN
IF stud_code = ‘T' THEN
RETURN ‘Temp';
ELSIF stud_code = 'P' THEN
RETURN 'Parmanent';
END IF;
END;
Packages
Example
CREATE PACKAGE PK1 CREATE PACKAGE BODY PK1 AS
AS I Integer :=0;
PROCEDURE P1; PROCEDURE P1 AS
BEGIN
PROCEDURE P2;
I := I + 100;
END PK1;
dbms_output.put_line(I);
END P1;
PROCEDURE P2 AS
BEGIN
I := I - 50;
dbms_output.put_line(I);
END P2;
END PK1;
Procedures, Functions and Packages : Summary
Introduction:
A database trigger is a stored program unit associated with a database table. Triggers are used to
overcome the limitations of constraints and to supplement the declarative referential integrity while
implementing complex business rules or to audit changes to data
Objective:
After completing this module, you will be able to,
These are stored procedures that gets implicitly executed when some
database-related event occurs
Can work for any DML statements like INSERT, UPDATE and DELETE but
not for SELECT
Syntax
CREATE OR REPLACE TRIGGER <TRIGGER_NAME>
[BEFORE/AFTER] [INSERT/UPDATE/DELETE]
ON <TABLE_NAME>
[ FOR EACH ROW [WHEN triggering_condition]]
trigger_body;
Components of Triggers
Trigger Timing
IT means when a trigger should fire. The possible trigger timing are BEFORE,
AFTER
Trigger Event
The trigger event can be INSERT, UPDATE or DELETE
Trigger Type
The type of trigger can be Statement or Row
Trigger Body
This section specifies the action need to be performed by the trigger i.e. it is
the PL/SQL block that gets executed
Types of Triggers
Row Level
The action specified with the row level trigger will be executed for each
affected row by the instruction for which the trigger is invoked
These triggers will fire for every INSERT/UPDATE/DELETE on the table
depending on the number of rows affected by by the triggering event
Should specify the keyword FOR EACH ROW
Statement Level
They get fired in the table level once for each trigger event
These triggers will fire for every INSERT/UPDATE/DELETE on the table
irrespective of the number of rows affected by by the triggering event
To define a statement level trigger omit the FOR EACH ROW keyword in
the trigger specification
Creating Triggers
Triggers are stored procedures that gets implicitly executed when some
database-related event occurs
Can work for any DML statements like INSERT, UPDATE and DELETE but not for
SELECT
The action specified with the row level trigger will be executed for each
affected row by the instruction for which the trigger is invoked
The statement level triggers will fire for every INSERT/UPDATE/DELETE on the
table irrespective of the number of rows affected by by the triggering event
: Quiz
Introduction:
Oracle implements collection using Tables and Varrays
Objective:
After completing this module, you will be able to,
1. Understand Collections
2. Types of Collection
3. Define and Declare Collection
4. Use Collection Methods
5. Learn Multi-level collection
Collection
Tables
Varrays
Index-by Tables
Also known as associative arrays, lets you look up
elements using arbitrary numbers and strings for
subscript values.
Nested Tables
Nested tables hold an arbitrary number of elements.
when the nested table is retrieve into a PL/SQL variable, the rows are
given consecutive subscripts starting at 1. That gives array-like access to
individual rows.
Types of Collections
Varrays
Items of type VARRAY are called varrays
Allow to associate a single identifier with an entire
collection
Manipulate the collection as a whole and reference
individual elements easily
To reference an element, use standard subscripting
syntax
Example,
Grade (3) references the third element in varray Grades.
Declaring and Defining Collection
INDEX BY key_type;
Type_name is a type specifier used later to declare collections.
Element_type is any PL/SQL datatype.
Key_type can be numeric, either BINARY_INTEGER or PLS_INTEGER.
It can also be VARCHAR2 or one of its subtypes VARCHAR, STRING, or LONG.
You mustSpecify the size. (Varchar2 (1000);)
Declaring and Defining Collection
SELECT EMPID
BULK COLLECT INTO empid_tab
FROM EMP;
IF empid_tab.last > 0 THEN
FORALL I in 1.. empid_tab.last
LOOP
Dbms_output.put_line(‘Empid: ‘||
empid_tab(i)) END LOOP
END IF;
END;
Declaring and Defining Collection
Example of Varrays
CREATE TYPE ProjectList AS VARRAY(50) OF
VARCHAR2(16);
/
CREATE TABLE department ( -- create database
table
dept_id NUMBER(2),
name VARCHAR2(15),
budget NUMBER(11,2),
-- Each department can have up to 50 projects.
projects ProjectList)
/
Using Collection Methods
Syntax:
collection_name.method_name[(parameters)]
PRIOR(n) - Returns the index of the element prior to the specified element
NEXT(n) - Returns the index of the next element after the specified
element.
Bulk DML using the FORALL statement will also take advantage of
turning multiple context switches into a single context switch.
Example
PROCEDURE proc_bulk_collect IS
CURSOR cur_emp IS
SELECT emono
FROM emp;
TYPE tt_empno IS TABLE OF emp.empno%TYPE INDEX BY BINARY_INTEGER;
tab_emono tt_empno;
BEGIN
OPEN cur_emp;
FETCH cur_emp INTO BULK COLLECT tab_emono;
close cur_emp;
FORALL i IN tab_emono.FIRST..tab_emono.LAST LOOP
DELETE FROM new_emp
WHERE empno = tab_emono(i);
END LOOP;
end;
BULK COLLECT
The following are the two Dynamic SQL statements. What is the main difference
between this two statements in the respect of execution.
Begin
EXECUTE IMMEDIATE 'CREATE TABLE X(A DATE)';
End;
/
CREATE OR REPLACE PROCEDURE CREATE_TABLE2 AS
cur integer;
rc integer;
BEGIN cur := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(cur, 'CREATE TABLE X (Y DATE)',
DBMS_SQL.NATIVE);
rc := DBMS_SQL.EXECUTE(cur);
DBMS_SQL.CLOSE_CURSOR(cur);
END;
/
Oracle - Summary
Physical database structure includes data file, redo log file and control
files
All the data dictionary tables and views for a given database are stored
in that database’s SYSTEM tablespace
Oracle 9i