You are on page 1of 78

Presented For GCP-EBDP

Team ( AT & T )
22 December 2008

Overview of PL/SQL

SRINIVAS PUSHPALA
AT&T - GCP-EBDB Team

Overview
PL/SQL is a procedural language extension to SQL,
the standard data access language for relational
databases.

 PL/SQL offers modern software engineering


features such as
 Data Encapsulation
 Exception Handling
 Information Hiding,
 Object orientation
 Brings state-of-the art programming to the Oracle
Server and toolset.

2 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

Difference between SQL and PL/SQL


SQL PL/SQL
 4GL 3&4GL

 Includes only Data Data Manipulation and


Manipulation Logic Processing Logic

 More no. of Network Less no. of network


Round Trips to server round trips to server
in client- server Scenario since the request is sent
in blocks.

3 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

 Block Structure
 PL/SQL is a block-structured language. That is, the
basic units (procedures, functions, and anonymous
blocks) that make up a PL/SQL program are logical
blocks, which can contain any number of nested sub-
blocks. Typically, each logical block corresponds to a
problem or subproblem to be solved. Thus, PL/SQL
supports the divide-and-conquer approach to problem
solving called stepwise refinement.

4 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

 PL/SQL block has three parts:


 DECLARATIONS

 EXECUTION

 EXCEPTION-HANDLING.
Block Structure
Declare
--declarations
Begin
-- statements
[EXCEPTION
--- handlers]
END;

5 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

 DECLARATION SECTION:
 Variables and Constants
 Variables can be used for:
• Temporary storage of data
• Manipulation of stored values
• Reusability
• Ease of maintenance

 Variable Types
- Scalar
- Composite
- Reference
- LOB (large objects)

6 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

 Guidelines for Declaring PL//SQL Variables


• Follow naming conventions.
• Initialize variables designated as NOT NULL

 Constant
• Declare one identifier per line.
• Initialize identifiers by using the assignment
operator (:=) or the DEFAULT reserved word.

7 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

 Scalar Datatypes
- Char [(maximum length)]
- Varchar [(maximum length)]
- LONG
- LONG RAW
- NUMBER [(precision, scale)]
- BINARY_INTEGER
- PLS_INTEGER
- BOOLEAN
- DATE
- TIMESTAMP

8 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

 %TYPE
Can be used to create variable with the same attribute
as the column in a type

Ex:
 v_name employees.last_name%TYPE;
 v_balance NUMBER(7,2);
 v_min_balance v_balance%TYPE :=10;

9 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

Bind Variables
PLSQL does not have any input output capability of its own
can reference substitution variables within a PLSQL with a
preceding ampersand isql* plus host (or "bind") variables
can be used to pass runtime values out of the PLSQL block
back to isql* plus environment.

Ex.

VARIABLE g_salary NUMBER


BEGIN
SELECT sal
INTO :g_salary
FROM emp
WHERE empno = 7698;
END;
/
PRINT g_salary

10 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

 Variables can have any SQL datatype


Data types
- CHAR
- DATE
- NUMBER
- BOOLEAN
- BINARY_INTEGER.

Ex:
part_no NUMBER(4); -- variable named part_no
to hold 4-digit numbers

in_stock BOOLEAN; -- variable named


in_stock to hold the Boolean value TRUE or FALSE
11 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation
AT&T - GCP-EBDB Team

PL/SQL

You can also declare nested tables, variable-size arrays


(varrays for short), and records using the TABLE, VARRAY,
and RECORD composite datatypes.

Assigning Variables:
a. :=
b. select or fetch database values into it

Ex.
a. tax := price * tax_rate;
bonus := current_salary * 0.10;
amount := TO_NUMBER(SUBSTR('750 dollars', 1, 3));
valid := FALSE;

b. SELECT sal * 0.10 INTO bonus FROM emp WHERE empno =


emp_id;

12 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

 Declaring Constants

credit_limit CONSTANT REAL := 5000.00;

13 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

 EXECUTION SECTION:
Can contain SQL Queries and Procedural Logic

 Ex:
 Insert the data into Hike_emp for the following
1. Increase commission of all employees in sales by 50%
2. Provide commission of all employees in Accounting by 25% of
salary
SQL> SELECT D.DNAME, E.ENAME, E.JOB, E.SAL, E.COMM
2 FROM EMP E LEFT OUTER JOIN (SELECT DEPTNO, DNAME
FROM DEPT WHERE DNAME IN ('SALES', 'ACCOUNTING
')) D ON D.DEPTNO = E.DEPTNO;
OUTPUT:

14 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

 OUTPUT:
DNAME ENAME JOB SAL COMM
-------------- ---------- --------- ---------- ----------
SMITH CLERK 800
SALES ALLEN SALESMAN 1600 300
SALES WARD SALESMAN 1250 500
JONES MANAGER 2975
SALES MARTIN SALESMAN 1250 1400
SALES BLAKE MANAGER 2850
ACCOUNTING CLARK MANAGER 2450
SCOTT ANALYST 3000
ACCOUNTING KING PRESIDENT 5000
SALES TURNER SALESMAN 1500 0
ADAMS CLERK 1100
DNAME ENAME JOB SAL COMM
-------------- ---------- --------- ---------- ----------
SALES JAMES CLERK 950
FORD ANALYST 3000
ACCOUNTING MILLER CLERK 1300
14 rows selected.

15 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

DECLARE
DVar1 VARCHAR(25);
DVar2 VARCHAR(25);
BEGIN
DVar1 := 'SALES';
DVar2 := 'ACCOUNTING';
INSERT INTO HIKE_EMP ( EMPNO,
ENAME,
JOB,
MGR,
HIREDATE,
SAL,
COMM,
DEPTNO)
SELECT EMPNO,
ENAME,
JOB,
MGR,
HIREDATE,
SAL,
COMM + COMM * .50 AS COMM,
DEPTNO
FROM EMP
WHERE DEPTNO = (SELECT DEPTNO FROM DEPT WHERE DNAME= DVar1);

16 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

INSERT INTO HIKE_EMP ( EMPNO,


ENAME,
JOB,
MGR,
HIREDATE,
SAL,
COMM,
DEPTNO)
SELECT EMPNO,
ENAME,
JOB,
MGR,
HIREDATE,
SAL,
SAL * .25 AS COMM,
DEPTNO
FROM EMP
WHERE DEPTNO = (SELECT DEPTNO FROM DEPT WHERE DNAME = DVar2);
COMMIT;
END;
PL/SQL procedure successfully completed.

17 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

Verify :

SQL> SELECT D.DNAME, E.ENAME, E.JOB,


E.SAL, E.COMM FROM HIKE_EMP E
LEFT OUTER JOIN
(SELECT DEPTNO, DNAME FROM DEPT WHERE
DNAME IN ('SALES', 'ACCOUNTING')) D ON
D.DEPTNO = E.DEPTNO;

18 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

 Output:
DNAME ENAME JOB SAL COMM
--------------
---------- --------- ----------
----------
SALES ALLEN SALESMAN 1600 450
SALES WARD SALESMAN 1250 750
SALES MARTIN SALESMAN 1250 2100
SALES BLAKE MANAGER 2850
SALES TURNER SALESMAN 1500 0
SALES JAMES CLERK 950
ACCOUNTING CLARK MANAGER 2450 612.5
ACCOUNTING KING PRESIDENT 5000 1250
ACCOUNTING MILLER CLERK 1300 325

9 rows selected.

19 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

 EXCEPTION/ERROR HANDLING:
- Allows you to handle Oracle Errors using Error
handling Routines
- You can create user defined errors and handle them
using Error handling routines.

Exceptions are designed for Runtime errors


and compilations errors are reported by SQL engine.

20 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

 Predefined Exceptions
Ex.

SQL> begin
2 select empname from emp;
3 end;
4 /
select empname from emp;
*
ERROR at line 2:
ORA-06550: line 2, column 8:
PL/SQL: ORA-00904: "EMPNAME": invalid identifier
ORA-06550: line 2, column 1:
PL/SQL: SQL Statement ignored

21 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

Please refer the attached PDF for list of


predefined exceptions.

Adobe Acrobat
Document

22 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

Ex:

SQL> set serveroutput on


SQL> Declare
2 errormsg varchar(25);
3 begin
4 select ename into errormsg from emp where ename = 'abc';
5 exception
6 when no_data_found then
7 dbms_output.put_line ('Empname not found');
8 end;
9 /
Empname not found

PL/SQL procedure successfully completed.

23 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

 User Defined Exceptions

- Raised by Programmer for better handling of


RAISING EXCEPTIONS
User-defined exceptions are raised explicitly via the RAISE statement.
Ex:
SQL> set serveroutput on
SQL> DECLARE
2 e exception;
3 BEGIN
4 raise e;
5 EXCEPTION
6 when e then
7 dbms_output.put_line('e is raised');
8 END;
9 /
e is raised
PL/SQL procedure successfully completed.

24 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

Using OTHERS Exception to handle Unhandled excepions


Ex:
SQL> set serveroutput on
SQL> Declare
2 errormsg varchar(25);
3 begin
4 select ename into errormsg from emp where ename = 'abc';
5 exception
6 When others then
7 dbms_output.put_line('Error Code:' || SQLCODE);
8 dbms_output.put_line('Error Message:' || SQLERRM);
9 end;
10 /
Error Code:100
Error Message:ORA-01403: no data found

PL/SQL procedure successfully completed.

25 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

 Writing Control Structures


 CONDITIONAL IF Statement
Used to change the logical flow of execution of Statemens

 SYNTAX:
IF condition THEN
statements;
[ELSIF condition THEN
statements;]
[ELSE
statements;]
END IF;
Syntax:
If the employee

26 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

EX:
Program to show employee and his designation drawing highest
salary

SQL> declare
2 vEmpname varchar(25);
3 vJob varchar(25);
4 begin
5 select ename into vEmpname from emp where sal = (select
max(sal) from emp);
6 select job into vJob from emp where sal = (select max(sal)
from emp);
7 if vJob = 'CLERK' then
8 dbms_output.put_line(vEmpname || 'is a ' || vJob);
9 elsif vJob = 'SALESMAN' then
10 dbms_output.put_line(vEmpname || 'is a ' || vJob);
11 elsif vJob = 'MANAGER' then

27 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

12 dbms_output.put_line('Oops ' || vEmpname || 'is a ' || vJob);


13 elsif vJob = 'ANALYST' then
14 dbms_output.put_line(vEmpname || 'is a ' || vJob);
15 elsif vJob = 'PRESIDENT' then
16 dbms_output.put_line('Oops ' || vEmpname || 'is a ' || vJob);
17 else
18 dbms_output.put_line(vEmpname || 'is a ' || vJob);
19 end if;
20 end;
21 /

Output:
Oops KING is a PRESIDENT

PL/SQL procedure successfully completed.

28 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

 CASE Statement
Used to select one of several alternatives

 SYNTAX:

CASE selector
WHEN expression1 THEN result1
WHEN expression2 THEN result2
...
WHEN expressionN THEN resultN
[ELSE resultN+1;]
END;

29 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

Ex:
PLSQL showing employee earning max salary and his designation

SQL> declare
2 vEmpname varchar(25);
3 vJob varchar(25);
4 vSal Number(9,2);
5 vMsg varchar(255);
6 begin
7 select ename, job, sal into vEmpname, vJob, vSal from emp
where sal = (select max(sal) from e
mp);
8 Case vJob
9 When 'CLERK' then
10 vMsg := vEmpname || 'is a ' || vJob || 'Earning ' || to_char(vSal);
11 When 'SALESMAN' then

30 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

12 vMsg := vEmpname || 'is a ' || vJob || 'Earning ' || to_char(vSal);


13 WHEN 'MANAGER' then
14 vMsg := 'Oops ' || vEmpname || 'is a ' || vJob || 'Earning ' ||
to_char(vSal);
15 WHEN 'ANALYST' then
16 vMsg := vEmpname || 'is a ' || vJob || 'Earning ' || to_char(vSal);
17 WHEN 'PRESIDENT' then
18 vMsg := 'Oops ' || vEmpname || 'is a ' || vJob || 'Earning ' ||
to_char(vSal);
19 else
20 vMsg := vEmpname || 'is a ' || vJob || 'Earning ' || to_char(vSal);
21 End Case;
22 dbms_output.put_line(vMsg);
23 End;
24 /
output:
Oops KINGis a PRESIDENT Earning 5000
PL/SQL procedure successfully completed.

31 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

 Iterative Control: Loop Statements


Loops repeat the statement or sequence of statements multiple
times

 There are 3 types of Loop


- Basic Loop
- For Loop
- While Loop

Basic Loop
- Executes the statements atleast once before checking for the
condition.
- Explicitly increment the loop value

32 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

Syntax:

LOOP
statement1;-- delimiter
. . .-- statements
EXIT [WHEN condition];
END LOOP;

condition is a Boolean variable or


expression (TRUE, FALSE, or NULL);

33 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

 Ex.
Count Program
SQL> DECLARE
2 i number := 1;
3 BEGIN
4 loop
5 dbms_output.put_line('i = ' || i);
6 i := i + 1;
7 exit when i > 5;
8 end loop;
9 END;
 Output:
i=1
i=2
i=3
i=4
i=5

34 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

 For Loop
- Executes the statements in the loop only after
checking for the condition
- Automatically increments the loop value
 Syntax:
For <loop_counter_variable> in
low_bound..high_bound loop
Sequence of statements;
End loop;

35 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

 Ex:
SQL> declare
2 i number := 1;
3 begin
4 for i in 1..5 loop
5 dbms_output.put_line('i =' || i);
6 end loop;
7 end;
8 /
 output:
i =1
i =2
i =3
i =4
i =5

36 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

 While Loop
- Check for the condition before execution of
statements
- Increments loop value explicitly

 Syntax:
While <condition> loop
Sequence of statements;
End loop;

37 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

 Ex:
SQL> declare
2 i number := 1;
3 begin
4 while i<5 loop
5 dbms_output.put_line('i= ' || i);
6 i:= i+1;
7 end loop;
8 end;
9 /

 output:
i= 1
i= 2
i= 3
i= 4

38 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

Nested Loops and labels


...
BEGIN
<<Outer_loop>>
LOOP
v_counter := v_counter+1;
EXIT WHEN v_counter>10;
<<Inner_loop>>
LOOP
...
EXIT Outer_loop WHEN total_done = 'YES';
-- Leave both loops
EXIT WHEN inner_done = 'YES';
-- Leave inner loop only
...
END LOOP Inner_loop;
...
END LOOP Outer_loop;
END;

39 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

 BENEFITS of PL/SQL
1. PLSQL is portable
2. You can program with procedural Language control
Structures

40 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 Overview of Subprograms
A subprogram:
• Is a named PL/SQL block that can accept parameters
and be invoked from a calling environment
• Is of two types:
– A procedure that performs one of more actions
– A function that computes and returns a value
• Is based on standard PL/SQL block structure
• Provides modularity, reusability, extensibility,
and maintainability
• Provides easy maintenance, improved data security
and integrity, improved performance, and improved
code clarity

41 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 Stored Procedure:
• A procedure is a type of subprogram that performs
an action.
• A procedure can be stored in the database, as a
schema object, for repeated execution.

 Syntax:
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter1 [mode1] datatype1,
parameter2 [mode2] datatype2,
. . .)]
IS|AS
PL/SQL Block;

42 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 Formal Versus Actual Parameters


CREATE PROCEDURE raise_sal(p_id NUMBER, p_amount
NUMBER)
...
END raise_sal;
raise_sal(v_id, 2000)
• Formal parameters: variables declared in the
parameter list of a subprogram specification
Example:
CREATE PROCEDURE raise_sal(p_id NUMBER, p_amount
NUMBER)
...
END raise_sal;
• Actual parameters: variables or expressions
referenced in the parameter list of a subprogram call
Example:
raise_sal(v_id, 2000)

43 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

The REPLACE option indicates that if the procedure


exists, it will be dropped and replaced with the
new version created by the statement.
• PL/SQL block starts with either BEGIN or the
declaration of local variables and ends with either
END or END procedure_name.

44 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

PARAMETER MODES

In (Default)

Out

In out

45 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 IN
 In parameter will act as pl/sql constant.

 OUT
 Out parameter will act as unintialized variable.
 You cannot provide a default value to an out
parameter.
 An actual parameter corresponding to an out formal
parameter must be a variable.

 IN OUT
 In out parameter will act as initialized variable.
 An actual parameter corresponding to an in out
formal parameter must be a variable.

46 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 Ex:
 IN parameter:
 SQL> create or replace procedure disp_employee_details(empid
in number)
2 as
3 Begin
4 declare
5 cursor c is select * from emp;
6 begin
7 for tmp in c loop
8 if tmp.empno = empid then
9 dbms_output.put_line('Empid :' || tmp.empno);
10 dbms_output.put_line('Empname :' || tmp.ename);
11 dbms_output.put_line('Salary :' || tmp.sal);
12 dbms_output.put_line('Job :' || tmp.job);

47 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

13 dbms_output.put_line('Manager :' || tmp.mgr);


14 end if;
15 end loop;
16 end;
17 End disp_employee_details;
18 /
Procedure created.
Invoking stored Procedure :
call disp_employee_details(7369);

 output:
Empid :7369
Empname :SMITH
Salary :800
Job :CLERK
Manager :7902

48 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 OUT Parameter:

 SQL> create or replace procedure show_emp(empid in number,


empname out varchar2, salary out number,

2 desig out varchar2)


3 is
4 begin
5 select ename, sal, job into empname, salary, desig
6 from emp
7 where empno = empid;
8 end show_emp;
9 /

Procedure created.

49 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 SQL> variable vEmpname varchar2(25);


 SQL> variable vEmpsal NUMBER;
 SQL> variable vEmpDesig varchar2(25);
 SQL> exec show_emp(7369, :vEmpname, :vEmpsal, :vEmpDesig);
 PL/SQL procedure successfully completed.
 SQL> print vEmpname
 VEMPNAME
 --------------------------------
 SMITH
 SQL> print vEmpsal;
 VEMPSAL
 ----------
 800

 SQL> print vEmpDesig;


 VEMPDESIG
 --------------------------------
 CLERK

50 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 IN OUT PARAMETER
 SQL> CREATE OR REPLACE PROCEDURE
format_phone
2 (p_phone_no IN OUT VARCHAR2)
3 IS
4 BEGIN
5 p_phone_no := '(' || SUBSTR(p_phone_no,1,3) ||
6 ')' || SUBSTR(p_phone_no,4,3) ||
7 '-' || SUBSTR(p_phone_no,7);
8 END format_phone;
9 /

Procedure created.
51 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation
AT&T - GCP-EBDB Team

Advanced PL/SQL

SQL> VARIABLE g_phone_no VARCHAR2(15)


SQL> BEGIN
2 :g_phone_no := '8006330575';
3 END;
4 /
PL/SQL procedure successfully completed.
SQL> PRINT g_phone_no
G_PHONE_NO
--------------------------------
8006330575
SQL> EXECUTE format_phone (:g_phone_no)
PL/SQL procedure successfully completed.
SQL> PRINT g_phone_no
G_PHONE_NO
--------------------------------
(800)633-0575

52 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 Invoking Functions as Expressions


 Ex:
 SQL> CREATE OR REPLACE FUNCTION tax(p_value
IN NUMBER)
2 RETURN NUMBER IS
3 BEGIN
4 RETURN (p_value * 0.08);
5 END tax;
6 /

Function created.

53 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 SQL> SELECT empno, ename, sal, tax(sal)


2 FROM emp
3 WHERE deptno = 10;

EMPNO ENAME SAL TAX(SAL)


---------- ---------- ---------- ----------
7782 CLARK 2450 196
7839 KING 5000 400
7934 MILLER 1300 104

 Benefits of Stored Procedures and Functions


• Improved performance
• Easy maintenance
• Improved data security and integrity
• Improved code clarity

54 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

PL/SQL

 STORED FUNCTIONS

 Overview of Stored Functions


• A function is a named PL/SQL block that returns
a value.
• A function can be stored in the database as a
schema object for repeated execution.
• A function is called as part of an expression.

55 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 Syntax:

CREATE [OR REPLACE] FUNCTION function_name


[(parameter1 [mode1] datatype1,
parameter2 [mode2] datatype2,
. . .)]
RETURN datatype
IS|AS
PL/SQL Block;

56 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 SQL> CREATE OR REPLACE FUNCTION get_sal


2 (p_id IN emp.empno%TYPE)
3 RETURN NUMBER
4 IS
5 v_salary emp.sal%TYPE :=0;
6 BEGIN
7 SELECT sal
8 INTO v_salary
9 FROM emp
10 WHERE empno = p_id;
11 RETURN v_salary;
12 END get_sal;
13 /

Function created.

57 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 SQL> VARIABLE g_salary NUMBER


 SQL> EXECUTE :g_salary := get_sal(7369);

 PL/SQL procedure successfully completed.

 SQL> PRINT g_salary;


G_SALARY
----------
800

58 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 Locations to Call User-Defined Functions


• Select list of a SELECT command

• Condition of the WHERE and HAVING clauses

• CONNECT BY, START WITH, ORDER BY, and GROUP


BY clauses

• VALUES clause of the INSERT command

• SET clause of the UPDATE command

59 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 PROCEDURES V FUNCTIONS
 Procedures may return through out and in out parameters where as function
must return.

 Procedures can not have return clause where as functions must.


 We can use call statement directly for executing procedure where as we
need to declare a variable in case of functions.
 Functions can use in select statements where as procedures can not.
 Functions can call from reports environment where as procedures can not.
 We can use exec for executing procedures where as functions can not.
 Function can be used in dbms_output where as procedure can not.
 Procedure call is a standalone executable statement where as function call is
a part of an executable statement.

60 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 Advantages of User-Defined Functions


in SQL Expressions

• Extend SQL where activities are too complex, too


awkward, or unavailable with SQL

• Can increase efficiency when used in the WHERE


clause to filter data, as opposed to filtering the
data in the application

• Can manipulate character strings

61 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 PACKAGES

• Group logically related PL/SQL types, items, and


subprograms
• Consist of two parts:
– Specification
– Body
• Cannot be invoked, parameterized, or nested
• Allow the Oracle server to read multiple objects
into memory at once

62 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 PACKAGE SYNTAX
 Create or replace package <package_name> is
-- package specification includes subprograms signatures, cursors
and global or
public variables.
End <package_name>;

 Create or replace package body <package_name> is


-- package body includes body for all the subprograms
declared in the spec, private
Variables and cursors.
Begin
-- initialization section
Exception
-- Exception handling section
End <package_name>;

63 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 COMPILING PACKAGES

 SQL> Alter package PKG compile;


 SQL> Alter package PKG compile specification;
 SQL> Alter package PKG compile body;

64 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 Ex:
 Creating specification :
SQL> create or replace package EmpPkg is
2 procedure disp_employee_details(empid in number);
3 end EmpPkg;
4 /
Package created.

 Creating Body:
SQL> create or replace package body EmpPkg is
2 procedure disp_employee_details(empid in number)
3 as
4 Begin
5 declare
6 cursor c is select * from emp;
7 begin
8 for tmp in c loop

65 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

9 if tmp.empno = empid then


10 dbms_output.put_line('Empid :' || tmp.empno);
11 dbms_output.put_line('Empname :' || tmp.ename);
12 dbms_output.put_line('Salary :' || tmp.sal);
13 dbms_output.put_line('Job :' || tmp.job);
14 dbms_output.put_line('Manager :' || tmp.mgr);
15 end if;
16 end loop;
17 end;
18 End disp_employee_details;
19 End EmpPkg;
20 /
Package body created.
Invoking procedure:
SQL> execute EmpPkg.disp_employee_details(7369);
OUTPUT:
Empid :7369
Empname :SMITH
Salary :800
Job :CLERK
Manager :7902

66 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 Advantages of Packages
• Added functionality: Persistency of variables
and cursors
• Better performance:
– The entire package is loaded into memory
when the package is first referenced.
– There is only one copy in memory for all users.
– The dependency hierarchy is simplified.
• Overloading: Multiple subprograms of the
same name

67 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 Cursors
 Oracle uses work areas to execute SQL statements
and store processing information.
 A PL/SQL construct called a cursor lets you name a
work area and access its stored information. There are
two kinds of

 cursors:
- implicit
- explicit.

68 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

• Implicit cursors: Declared for all DML and PL/SQL


SELECT statements

PL/SQL implicitly declares a cursor for all SQL data


manipulation statements, including queries that return
only one row. For queries that return more than
one row, you can explicitly declare a cursor to
process the rows individually. An example follows:

DECLARE
CURSOR c1 IS
SELECT empno, ename, job FROM emp WHERE
deptno = 20;

69 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

The set of rows returned by a multi-row query is called the result


set. Its size is the number of rows that meet your search criteria.

• Explicit cursors: Declared and named by the programmer


an explicit cursor "points" to the current row in the result set.
This allows your program to process the rows one at a time.

Multi-row query processing is somewhat like file processing. For


example, a COBOL program opens a file, processes records,
then closes the file. Likewise, a PL/SQL program opens a cursor,
processes rows returned by a query, then closes the cursor.

Just as a file pointer marks the current position in an open file, a


cursor marks the current position

70 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

CURSOR LIFE CYCLE:


DECLARE : Create a named work area
OPEN : Identify the active set
FETCH : Load the current row into variables
CLOSE : Release the active work area

 You use the OPEN, FETCH, and CLOSE statements to control a


cursor.
 The OPEN statement executes the query associated with the
cursor, identifies the result set, and positions the cursor before
the first row.
 The FETCH statement retrieves the current row and advances the
cursor to the next row.
 When the last row has been processed, the CLOSE statement
disables the cursor.

71 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 Ex:
 Assuming the salary drawn by employee is in dollars convert
them into Rupees and display employees as taxable if salary
exceeds 100000 p.a else display as non taxable

 SQL> declare
2 cursor c is
3 select ename, sal from emp;
4 v_empname varchar(25);
5 v_sal number(9,2);
6 begin
7 open c;
8 fetch c into v_empname, v_sal;
9 loop
10 if v_sal * 600 > 100000 then
11 dbms_output.put_line('Empname :' || v_empname);
12 dbms_output.put_line('Salary :' || v_sal);
13 dbms_output.put_line('Annual Salary :' || v_sal * 600);

72 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

14 dbms_output.put_line('Taxable');
15 else
16 dbms_output.put_line('Empname :' || v_empname);
17 dbms_output.put_line('Salary :' || v_sal);
18 dbms_output.put_line('Annual Salary :' || v_sal * 600);
19 dbms_output.put_line('Non Taxable');
20 End if;
21
22 fetch c into v_empname, v_sal;
23 exit when c%notfound;
24
25 end loop;
26 close c;
27 end;
28 /

73 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 Output:

 Empname :SMITH
 Salary :800
 Annual Salary :480000
 Taxable
 Empname :ALLEN
 Salary :1600
 Annual Salary :960000
 Taxable
 Empname :WARD
 Salary :1250
 Annual Salary :750000
 Taxable
 Empname :JONES
 Salary :2975
 Annual Salary :1785000
 Taxable
 Empname :MARTIN
 Salary :1250
 Annual Salary :750000
 Taxable

74 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 Empname :BLAKE
 Salary :2850
 Annual Salary :1710000
 Taxable
 Empname :CLARK
 Salary :2450
 Annual Salary :1470000
 Taxable
 Empname :SCOTT
 Salary :3000
 Annual Salary :1800000
 Taxable
 Empname :KING
 Salary :5000
 Annual Salary :3000000
 Taxable
 Empname :TURNER
 Salary :1500
 Annual Salary :900000
 Taxable
 Empname :ADAMS
 Salary :1100
 Annual Salary :660000
 Taxable
 Empname :JAMES
 Salary :950
 Annual Salary :570000
 Taxable
 Empname :FORD
 Salary :3000
 Annual Salary :1800000
 Taxable
 Empname :MILLER
 Salary :1300
 Annual Salary :780000
 Taxable

75 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 Above cursor in for loop


 Note: there is no fetch statement required.

 SQL> declare
2 cursor c is
3 select ename, sal from emp;
4 begin
5 for tmp in c loop
6 if tmp.sal * 600 > 100000 then
7 dbms_output.put_line('Empname :' || tmp.ename);
8 dbms_output.put_line('Salary :' || tmp.sal);
9 dbms_output.put_line('Annual Salary :' || tmp.sal * 600);
10 dbms_output.put_line('Taxable');
11 else
12 dbms_output.put_line('Empname :' || tmp.ename);
13 dbms_output.put_line('Salary :' || tmp.sal);
14 dbms_output.put_line('Annual Salary :' || tmp.sal * 600);
15 dbms_output.put_line('Non Taxable');
16 End if;
17 end loop;
18 end;
19 /

76 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

 Explicit cursor Attributes

 Obtain status information about an cursor..


 Attribute Type Description
 %ISOPEN Boolean Evaluates to TRUE if the cursor is
open
 %NOTFOUND Boolean Evaluates to TRUE if the
most recent fetch does not return a row
 %FOUND Boolean Evaluates to TRUE if the most
recent fetch returns a row; complement of %NOTFOUND
 %ROWCOUNT Number Evaluates to the total number
of rows returned so far

77 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation


AT&T - GCP-EBDB Team

Advanced PL/SQL

THANK YOU

78 PL/SQL – Dec 2008 Copyright © 2008 IBM Corporation

You might also like