0% found this document useful (0 votes)
69 views

Database Engineering: PL/SQL

This document summarizes a lecture on PL/SQL features in Oracle databases. It discusses the history of Oracle releases and features over time. It then covers SQL commands, PL/SQL programming constructs like IF/ELSE statements and loops, using cursors to retrieve multiple rows, creating triggers, and defining stored procedures. Examples are provided for many of the PL/SQL concepts discussed.

Uploaded by

ash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views

Database Engineering: PL/SQL

This document summarizes a lecture on PL/SQL features in Oracle databases. It discusses the history of Oracle releases and features over time. It then covers SQL commands, PL/SQL programming constructs like IF/ELSE statements and loops, using cursors to retrieve multiple rows, creating triggers, and defining stored procedures. Examples are provided for many of the PL/SQL concepts discussed.

Uploaded by

ash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Database Engineering

[Spring Course 10]

PL/SQL
Korra Sathya Babu
Department of Computer Science
NIT Rourkela
11/29/15

Lecture 3

History of Oracle features


development

Oracle Release Version 1,2 Initial release of RSI product


Oracle Release Version 3 Oracle rewritten in C and RSI takes the name Oracle
Oracle Release Version 4 Introduced Read Consistency
Oracle Release Version 5 Operate on Client Server Model computing
Oracle Release Version 5.1 Supported Distributed Queries
Oracle Release Version 6 supports row level locking and hot backups and
embedded PL/SQL
Oracle Release Version 7 Released with performance enhancements, administrative utilities,
application-development tools, security features, the ability to persist PL/SQL program units in the
database asstored procedures and triggers, and support for declarativereferential integrity

Oracle
Oracle
Oracle
Oracle
Oracle

Release
Release
Release
Release
Release

11/29/15

Version
Version
Version
Version
Version

8 released with SQL object technology and support for terabytes of data
8i Internet technology
9i Application Server released with support for building portals
10g support of grid computing
11g on windows and linux based systems

Lecture 3

DDL

CREATE, ALTER, DROP, TRUNCATE, COMMENT, RENAME

DML

Classification of SQL
Commands

SELECT , INSERT, UPDATE, DELETE, MERGE,CALL, LOCK TABLE

DCL

GRANT, REVOKE

TCL

COMMIT, SAVEPOINT, ROLLBACK, COMMIT, SET TRANSACTION

11/29/15

Lecture 3

Hospital Database

BILLED(BILL_NO: NUMBER(5) PK, PATIENT_NO: NUMBER(9), ITEM_CODE:


NUMBER(5), CHARGE: NUMBER(7,2))

TREATS(PHY_ID: NUMBER(4) PK, PATIENT_NO: NUMBER(4) PK,


PROCEDURE_NO: NUMBER(4) PK, DATE_TREATED: DATE PK,
TREAT_RESULT: VARCHAR2(50))

ITEM(ITEM_CODE: NUMBER(4) PK, DESCRIPTION: VARCHAR2(50),


NORMAL_CHARGE: NUMBER(7,2))

PHYSICIANS(PHY_ID: NUMBER(4) PK, PHY_PHONE: CHAR(8), PHY_NAME:


VARCHAR2(50))

PATIENT(PATIENT_NO: NUMBER(4) PK, DATE_LAST_TREATED: DATE,


PAT_NAME: VARCHAR2(50), ROOM_LOCATION: CHAR(4))

ROOM(ROOM_LOCATION: CHAR(4) PK, ROOM_ACCOMMODATION:


CHAR(2), ROOM_EXTENTION: NUMBER(4))

PROCEDURES(PROCEDURE_NO: NUMBER(4) PK, PROC_DESCRIPTION:


VARCHAR(50))
11/29/15

Lecture 3

SQL Vs PL/SQL
SQL
Non Procedural capabilities
Time consuming processing
No error handling routines

PL/SQL

Procedural capabilities
Reduced network traffic
Error handling
Resource sharing

11/29/15

Lecture 3

PL/SQL Block
DECLARE
Declaration of memory variables, constants, cursors, etc in PL/SQL

BEGIN
SQL executable statements
Pl/SQL executable statements

EXCEPTION
SQL or PL/SQL code to handle errors that may arise during the
execution of the ode block between BEGIN and EXCEPTION section

END ;

11/29/15

Lecture 3

File creation,execution
Steps to Create a PL/SQL Program and execute

Start Notepad
Type the Program code
Type a slash (/) at the end of the program and press enter
Save the file (example MyFirstProgram)
Switch back to SQL Plus Prompt
Execute the Program by typing one of the following commands
START MyFirstProgram
@ MyFirstProgram
EXEC MyFirstProgram
RUN MyFirstProgram

11/29/15

Lecture 3

Program

Program to read two numbers and display their sum


SET SERVEROUTPUT ON
DECLARE
n1 NUMBER(3);
n2 NUMBER(3);
n3 NUMBER(3);
BEGIN
n1 := &Number1;
n2 := &Number2;
n3 := n1 + n2;
DBMS_OUTPUT.PUT_LINE(The Sum is
END;
/
SET SERVEROUTPUT OFF

11/29/15

Lecture 3

:||n3);

Program

Program to retrieve name, basic and designation of an employee


--Program to retrieve name, basic and designation
SET SERVEROUTPUT ON
PROMPT Enter Employee Number
ACCEPT N
DECLARE
DNAME EMP.EMP_NAME%TYPE;
DBASIC EMP.BASIC%TYPE;
DDESIGN EMP.DESIGN%TYPE;
BEGIN
SELECT EMP_NAME, BASIC, DESIGN INTO DNAME, DBASIC, DDESIGN
FROM EMP
WHERE EMP_NO=&N;
DBMS_OUTPUT.PUT_LINE(NAME
:||DNAME);
DBMS_OUTPUT.PUT_LINE(SALARY
:||DBASIC);
DBMS_OUTPUT.PUT_LINE(DESIGNATION
:||DDESIGN);
END;
/
SET SERVEROUTPUT OFF

11/29/15

Lecture 3

PL/SQL Constructs (IF)


IF Statement
IF <Condition> THEN
<Action>
END IF;

IF Statement
IF <Condition> THEN
<Action>
ELSE
<Action>

11/29/15

Lecture 3

Nested IF Statement
IF <Condition> THEN
<Action>
ELSIF <Condition> THEN
<Action>
ELSIF <Condition> THEN
<Action>
END IF;

10

PL/SQL Constructs (FOR)


FOR Statement
FOR <Variable> IN <Startnumber> .. <Endnumber> LOOP
<Statements>
END LOOP;

Example (create a file to execute FOR loop and display the variable)
SET SERVEROUTPUT ON
BEGIN
DBMS_OUTPUT.PUT_LINE(This is a demo for FOR Loop);
FOR CTR IN 1 .. 5 LOOP
-- The variable CTR neednt be declared
DBMS_OUTPUT.PUT_LINE(Loop Number:||CTR);
END LOOP;
END;
/
SET SERVEROUTPUT OFF

11/29/15

Lecture 3

11

PL/SQL Constructs (LOOP)


LOOP Statement
LOOP
<Statements>
END LOOP;

Example (To demonstrate LOOP Statement)


SET SERVEROUTPUT ON
DECLARE
CTR NUMBER(2):=0;
BEGIN
DBMS_OUTPUT.PUT_LINE(The LOOP loop begins);
LOOP
CTR:=CTR+1;
EXIT WHEN CTR>1;
DBMS_OUTPUT.PUT_LINE(Loop Number:||CTR);
END LOOP;
END;
/
SET SERVEROUTPUT OFF
11/29/15

Lecture 3

12

PL/SQL Constructs (WHILE)

WHILE Statement (similar to loop construct but the condition is checked in


the beginning)
WHILE <Condition> LOOP
<Statements>
END LOOP;

Example (To demonstrate WHILE Statement)


SET SERVEROUTPUT ON
DECLARE
CTR NUMBER(2):=1;
BEGIN
DBMS_OUTPUT.PUT_LINE(The WHILE loop begins);
WHILE CTR <=10 LOOP
DBMS_OUTPUT.PUT_LINE(Loop Number:||CTR);
CTR:=CTR+1;
END LOOP;
END;
/
SET SERVEROUTPUT OFF
11/29/15

Lecture 3

13

Cursors

Cursors are used when the SQL select statement is expected to return
more than one row
Cursor is a buffer which will store the results of the recent query

A cursor must be declared and its definition contains the query


It must be declared in the DECLARE section of the program
Cursors must be opened before processing and closed after
processing

11/29/15

Lecture 3

14

Cursor

Syntax
CURSOR <Cursorname> IS <SELECT Statement>;

Example
CURSOR CUR_SAL IS SELECT EMPNO, BASIC FROM SALARY WHERE BASIC > 2000;

Syntax to Open the Cursor


OPEN <Cursorname>

Syntax to Store data in the Cursor


FETCH <Cursorname> INTO <Var1>, <Var2>,, <Varn>
or
FETCH <Cursorname> INTO <RecordName>

Syntax to Close the Cursor


CLOSE <Cursorname>

11/29/15

Lecture 3

15

Cursor Attributes
There are four Cursor Attributes used to provide information
on the status of the cursor

%NOTFOUND
To determine if a row was retrieved. Use after FETCH
NOTFOUND is TRUE if a row was not retrieved
NOTFOUND is FALSE if a row was retrieved

%FOUND
To determine if a row was retrieved. Use after FETCH

%ROWCOUNT
ROWCOUNT is zero when the cursor is opened
ROWCOUNT returns the number of rows retrieved
%ISOPEN
To determine if a Cursor is open
ISOPEN is TRUE if a cursor is open
ISOPEN is FALSE if a cursor is not open

11/29/15

Lecture 3

16

Cursor Demonstration

Write a code to display no, name and basic of 3 highest paid employees
--To display no, name and basic of 3 highest paid employees
SET SERVEROUTPUT ON
DECLARE
ENO SALARY.EMP_NO%TYPE;
ENAME EMP.EMP_NAME%TYPE;
EBASIC SALARY.BASIC%TYPE;
CURSOR CUR_SAL IS SELECT DISTINCT SALARY.EMP_NO, EMP.EMP_NAME, SALARY.BASIC
FROM SALARY, EMP
WHERE SALARY.EMP_NO = EMP.EMP_NO
ORDER BY BASIC DESC;
BEGIN
OPEN CUR_SAL;
LOOP
FETCH CUR_SAL INTO ENO, ENAME, EBASIC;
EXIT WHEN CUR_SAL%NOTFOUND;
EXIT WHEN (CUR_SAL%ROWCOUNT>3);
DBMS_OUTPUT.PUT_LINE(ENO|| ||ENAME|| ||EBASIC);
END LOOP
CLOSE CUR_SAL;
END;
/
SET SERVEROUTPUT OFF

11/29/15

Lecture 3

17

Triggers
A PL/SQL code that defines some action that the database
should take when some database related events occurs
Triggers are executed when a DML command(Insert, Delete, Update)
is performed on the table for which the trigger is written
Triggers are executed automatically
CREATE TRIGGER Privilege (its a part of Resource role) is
required for a user to create a trigger
Usage

To enforce rules that cannot be coded through Referential Integrity


To enforce certain business rules (validation ) in an application
To maintain an audit of changes made to data
Derive column values

There are AFTER and BEFORE Triggers

11/29/15

Lecture 3

18

Triggers

Syntax
CREATE [or REPLACE ] TRIGGER <Trigger_name>
[BEFORE/AFTER]
[DELETE/INSERT/UPDATE] [of column]
ON [user]. Table
[FOR EACH ROW]
[WHEN <condition>]
[PL/SQL Block]
..
..

11/29/15

Lecture 3

19

Triggers
Trigger will be
fired for each row
of action
otherwise for
each statement
only

example:

Create Trigger UPDATESAL


Before update on salary
For each row
Begin
Insert into salaryaud values(:old.emp_no, :old.basic, :old.commision,
:old.deduction);
end;
/

Triggers can be many for a single table but only one of each
type (update, delete or insert)
Triggers cannot include COMMIT, ROLLBACK, SAVEPOINT

11/29/15

Lecture 3

20

Procedures
Stored database objects that use a
PL/SQL statement(s) in their body
CREATE
CREATEOR
ORREPLACE
REPLACE
PROCEDURE
PROCEDURE procedure_name
procedure_name(( parameters
parameters)) IS
IS
BEGIN
BEGIN
procedure_body
procedure_body
END;
END;

DROP
DROPPROCEDURE
PROCEDURE<my-proc>;
<my-proc>;
21

Example procedure
Define the procedure:
CREATE
CREATEPROCEDURE
PROCEDUREtestProcedure
testProcedureAS
AS
BEGIN
BEGIN
INSERT
INSERTINTO
INTOStudent
Student VALUES
VALUES(5,
(5, 'Joe');
'Joe');
END;
END;

Now we can call it:


EXEC
EXECtestProcedure
testProcedure

or
CALL
CALLtestProcedure
testProcedure

22

Example procedure
CREATE OR REPLACE PROCEDURE HELLO IS
BEGIN
DBMS_OUTPUT.PUT_LINE(Hello World);
END;

11/29/15

Lecture 3

23

Procedure with parameters


CREATE
CREATEOR
ORREPLACE
REPLACE
PROCEDURE
PROCEDUREDISPN
DISPN(N
(NINT)
INT) IS
IS
BEGIN
BEGIN
DBMS_OUTPUT.PUT_LINE(N
DBMS_OUTPUT.PUT_LINE(Nisis ||||N);
N);
END;
END;

Which
Whichififyou
you call,
call, will
will promptly
promptly display:
display:
SQL>
SQL> CALL
CALLDISPN(1234567891);
DISPN(1234567891);
NN isis 1234567891
1234567891
24

Multiple Parameters
You can also have multiple parameters. For example, you can
accept A and B and display their sum and product.

CREATE
CREATE OR
OR REPLACE
REPLACE
PROCEDURE
PROCEDURE DISP_AB
DISP_AB (A
(AINT,
INT,BB INT)
INT) IS
IS
BEGIN
BEGIN
DBMS_OUTPUT.PUT_LINE(A
DBMS_OUTPUT.PUT_LINE(A++ BB == |||| (A
(A++ B));
B));
DBMS_OUTPUT.PUT_LINE(A
DBMS_OUTPUT.PUT_LINE(A** BB == |||| (A
(A** B));
B));
END;
END;

25

Functions
Like procedures but with return values
CREATE
CREATE OR
OR REPLACE
REPLACE
FUNCTION
FUNCTION function_name
function_name (function_params)
(function_params)
RETURN
RETURN return_type
return_type IS
IS
BEGIN
BEGIN
function_body
function_body
RETURN
RETURN something_of_return_type;
something_of_return_type;
END;
END;
DROP
DROP FUNCTION
FUNCTION <functionName>;
<functionName>;

Big strength: can be called from SQL


itself
26

Function example
CREATE
CREATEOR
ORREPLACE
REPLACE
FUNCTION
FUNCTIONADD_TWO
ADD_TWO(A
(AINT,B
INT,BINT)
INT)RETURN
RETURNINT
INTIS
IS
BEGIN
BEGIN
RETURN
RETURN(A
(A++B);
B);
END;
END;
To
Torun
runit,it,well
wellwrite
writeaasmall
smallpiece
pieceof
ofcode
codethat
thatcalls
callsthis:
this:
BEGIN
BEGIN
DBMS_OUTPUT.PUT_LINE(RESULT
DBMS_OUTPUT.PUT_LINE(RESULTIS:
IS: ||||ADD_TWO(12,34));
ADD_TWO(12,34));
END;
END;
Which
Whichgives
givesthe
theoutput:
output:
RESULT
RESULTIS:
IS:46
46

27

You might also like