0% found this document useful (0 votes)
8 views64 pages

PL/SQL

Uploaded by

gangamanimajhi7
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)
8 views64 pages

PL/SQL

Uploaded by

gangamanimajhi7
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/ 64

PL/SQL

Overview of PL/SQL
• With PL/SQL, you can use SQL statements to
manipulate ORACLE data and flow-of-control
statements to process the data.
• can declare constants and variables, define
subprograms (procedures and functions), and
trap runtime errors.
• PL/SQL combines the data manipulating
power of SQL with the data processing power
of procedural languages.
Overview of PL/SQL cont..
• PL/SQL is a block-structured language.

• Basic units (procedures, functions, and anonymous


blocks) thatmake up a PL/SQL program are logical
blocks, which can contain any number of nested sub-
blocks.

DECLARE
-- Declarations
BEGIN
-- Statements
EXCEPTION
-- Handlers
• END;
The PL/SQL Block
• All PL/SQL programs are made up of Blocks. A
• PL/SQL program MUST contain at least one block.
A
• Block is made up of PL/SQL statements enclosed
• within the keywords, BEGIN and END, for
example:-
• BEGIN
• INSERT INTO table (col) VALUES ('XX');
• END;
The PL/SQL Block
Multiple Blocks
• A PL/SQL program can consist of several in-line
• blocks, for example:-
• DECLARE
• v_number NUMBER;
• BEGIN
• v_number := 10;
• EXCEPTION
• WHEN OTHERS THEN
• DBMS_OUTPUT.put_line('Error 1');
• END;
• BEGIN
• v_number := 20;
• EXCEPTION
• WHEN OTHERS THEN
• DBMS_OUTPUT.put_line('Error 2');
• END;
• BEGIN
• v_number := 20;
• EXCEPTION
• WHEN OTHERS THEN
• DBMS_OUTPUT.put_line('Error 3');
The PL/SQL Block
Multiple Blocks cont..
The PL/SQL Block
Nested Blocks
The PL/SQL Block
Block Types

• There are several types of blocks:-


• • Anonymous Block - Seen in the examples so
• far. These blocks have no name and are generally
• stored in a host file or entered directly into
• SQL*Plus and executed just once.
• • Named Blocks - Very much the same as an
• Anonymous Block except the block is given a
• label.
• • Subprograms - Packages, Procedures and
• Functions are blocks of code stored within the
• database. These blocks are executed via a
• specific call via the block name.
• • Triggers - These are also named blocks that are
• stored within the database. Triggers are executed
• implicitly whenever the triggering event occurs.
The PL/SQL Block
Block Types - Examples

• Named Blocks - Name is enclosed in << and >>:-


• <<my_block>>
• DECLARE
• v_number := 10;
• BEGIN
• v_number := v_number * 10;
• END;
• Subprograms - Function to square a number:-
• CREATE OR REPLACE FUNCTION square(p_number IN NUMBER)
• IS
• BEGIN
• RETURN p_number * 2;
• END;
• Triggers - These are also named blocks that fire in
• response to a database event.
• CREATE OR REPLACE TRIGGER audit
• BEFORE DELETE ON items
• FOR EACH ROW
• BEGIN
• INSERT INTO audit_table(item,description)
• VALUES(:old.item,:old.description);
• END;
Scope and Visibility
The block in which an object is declared, including

any nested blocks is the scope on an object .


Advantages of PL/SQL

• ■ Support for SQL


• ■ Support for object-oriented programming
• ■ Better performance
• ■ Higher productivity
• ■ Full portability
• ■ Tight integration with Oracle
• ■ Tight security
Overview of Predefined PL/SQL Datatypes
• A scalar type has no internal components. It holds a single value,
such as a number or
• character string.
• A composite type has internal components that can be
manipulated individually, such
• as the elements of an array.
• A reference type holds values, called pointers, that designate
other program items.
• A LOB type holds values, called lob locators, that specify the
location of large objects,
• such as text blocks or graphic images, that are stored separately
from other database data.
Overview of Predefined PL/SQL Datatypes
PL/SQL Architecture
PL/SQL Arch …

• PL/SQL Engine
• It is a separator,which splits the SQL and PL/SQL
statements.PL/SQL block comprises of SQL &PL
commands are submitted as one request.PL/SQL
engine split the block and sends appropriated
commands to the corresponding units.SQL
evaluator will handle SQL statements(available on
the server side).PL Evaulator to handle PL
commands.Engine can reside either in client side or
in the server side.
PL/SQL Arch …
Using DEFAULT
• You can use the keyword DEFAULT instead of the assignment operator to initialize
• variables. For example, the declaration
• blood_type CHAR := 'O';
• can be rewritten as follows:
• blood_type CHAR DEFAULT 'O';
• Use DEFAULT for variables that have a typical value. Use the assignment operator
for
• variables (such as counters and accumulators) that have no typical value. For
example:
• hours_worked INTEGER DEFAULT 40;
• employee_count INTEGER := 0;
• You can also use DEFAULT to initialize subprogram parameters, cursor parameters,
• and fields in a user-defined record.
Using NOT NULL
• Besides assigning an initial value, declarations
can impose the NOT NULL constraint:
• DECLARE
• acct_id INTEGER(4) NOT NULL := 9999;
• You cannot assign nulls to a variable defined as
NOT NULL. If you try, PL/SQL raises
• the predefined exception VALUE_ERROR.
• The NOT NULL constraint must be followed by
an initialization clause
Using the %TYPE Attribute
• The %TYPE attribute provides the datatype of a
variable or database column. In the
• following example, %TYPE provides the
datatype of a variable:
• DECLARE
• credit NUMBER(7,2);
• debit credit%TYPE;
• %TYPE variables do not inherit the NOT NULL
column constraint
PL/SQL Records

• What are records ?


• Records are another type of datatypes which
oracle allows to be defined as a placeholder.
• Records are composite datatypes, which
means it is a combination of different scalar
datatypes like char, varchar, number etc.
• Each scalar data types in the record holds a
value.
PL/SQL Records Cont…

• A record can be visualized as a row of data.


• It can contain all the contents of a row.

• Declaring a record:
• TYPE record_type_name IS RECORD
(first_col_name column_datatype,
second_col_name column_datatype);
What are records Cont…

• DECLARE TYPE employee_type IS RECORD


(employee_id number(5),
employee_first_name varchar2(25),
employee_last_name employee.last_name
%type, employee_dept employee.dept
%type); employee_salary employee.salary
%type; employee_rec employee_type;
Pl/SQL Records
• Initialize value to records type
• record_name.col_name := value;
Using the %ROWTYPE Attribute
• The %ROWTYPE attribute provides a record type that represents a
row in a table (or
• view). The record can store an entire row of data selected from the
table, or fetched
• DECLARE
• -- %ROWTYPE can include all the columns in a table...
• emp_rec employees%ROWTYPE;
• -- ...or a subset of the columns, based on a cursor.
• CURSOR c1 IS
• SELECT department_id, department_name FROM departments;
• dept_rec c1%ROWTYPE;
• -- Could even make a %ROWTYPE with columns from multiple tables.
Using the %ROWTYPE Attribute cont…

• The advantages of declaring the record as a ROWTYPE are


• 1) You do not need to explicitly declare variables for all the columns in a table.
2) If you alter the column specification in the database table, you do not need
to update the code.
Disadvantages …
• 1) When u create a record as a ROWTYPE, fields
will be created for all the columns in the table
and memory will be used to create the datatype
for all the fields. So use ROWTYPE only when you
are using all the columns of the table in the
program.
Restrictions on Declarations
• PL/SQL does not allow forward references. You
must declare a variable or constant
• before referencing it in other statements,
including other declarative statements.
Overview of PL/SQL Control Structures
• SELECTION
• ITERATION
• SEQUENCE
• IF condition THEN
• sequence_of_statements
• END IF;
• IF condition THEN
• sequence_of_statements
• END IF;
Using the IF-THEN-ELSE Statement
• The second form of IF statement adds the
keyword ELSE followed by an alternative
• sequence of statements:
• IF condition THEN
• sequence_of_statements1
• ELSE
• sequence_of_statements2
• END IF;
• IF trans_type = 'CR' THEN
• UPDATE accounts SET balance = balance +
credit WHERE ...
• ELSE
• UPDATE accounts SET balance = balance -
debit WHERE ...
• END IF;
Using the IF-THEN-ELSIF Statement
• Sometimes you want to choose between several alternatives.
You can use the keyword
• ELSIF (not ELSEIF or ELSE IF) to introduce additional
conditions:
• IF condition1 THEN
• sequence_of_statements1
• ELSIF condition2 THEN
• sequence_of_statements2
• ELSE
• sequence_of_statements3
• END IF;
Using the IF-THEN-ELSIF Statement

BEGIN
IF sales > 50000 THEN
bonus := 1500;
ELSIF sales > 35000 THEN
bonus := 500;
ELSE
bonus := 100;
END IF;
INSERT INTO payroll VALUES (emp_id, bonus, ...);
END;
Case Statement

• Like the IF statement, the CASE statement


selects one sequence of statements to
execute.
• The CASE statement is more readable and
more efficient. When possible, rewrite lengthy
IF-THEN-ELSIF statements as CASE statements.
• The CASE statement begins with the keyword
CASE. The keyword is followed by a selector.
Case exmp..

• DECLARE
• grade VARCHAR2(12) :='A';
• BEGIN
• CASE grade
• WHEN 'A' THEN dbms_output.put_line('Excellent');
• WHEN 'B' THEN dbms_output.put_line('Very Good');
• WHEN 'C' THEN dbms_output.put_line('Good');
• WHEN 'D' THEN dbms_output.put_line('Fair');
• WHEN 'F' THEN dbms_output.put_line('Poor');
• ELSE dbms_output.put_line('No such grade');
• END CASE;
• * END;
Iterative Statements in PL/SQL

• An iterative control Statements are used when


we want to repeat the execution of one or
more statements for specified number of
times.
• Three types of Iterative statements.
• Simple Loop
• While Loop
• For Loop
Iterative Statements in PL/SQL
• Simple Loop
• A Simple Loop is used when a set of
statements is to be executed at least once
before the loop terminates. An EXIT condition
must be specified in the loop, otherwise the
loop will get into an infinite number of
iterations. When the EXIT condition is satisfied
the process exits from the loop.
• LOOP
• statements;
• EXIT; {or EXIT WHEN condition;}
• END LOOP;
• 1) Initialise a variable before the loop body.
2) Increment the variable in the loop.
3) Use a EXIT WHEN statement to exit from the Loop. If
you use a EXIT statement without WHEN condition,
the statements in the loop is executed only once.
• While Loop
• A WHILE LOOP is used when a set of statements has to be
executed as long as a condition is true. The condition is
evaluated at the beginning of each iteration. The iteration
continues until the condition becomes false.
• The General Syntax to write a WHILE LOOP is:
• WHILE <condition> LOOP statements; END LOOP; Important
steps to follow when executing a while loop:
1) Initialise a variable before the loop body.
2) Increment the variable in the loop.
3) EXIT WHEN statement and EXIT statements can be used in
while loops but it's not done oftenly.
FOR Loop
• A FOR LOOP is used to execute a set of statements for a predetermined number
of times. Iteration occurs between the start and end integer values given. The
counter is always incremented by 1. The loop exits when the counter reachs the
value of the end integer.
• The General Syntax to write a FOR LOOP is:

• FOR counter IN val1..val2 LOOP statements; END LOOP; val1 - Start integer value.
• val2 - End integer value.
• Important steps to follow when executing a while loop:
1) The counter variable is implicitly declared in the declaration section, so it's
not necessary to declare it explicity.
2) The counter variable is incremented by 1 and does not need to be
incremented explicitly.
3) EXIT WHEN statement and EXIT statements can be used in FOR loops but it's
not done oftenly.
CURSOR

• A cursor is a temporary work area created in the


system memory when a SQL statement is
executed. A cursor contains information on a
select statement and the rows of data accessed
by it. This temporary work area is used to store
the data retrieved from the database, and
manipulate this data. A cursor can hold more
than one row, but can process only one row at a
time. The set of rows the cursor holds is called
the active set.
Cursor cont..
• There are two types cursor.
• 1) Implicit Cursors
• 2) Explicit cursors
Cursors cont …
• When you execute DML statements like
DELETE, INSERT, UPDATE and SELECT
statements, implicit statements are created
to process these statements.

• Oracle provides few attributes called as implicit


cursor attributes to check the status of DML
operations. The cursor attributes available are
%FOUND, %NOTFOUND, %ROWCOUNT, and
%ISOPEN.
Cursors cont …
Explicit Cursors
• An explicit cursor is defined in the declaration section of
the PL/SQL Block. It is created on a SELECT Statement
which returns more than one row. We can provide a
suitable name for the cursor.

• E.g.

CURSOR cursor_name IS select_statement;


cursor_name – A suitable name for the cursor.

select_statement – A select query which returns multiple rows.


Explicit Cursors cont …
• How to use Explicit Cursor?

DECLARE the cursor in the declaration section.
• OPEN the cursor in the Execution Section.
• FETCH the data from cursor into PL/SQL
variables or records in the Execution Section.
• CLOSE the cursor in the Execution Section
before you end the PL/SQL Block.
Explicit Cursors cont …
Loops with Explicit Cursors
• DECLARE
CURSOR emp_cur IS
SELECT ename, sal FROM emp;
emp_rec emp_cur%rowtype;

BEGIN
IF NOT emp_cur %ISOPEN THEN
OPEN emp_cur ;
END IF;
LOOP
FETCH emp_cur INTO emp_rec;
EXIT WHEN emp_cur%NOTFOUND;
dbms_output.put_line(emp_cur r.ename || ' ' ||emp_cur.sal || ' ' ||
emp_cur.mgr);
END LOOP;
END;
While Loop with Explicit Cursors

DECLARE

CURSOR emp_cur
IS SELECT ename, sal FROM emp;
emp_rec emp_cur%rowtype;

BEGIN

OPEN emp_cur;

FETCH emp_cur INTO emp_rec;


WHILE emp_cur%FOUND
LOOP
dbms_output.put_line(emp_rec.ename || ' ' ||emp_rec.sal );
FETCH emp_cur INTO emp_rec;
END LOOP;
END;
/
Cursor with a FOR Loop..

• When using FOR LOOP you need not


declare a record or variables to store the
cursor values, need not open, fetch and
close the cursor.
FOR record_name IN cusror_name
LOOP
process the row...
END LOOP;
Cursor with a FOR Loop..

DECLARE
CURSOR emp_cur IS
SELECT ename, sal FROM emp;
BEGIN
FOR emp_rec in emp_cur LOOP
dbms_output.put_line(emp_rec.ename || ' '
||emp_rec.sal);
END LOOP;
END
Passing Parameters

• You can pass parameters to the cursor in a


cursor.
• We can only pass the parameters into
cursors and use them in a query.

• We can only pass the values to the cursors


and can not pass the values out of the
cursor through parameters.

• Only data type is defined not length.


• The mode of the parameters can only be
IN.

• Cursors becomes more reusable with


cursors parameters.

• Default values can be assigned to cursor


parameters.

• The Scope of the cursor paramters is local


to the cursor.
Example …
• DECLARE
CURSOR emp_cur(v_deptno NUMBER) IS
SELECT ename, sal FROM emp where deptno=v_deptno;
emp_rec emp_cur%rowtype;
BEGIN
OPEN emp_cur(30);
LOOP
FETCH emp_cur INTO emp_rec;
EXIT WHEN emp_cur%NOTFOUND;
dbms_output.put_line(emp_rec.ename );
END LOOP;
END;
Cursor Using For Subquery
BEGIN
FOR emp_rec in (SELECT * FROM EMP)
LOOP
dbms_output.put_line(emp_rec.ename
|| ' ' ||emp_rec.hiredate || ' ' ||
emp_rec.sal);
END LOOP;
END
;
/
Cursor with UPDATE
• When a table is locked, all rows of the table are
locked.
• No other user can modify the table.
• It locks the rows until final execution stops.
• The user can use select for update NOWAIT to
stop access requests and get control once again if
it is already locked.
• When tables are locked then user used NOWAIT
with select… for update statement for processing
on that record of a table.
• He is need not to wait for releasing tables from
lock.
Cursor with Update
• SELECT ename,sal FROM emp WHERE deptno=30;

• DECLARE
• CURSOR emp_cur IS
• SELECT sal FROM emp
• WHERE deptno=10
• FOR UPDATE OF sal NOWAIT ;
• emp_record emp_cur%rowtype;
• BEGIN
• FOR emp_record in emp_cur
• LOOP
• UPDATE emp
• set sal = 1200
• WHERE CURRENT OF emp_cur;
• END LOOP;
• END;
• /SELECT ename,sal FROM emp WHERE deptno=30;
Cont …
• The Where Current of clause in UPDATE and Delete
statement states that the most recent row fetched
from the table should be updated or deleted.
• It must has to be declare with cursor and with FOR
UPDATE.
• When the session opens a cursor with the FOR
UPDATE clause, all rows in the return seet will hold
row level exclusive locks. Other sessions can only
query the rows but they can not update, delete or
select with FOR UPDATE
REF Cursor
• A ref cursor in Oracle PL/SQL is much like an
ordinary PL/SQL cursor in that it acts as a
pointer to the result set of the cursor with
which it is associated. However, the difference
is that a ref cursor can be assigned to different
result sets whereas a cursor is always
associated with the same result set. Cursors
and ref cursors are not interchangeable.
• A Ref cursor is a variable, defined as a cursor type which will point or reference result set.
The advantages of ref cursor has over a plain cursor is that it can be passed as variable to
procedure or functions.
• The ref cursor cab assigned to the ref cursor variables.
• The ref cursor variable is not a cursor, but a variable that points to a cursor.
• Before assigning a ref cursor, you must declare a cursor type must be declared.
• The “Ref Cursor” weak typed cursor variable because it doesn’t define data type which data
type will return.
Cont….
• The real purpose of ref cursors is to be able to share cursors and result sets between the client
and the Oracle server or between different subroutines. For example you might open a cursor
in an Oracle Forms client and then continue working with the cursor on the server or you might
open a cursor in say a Java program and then continue working with it in a PL/SQL stored
procedure.

Ref cursors also come in two variants: strongly typed and weakly typed depending on how likely
you are (or want to) reuse a cursor variable. Weak ref cursor types can be associated with any
query whereas strong ref cursor types can only be associated with cursors of the same type.
• The most important benefit of the cursor variable is that it provides a mechanism for passing
results of queries (the rows returned by fetches against a cursor) between different PL/SQL
programs -- even between client and server PL/SQL programs. Prior to PL/SQL Release 2.3, you
would have had to fetch all data from the cursor, store it in PL/SQL variables (perhaps a PL/SQL
table), and then pass those variables as arguments. With cursor variables, you simply pass the
reference to that cursor. This improves performance and streamlines your code.
• declare
• type r_cursor is REF CURSOR;
• c_emp r_cursor;
• er emp%rowtype;
• begin
• open c_emp for select * from emp;
• loop
• fetch c_emp into er;
• exit when c_emp%notfound;
• dbms_output.put_line(er.ename || ' - ' || er.sal);
• end loop;
• close c_emp;
• end;
• Usage Restrictions
• The following are restrictions on cursor variable usage.
• 1. Comparison operators cannot be used to test cursor variables for equality, inequality, null, or not null.
• 2. Null cannot be assigned to a cursor variable.
• 3. The value of a cursor variable cannot be stored in a database column.
• 4. Static cursors and cursor variables are not interchangeable. For example, a static cursor cannot be used in an
OPEN FOR statement.

• Cursor variables cannot be declared in a package since they do not have a persistent state.
• You cannot use RPCs (Remote Procedure Calls) to pass cursor variables from one server to another.
• If you pass a cursor variable as a bind or host variable to PL/SQL, you will not be able to fetch from it from within the
server unless you also open it in that same server call.
• The query you associate with a cursor variable in an OPEN-FOR statement cannot use the FOR UPDATE clause.
• You cannot test for cursor variable equality, inequality, or nullity using comparison operators.
• You cannot assign NULLs to a cursor variable.
• Database columns cannot store cursor variable values. You will not be able to use REF CURSOR types to specify
column types in statements to CREATE TABLEs or CREATE VIEWs.
• The elements in a nested table, index-by table, or variable array (VARRAY) cannot store the values of cursor variables.
You will not be able to use REF CURSOR types to specify the element type of a collection.
• Cursor variables cannot be used with dynamic SQL (through use of the DBMS_SQL package).

You might also like