Overview of PL/SQL: Presented For GCP-EBDP Team (AT & T) 22 December 2008
Overview of PL/SQL: Presented For GCP-EBDP Team (AT & T) 22 December 2008
Overview of PL/SQL: Presented For GCP-EBDP Team (AT & T) 22 December 2008
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
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.
PL/SQL
EXECUTION
EXCEPTION-HANDLING.
Block Structure
Declare
--declarations
Begin
-- statements
[EXCEPTION
--- handlers]
END;
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)
PL/SQL
Constant
• Declare one identifier per line.
• Initialize identifiers by using the assignment
operator (:=) or the DEFAULT reserved word.
PL/SQL
Scalar Datatypes
- Char [(maximum length)]
- Varchar [(maximum length)]
- LONG
- LONG RAW
- NUMBER [(precision, scale)]
- BINARY_INTEGER
- PLS_INTEGER
- BOOLEAN
- DATE
- TIMESTAMP
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;
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.
PL/SQL
Ex:
part_no NUMBER(4); -- variable named part_no
to hold 4-digit numbers
PL/SQL
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;
PL/SQL
Declaring Constants
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:
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.
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);
PL/SQL
PL/SQL
Verify :
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.
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.
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
PL/SQL
Adobe Acrobat
Document
PL/SQL
Ex:
PL/SQL
PL/SQL
PL/SQL
SYNTAX:
IF condition THEN
statements;
[ELSIF condition THEN
statements;]
[ELSE
statements;]
END IF;
Syntax:
If the employee
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
PL/SQL
Output:
Oops KING is a PRESIDENT
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;
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
PL/SQL
PL/SQL
Basic Loop
- Executes the statements atleast once before checking for the
condition.
- Explicitly increment the loop value
PL/SQL
Syntax:
LOOP
statement1;-- delimiter
. . .-- statements
EXIT [WHEN condition];
END LOOP;
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
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;
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
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;
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
PL/SQL
PL/SQL
BENEFITS of PL/SQL
1. PLSQL is portable
2. You can program with procedural Language control
Structures
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
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;
Advanced PL/SQL
Advanced PL/SQL
Advanced PL/SQL
PARAMETER MODES
In (Default)
Out
In out
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.
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);
Advanced PL/SQL
output:
Empid :7369
Empname :SMITH
Salary :800
Job :CLERK
Manager :7902
Advanced PL/SQL
OUT Parameter:
Procedure created.
Advanced PL/SQL
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
Advanced PL/SQL
Function created.
Advanced PL/SQL
PL/SQL
STORED FUNCTIONS
Advanced PL/SQL
Syntax:
Advanced PL/SQL
Function created.
Advanced PL/SQL
Advanced PL/SQL
Advanced PL/SQL
PROCEDURES V FUNCTIONS
Procedures may return through out and in out parameters where as function
must return.
Advanced PL/SQL
Advanced PL/SQL
PACKAGES
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>;
Advanced PL/SQL
COMPILING PACKAGES
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
Advanced PL/SQL
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
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.
Advanced PL/SQL
DECLARE
CURSOR c1 IS
SELECT empno, ename, job FROM emp WHERE
deptno = 20;
Advanced PL/SQL
Advanced PL/SQL
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);
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 /
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
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
Advanced PL/SQL
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 /
Advanced PL/SQL
Advanced PL/SQL
THANK YOU