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

PL SQL

Uploaded by

Sayantan Marik
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

PL SQL

Uploaded by

Sayantan Marik
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 60

PL/SQL

PL/SQL-1 1
1
Objectives

• Write your own PL/SQL code using conditional


statements and loop constructs
• Create PL/SQL code with Cursors
• Create PL/SQL code with Exceptions
• Create PL/SQL code with Stored Procedures

-2- INTERNAL
Introduction
Why PL/SQL
• SQL does not have any procedural capabilities such as
looping and branching nor does it have any conditional
checking capabilities vital for data testing before
storage.

• PL/SQL adds to the power of SQL and provides the


user with all the facilities of a programming
environment.

• PL/SQL bridges the gap between database technology


and procedural programming languages.

-3- INTERNAL
Introduction contd..

• Via PL/SQL you can insert, delete, update and retrieve


table data as well as use procedural techniques such
as writing loops or branching to another block of code.

• PL/SQL is really an extension of SQL.

• PL/SQL blocks can contain any number of SQL


statements. It allows you to logically group a number of
SQL statements and pass them to the DBA as a single
block.

• Without PL/SQL, DBA has to process SQL statements


one at a time.

-4- INTERNAL
Introduction contd..

• Via PL/SQL you can insert, delete, update and retrieve


table data as well as use procedural techniques such
as writing loops or branching to another block of code.

• PL/SQL is really an extension of SQL.

• PL/SQL blocks can contain any number of SQL


statements. It allows you to logically group a number of
SQL statements and pass them to the DBA as a single
block.

• Without PL/SQL, DBA has to process SQL statements


one at a time.

-5- INTERNAL
PL/SQL Block
• A standard PL/SQL code segment is called a block. A
standard PL/SQL block is made up of three sections.

1. Declaration Section is meant for declaring


variables and constants.

1. Executable Statements Section is meant for


manipulating objects during execution.

1. Exception Handling Section - any errors or


exceptions raised during execution of the PL/SQL
block are handled here.

-6- INTERNAL
Block Structure

DECLARE
<declaration of variables/constants/cursors/records/exceptions>
BEGIN
<executable statements>
---
[EXCEPTION]
WHEN <exception1> THEN
----
WHEN <exception2> THEN

WHEN OTHERS THEN
---
END;

-7- INTERNAL
Scalar Data Types

Hold a single value


Have no internal components

TRUE 25-JAN-01

The soul of the lazy man


desires, and he has nothing;
but the soul of the diligent
shall be made rich.

256120.08 Atlanta

INTERNAL
Base Scalar Data Types

CHAR [(maximum_length)]
VARCHAR2 (maximum_length)
NUMBER [(precision, scale)]
BINARY_INTEGER
PLS_INTEGER
BOOLEAN
BINARY_FLOAT
BINARY_DOUBLE

INTERNAL
Base Scalar Data Types

DATE
TIMESTAMP
TIMESTAMP WITH TIME ZONE
TIMESTAMP WITH LOCAL TIME ZONE
INTERVAL YEAR TO MONTH
INTERVAL DAY TO SECOND

INTERNAL
LOB Data Type Variables

Book
(CLOB)

Photo
(BLOB)

Movie
(BFILE)

NCLOB

INTERNAL
Variables and Constants
Variables
• A PL/SQL variable can be used either in SQL or
PL/SQL statements provided it is declared before
referencing it.
• DECLARE V_NUMBER ;
Constants
• Declaration of a constant is similar to the declaration of
a variable except that the keyword CONSTANT must
be added and a value must be assigned.

• DECLARE V_pi constant number := 3.141592654;

- 12
INTERNAL
-
Declaration Using Attributes

%TYPE attribute

• This attribute provides the data type of a variable,


constant or column.

• %TYPE attribute is useful while declaring a variable


that has same data type as a table column.

- 13
INTERNAL
-
DECLARE
V_ENAME EMP.ENAME%TYPE;
AMT NUMBER(5,2);
V_AMT AMT%TYPE;
BEGIN
---
---

- 14
INTERNAL
-
Declaration Using Attributes contd..

%ROWTYPE attribute
• This attribute is used to declare a variable to be a
record having the same structure as a row in a table.

• The row is represented as a record and its fields have


the same names and data types as the columns in the
table or view.

DECLARE
EREC EMP%ROWTYPE;
BEGIN

- 15
INTERNAL
-
Operators

Logical:

• AND
• OR
• NOT

- 16
INTERNAL
-
Conditional Control

if (condition) then if (condition) then


statements statements
else elsif (condition) then
statements statements
end if; else
statements
end if;

- 17
INTERNAL
-
Conditional Control

DECLARE
AGE NUMBER:=8
SEX CHAR(1):='M';
BEGIN
IF AGE<12 AND SEX='M' THEN
DBMS_OUTPUT.PUT_LINE('MALE CHILD');
ELSIF AGE<12 AND SEX='F' THEN
DBMS_OUTPUT.PUT_LINE('FEMALE CHILD');
ELSE
DBMS_OUTPUT.PUT_LINE('NOT A CHILD');
END IF;
END;

- 18
INTERNAL
-
Iterative Control

1. Endless Loop

LOOP
statements
..........
END LOOP;

LOOP and END LOOP are the keywords.

- 19
INTERNAL
-
Iterative Control contd..

2. For Loop

FOR i IN 1..10
LOOP
statements
.........
END LOOP;

- FOR loop index is implicitly declared to be of data


type NUMBER.
- CONTINUE
- EXIT [WHEN <condition>]

- 20
INTERNAL
-
Iterative Control contd..

3. While Loop

WHILE (condition)
LOOP
.........
statements
.........
END LOOP;

- 21
INTERNAL
-
Iterative Control contd..

SET SERVEROUT ON
DECLARE
S NUMBER:=0;
BEGIN
FOR I IN 1..10
LOOP
S:=S+I;
END LOOP;
DBMS_OUTPUT.PUT_LINE('SUM IS '||S);
END;

- 22
INTERNAL
-
Iterative Control contd..

SET SERVEROUT ON
DECLARE
I NUMBER:=0;
S NUMBER:=0;
BEGIN
WHILE(I<=10)
LOOP
S:=S+I;
I:=I+1;
END LOOP;
DBMS_OUTPUT.PUT_LINE('SUM IS '||S);
END;

- 23
INTERNAL
-
SQL Statements in PL/SQL

• Retrieve a row from the database by using the


SELECT command.
• Make changes to rows in the database by using
DML commands.
• Control a transaction with the COMMIT,
ROLLBACK, or SAVEPOINT command.

INTERNAL
SELECT Statements in PL/SQL

Retrieve data from the database with a SELECT


statement.
Syntax:
SELECT select_list
INTO {variable_name[, variable_name]...
| record_name}
FROM table
[WHERE condition];

INTERNAL
SELECT Statements in PL/SQL

• The INTO clause is required.


• Queries must return only one row.

Example:
DECLARE
v_fname VARCHAR2(25);
BEGIN
SELECT first_name INTO v_fname
FROM employees WHERE employee_id=200;
DBMS_OUTPUT.PUT_LINE(' First Name is : '||v_fname);
END;
/

INTERNAL
Retrieving Data in PL/SQL
Retrieve hire_date and salary for the
specified employee.

Example:
DECLARE
v_emp_hiredate employees.hire_date%TYPE;
v_emp_salary employees.salary%TYPE;
BEGIN
SELECT hire_date, salary
INTO v_emp_hiredate, v_emp_salary
FROM employees
WHERE employee_id = 100;
END;
/

INTERNAL
Retrieving Data in PL/SQL
Return the sum of the salaries for all the
employees in the specified department.
Example:

DECLARE
v_sum_sal NUMBER(10,2);
v_deptno NUMBER NOT NULL := 60;
BEGIN
SELECT SUM(salary) -- group function
INTO v_sum_sal FROM employees
WHERE department_id = v_deptno;
DBMS_OUTPUT.PUT_LINE ('The sum of salary is ' || v_sum_sal);
END;

INTERNAL
Using PL/SQL to Manipulate Data

Make changes to database tables by using DML


commands:
• INSERT
• UPDATE DELETE
• DELETE

INSERT

MERGE
UPDATE

INTERNAL
Inserting Data

Add new employee information to the EMPLOYEES table.

Example:
BEGIN
INSERT INTO employees
(employee_id, first_name, last_name, email,
hire_date, job_id, salary)
VALUES(employees_seq.NEXTVAL, 'Ruth', 'Cores',
'RCORES',CURRENT_DATE, 'AD_ASST', 4000);
END;
/

INTERNAL
Updating Data

Increase the salary of all employees who are stock clerks.

Example:
DECLARE
sal_increase employees.salary%TYPE := 800;
BEGIN
UPDATE employees
SET salary = salary + sal_increase
WHERE job_id = 'ST_CLERK';
END;
/

INTERNAL
Deleting Data

Delete rows that belong to department 10 from the


employees table.

Example:
DECLARE
deptno employees.department_id%TYPE := 10;
BEGIN
DELETE FROM employees
WHERE department_id = deptno;
END;
/

INTERNAL
Cursors

• A cursor is a pointer to the private memory area


allocated by the Oracle server.
• A cursor is used to handle the result set of a SELECT
statement.
• There are two types of cursors:
– Implicit: Created and managed internally by the
Oracle server to process SQL statements
– Explicit: Declared explicitly by the programmer

INTERNAL
Implicit Cursors(SQL Cursor)

• Oracle implicitly opens a cursor to process each SQL


statement not associated with an explicitly declared
cursor.

• PL/SQL lets you refer to the most recent implicit


cursor as the "SQL" cursor.

• The values of cursor attributes always refer to the


most recently executed SQL statement, wherever that
statement appears.

- 34
INTERNAL
-
SQL Cursor Attributes for Implicit Cursors

Using SQL cursor attributes, you can test the outcome of


your SQL statements.
SQL%FOUND Boolean attribute that evaluates to TRUE if the
most recent SQL statement returned at least one
row

SQL%NOTFOUND Boolean attribute that evaluates to TRUE if


the most recent SQL statement did not
return even one row

SQL%ROWCOUNT An integer value that represents the number of


rows affected by the most recent SQL statement

INTERNAL
Explicit Cursors
• The set of rows returned by a multirow query is called
the "active set."

• An explicit cursor points to the current row in the


active set.

• Multirow query processing is somewhat like file


processing.

• Likewise, a PL/SQL program opens a cursor to


process rows returned by a query, then at the end,
closes the cursor.

- 36
INTERNAL
-
Explicit Cursors contd..

OPEN Statement

• The OPEN statement executes the query associated


with an explicitly declared cursor.

• OPENing the cursor executes the query and identifies


the active set, which consists of all rows that meet the
query search criteria.

• For cursors declared using the FOR UPDATE Clause,


the OPEN statement also locks those rows.

- 37
INTERNAL
-
Explicit Cursors contd..

FETCH Statement
• The FETCH statement retrieves the rows in the active
set one at a time.

• Each time FETCH is executed, the cursor advances


to the next row in the active set.

• An example of the FETCH statement follows:

FETCH c1 INTO my_empno, my_ename,


my_deptno;

- 38
INTERNAL
-
Explicit Cursors contd..

CLOSE Statement

• The CLOSE statement disables the cursor, and the


active set becomes undefined. An example of the
CLOSE statement follows:

CLOSE c1;

• Any other operation on a closed cursor raises the


predefined exception INVALID_CURSOR.

- 39
INTERNAL
-
Explicit Cursors contd..
Fetching data with cursor
DECLARE
CURSOR C1 IS SELECT * FROM EMPLOYEE;
EMPROW EMPLOYEE%ROWTYPE;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO EMPROW;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('NAME ' || EMPROW.ENAME||'
JOB '||EMPROW.DESIG);
END LOOP;
CLOSE C1;
END;
/
cursor1
- 40
INTERNAL
-
Cursor Attributes
• Each cursor that you explicitly define has four
attributes: %NOTFOUND, %FOUND,
%ROWCOUNT, and %ISOPEN.

• The SQL implicit cursor has the same four attributes.


When appended to the cursor name (SQL), these
attributes let you access information about the most
recently executed INSERT, UPDATE, DELETE, or
SELECT INTO statement.

• You can use cursor attributes in procedural


statements but not in SQL statements.

- 41
INTERNAL
-
%ISOPEN Attribute contd..

Explicit Cursors and %ISOPEN


Attribute
• %ISOPEN evaluates to TRUE if its cursor is open;
otherwise, %ISOPEN evaluates to FALSE.

• In this example, you use %ISOPEN to select an action:

IF c1%ISOPEN THEN -- cursor is open


...
ELSE -- cursor is closed, so open it
OPEN c1;
END IF;

- 42
INTERNAL
-
Exceptions

• PL/SQL makes it easy to detect and process


predefined and user-defined error conditions called
"exceptions."

• When an error occurs, an exception is raised.

• To handle raised exceptions, you write separate


routines called "exception handlers."

• Predefined exceptions are raised implicitly by the


runtime system.

- 44
INTERNAL
-
Declaring Exceptions

• You declare an exception by introducing its name,


followed by the keyword EXCEPTION.

• Exception and variable declarations are similar.

• But, an exception is an error condition, not an object.

• Unlike variables, exceptions cannot appear in


assignment statements or SQL statements.

- 45
INTERNAL
-
Exception Handlers

• When an exception is raised, normal execution of your


PL/SQL block or subprogram stops and control
transfers to its exception-handling part.

• To catch raised exceptions, you must write exception


handlers.

• The optional OTHERS exception handler, which is


always the last handler in a block or subprogram, acts
as the handler for all exceptions not named
specifically.

- 46
INTERNAL
-
Exception Handlers contd..

• If any of the exceptions in the list is raised, the


associated sequence of statements is executed.

• You can have any number of exception handlers, and


each handler can associate a list of exceptions with a
sequence of statements.

• However, an exception name can appear only once in


the exception-handling part of a PL/SQL block or
subprogram.

- 47
INTERNAL
-
Predefined Exceptions

• An internal exception is raised implicitly whenever a


PL/SQL program violates an Oracle rule or exceeds a
system-dependent limit.

• Every Oracle error has a number, but exceptions must


be handled by name. So, PL/SQL predefines some
common Oracle errors as exceptions.

• PL/SQL declares predefined exceptions globally in


package STANDARD, which defines the PL/SQL
environment.

- 48
INTERNAL
-
Predefined Exceptions

DECLARE
EMPNO NUMBER:=555;
VENAME EMPLOYEE.ENAME%TYPE;
VJOB EMPLOYEE.DESIG%TYPE;
BEGIN
SELECT ENAME,DESIG INTO VENAME,VJOB FROM EMPLOYEE
WHERE ENO=EMPNO;
DBMS_OUTPUT.PUT_LINE ('NAME ' || VENAME||' JOB '||VJOB);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('NO EMPLOYEE WITH THE GIVEN
NUMBER');
END;
/
EXCP1

- 49
INTERNAL
-
Predefined Exceptions
Sno Exception Sno Exception
1 ACCESS_INTO_NULL 12 ROWTYPE_MISMATCH
2 CASE_NOT_FOUND 13 SELF_IS_NULL
3 COLLECTION_IS_NULL 14 STORAGE_ERROR
4 CURSOR_ALREADY_OPEN 15 SUBSCRIPT_BEYOND_COUNT
5 DUP_VAL_ON_INDEX 16 SUBSCRIPT_OUTSIDE_LIMIT
6 INVALID_CURSOR 17 SYS_INVALID_ROWID
7 INVALID_NUMBER 18 TIMEOUT_ON_RESOURCE
8 LOGIN_DENIED 19 TOO_MANY_ROWS
9 NO_DATA_FOUND 20 VALUE_ERROR
10 NOT_LOGGED_ON 21 ZERO_DIVIDE
11 PROGRAM_ERROR

INTERNAL
Introduction to Procedures

• You can store PL/SQL code in the Oracle database


with the RDBMS Procedural Database Extension.

• If the procedural object will be in another user's


schema, then you must have CREATE ANY
PROCEDURE system privilege.

- 51
INTERNAL
-
Introduction to procedures contd..

CREATE OR REPLACE PROCEDURE stucourse(PSNO


NUMBER) IS
VCNAME VARCHAR2(20);
BEGIN
SELECT CNAME INTO VCNAME FROM STUDENT
S,COURSE C WHERE S.CID=C.COURSEID AND
S.SNO=PSNO;
DBMS_OUTPUT.PUT_LINE('COURSE OF THE
STUDENT IS '||VCNAME);
END;
/
SQL>EXECUTE stucourse(1);
STUCOURSE

- 52
INTERNAL
-
Introduction to procedures contd..

To call a procedure from an anonymous block

BEGIN
STUCOURSE(1);
END;
/

- 53
INTERNAL
-
Introduction to Procedures contd..

Executing Procedures
• The syntax used to execute a procedure depends on
the environment from which the procedure is called.

• From within SQLPLUS, a procedure can be executed


by the execute command, followed by the procedure
name.

• The preceding example executes the STUCOURSE


procedure, passing to it the value student id 1.

- 54
INTERNAL
-
Introduction to procedures contd..

To call the get_course procedure from an anonymous block


DECLARE
VCNAME VARCHAR2(20);
BEGIN
GET_COURSE(1,VCNAME);
DBMS_OUTPUT.PUT_LINE(VCNAME);
END;
/

- 55
INTERNAL
-
Introduction to Procedures contd..

Dropping a Procedure
• A procedure can be deleted from the database by
using the following command:

DROP PROCEDURE p_itemcodechk ;

- 56
INTERNAL
-
Introduction to Stored Functions

• Functions named PL/SQL blocks that can take


parameters, perform an action and return a value to
the host environment.

• A function can return only one value.

- 57
INTERNAL
-
Introduction to Stored Functions contd..

Creating Function for use

CREATE OR REPLACE FUNCTION GET_MARKS(PSNO


NUMBER) RETURN NUMBER IS
STUROW STUDENT%ROWTYPE;
BEGIN
SELECT * INTO STUROW FROM STUDENT WHERE
SNO=PSNO;
RETURN STUROW.MARKS;
END;
/
get_marks

- 58
INTERNAL
-
Introduction to Stored Functions contd..

Executing functions
• The syntax for executing a function is:

Syntax:
Variable:=function_name(arg_list);
DECLARE
VMARKS NUMBER;
BEGIN
VMARKS:=GET_MARKS(1);
DBMS_OUTPUT.PUT_LINE(VMARKS);
END;
/

- 59
INTERNAL
-
Introduction to Stored Functions contd..

Deleting a Stored Function


• A function can be deleted from the database by using
the following command:

DROP FUNCTION get_marks; ;

- 60
INTERNAL
-
Thank You

INTERNAL

You might also like