0% found this document useful (0 votes)
5 views61 pages

ADBMSUnit5pptx 2023 10 19 12 50 24

The document provides an overview of PL/SQL, a procedural extension for SQL, highlighting its block-structured nature and ability to combine SQL with procedural programming. It covers various aspects including syntax, data types, control structures, transactions, cursors, and locking mechanisms to maintain data integrity. Additionally, it explains the advantages of using PL/SQL for database management and development.

Uploaded by

parthx932
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)
5 views61 pages

ADBMSUnit5pptx 2023 10 19 12 50 24

The document provides an overview of PL/SQL, a procedural extension for SQL, highlighting its block-structured nature and ability to combine SQL with procedural programming. It covers various aspects including syntax, data types, control structures, transactions, cursors, and locking mechanisms to maintain data integrity. Additionally, it explains the advantages of using PL/SQL for database management and development.

Uploaded by

parthx932
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/ 61

DIPLOMA –

COMPUTER
ENGINEERING
Unit 5
Advance
PL / SQL Database
Management
System
(09CE1502)
 PL/SQL is a superset of SQL.

 PL/SQL is a block-structured language that enables


developers to combine the power of SQL with
PL/SQL procedural statements.

 PL/SQL bridges the gap between database technology


and procedural programming language.
 PL/SQL is development tool that not only supports
SQL data manipulation but also provides conditional
checking, branching and looping.
 PL/SQL sends an entire block of SQL statements to
the oracle engine all in one go.
Advantage  It also permits dealing with errors as required and
s of facilitates displaying user friendly messages.
 It allows declaration and use of variables in blocks of
PL/SQL code.
 Applications written in PL/SQL are portable to any
computer hardware and OS.
 Via PL/SQL, all sort of calculation can be done quickly
and efficiently without the use of Oracle engine.
 Syntax
DECLARE
<declarations section>
BEGIN
PL/SQL
<executable command(s)>
Structure EXCEPTION (Optional)
<exception handling>
END;
 Number: for storing numeric data
 Char: for storing character data
 Date: for storing date and time data
 Boolean: for storing True false or NULL data
Datatypes  Number, Char, date data types can have NULL values.
 To allow NOT NULL the variable has to be assigned an
NOT NULL keyword while declaring.
 A variable name must begin with a character and can
be followed by a maximum of 29 other characters.
 Case is insignificant when declaring variable names.
 The assigning of a value to a variable can be done
Variable using the assignment operator := (a colon followed by
an equal to sign)
 Declaring constant variable is same as others.
Constant keyword is used.
DECLARE
variable_name [CONSTANT] datatype [NOT NULL]
[:= initial_value];
BEGIN
Syntax -- PL/SQL statements using the declared variable
END;
 DECLARE
 a integer := 10;
 b integer := 20;
 c integer;
 f real;
 BEGIN
 c := a + b;
EXAMPLE  dbms_output.put_line('Value of c: ' || c);
 f := 70.0/3.0;
 dbms_output.put_line('Value of f: ' || f);
 END;
 /
Value of c: 30
Value of f: 23.333333333333333333

PL/SQL procedure successfully completed.


 The flow of control statements can be classified into
following categories:

Control 1. Conditional Control.


structure 2. Iterative Control.
3. Sequential Control.
 PL/SQL allows the use of IF statement to control the
execution of a block of code.
 In PL/sql IF-THEN-ELSEIF-END IF construct in code
Conditiona blocks allow specifying certain conditions.
l control  Under these conditions a specific block of code should
be executed.
 Syntax:

IF <condition> THEN
<action>
Conditiona ELSEIF < condition > THEN

l control < action >


ELSE
< action >
END IF;
 DECLARE
 a number(3) := 100;
 BEGIN
 IF ( a = 10 ) THEN
 dbms_output.put_line('Value of a is 10' );
 ELSEIF ( a = 20 ) THEN

Conditiona 

dbms_output.put_line('Value of a is 20' );
ELSEIF ( a = 30 ) THEN
l control -  dbms_output.put_line('Value of a is 30' );

Example  ELSE
 dbms_output.put_line('None of the values is matching');
 END IF;
 dbms_output.put_line('Exact value of a is: '|| a );
 END;
 /
None of the values is matching
Exact value of a is: 100

PL/SQL procedure successfully completed.


 It indicates the ability to repeat or skip sections of a
code block.
 A LOOP marks as sequence of statements that has to
be repeated.
Iterative  The keyword LOOP has to be placed before the first
Control statement in the sequence of statements.
 While the keyword END LOOP is placed immediately
after the last statement in the sequence.
 Syntax: Simple loop
Loop
Iterative <sequence of statements>

Control End loop;


 DECLARE
 x number := 10;
 BEGIN Output:
10
 LOOP 20
 30
dbms_output.put_line(x);
40
 x := x + 10;
50
Iterative  IF x > 50 THEN After Exit x is: 60

Control 

exit;
END IF;
PL/SQL procedure successfully
completed.
 END LOOP;
 -- after exit, control resumes here
 dbms_output.put_line('After Exit x is: '
|| x);
 END;
 /
 Syntax: While loop
WHILE <condition>
Iterative Loop

Control <action>
End loop;
 DECLARE
 a number(2) := 10;
 BEGIN
 WHILE a < 15 LOOP
 dbms_output.put_line('value of
a: ' || a);
Iterative  a := a + 1;
Control  END LOOP;
 END;
/
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14

PL/SQL procedure successfully


completed.
 Syntax: For loop
FOR variable IN initial value..final value
Iterative Loop

Control <action>
End loop;
 DECLARE
 a number(2);
 BEGIN
 FOR a in 10 .. 15 LOOP
 dbms_output.put_line('value of a: ' || a);
Iterative  END LOOP;
Control  END;
/
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15

PL/SQL procedure successfully completed.


 THE GOTO statement:
 It changes the flow of control within the PL/SQL
block.
 This statement allows the execution of a section of
Sequential code, which is not in the normal flow of control.
Control  The entry point is marked using << userdefined
name >>.
 GOTO can make use of this name to jump into blocks.
 Syntax:
Sequential GOTO <codeblock name>
Control
 BEGIN
 FOR i IN 1..5 LOOP
 dbms_output.put_line(i);
 IF i=4 THEN
 GOTO label1;
 END IF;
Sequential  END LOOP;
Control  <<label1>>
 DBMS_OUTPUT.PUT_LINE('Row Filled');
 END;
 /
1
2
3
4
Row Filled

PL/SQL procedure successfully


 A database transaction is an atomic unit of work
that may consist of one or more related SQL
statements.
 It is called atomic because the database modifications
brought about by the SQL statements that constitute
a transaction can collectively be either committed, or
PL/SQL roll backed.

Transactio  i.e., made permanent to the database or rolled back


(undone) from the database.
ns  A successfully executed SQL statement and a
committed transaction are not same.
 Even if an SQL statement is executed successfully,
unless the transaction containing the statement is
committed, it can be rolled back.
 A transaction ends when one of the following events
take place −
1. A COMMIT or a ROLLBACK statement is issued.
2. A DDL statement, such as CREATE
TABLE statement, is issued.
3. A DCL statement, such as a GRANT statement, is
PL/SQL issued.
Transactio 4. User disconnects from the database.

ns 5. User exits
the EXIT command.
from SQL*PLUS by issuing

6. SQL*Plus terminates abnormally, a ROLLBACK is


automatically performed.
7. A DML statement fails; in that case a ROLLBACK is
automatically performed.
 A transaction is made permanent by issuing the SQL
command COMMIT.
 Syntax:
COMMIT;
Commit
 EXAMPLE:
SQL>BEGIN
UPDATE emp_information SET
emp_dept='Web Developer‘ WHERE
emp_name='Saulin';
COMMIT;
END;
 Changes made to the database without COMMIT could
be undone using the ROLLBACK command.
 SYNTAX:

Rollback ROLLBACK [TO < savepoint_name>];


 Example:
SQL>DECLARE
emp_id emp.empno%TYPE;

BEGIN
SAVEPOINT dup_found;
Rollback UPDATE emp SET eno=1 WHERE
empname = 'Forbs ross'

EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN

ROLLBACK TO dup_found;
END;
 SAVEPOINT savepoint_names marks the current point
in the processing of a transaction.
 Savepoints let you rollback part of a transaction
instead of the whole transaction.
Savepoint
 SYNTAX:
SAVEPOINT SAVEPOINT_NAME;
 Example:

SQL>DECLARE
emp_id emp.empno%TYPE;

BEGIN
SAVEPOINT dup_found;
Savepoint UPDATE emp SET eno=1 WHERE
empname = 'Forbs ross'

EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN

ROLLBACK TO dup_found;
END;
 When an SQL statement is processed, Oracle creates
a memory area known as context area.
 A cursor is a pointer to this context area.
 It contains all information needed for processing the
Cursor statement.
 In PL/SQL, the context area is controlled by Cursor.
 A cursor contains information on a select statement
and the rows of data accessed by it.
 A cursor is used to referred to a program to fetch and
process the rows returned by the SQL statement, one
at a time.

 There are two types of cursors:


Cursor
1. Implicit Cursors
2. Explicit Cursors
 The implicit cursors are automatically generated by
Oracle while an SQL statement is executed.
 These are created by default to process the
statements when DML statements like INSERT,
Implicit UPDATE, DELETE etc. are executed.
 Oracle provides some attributes known as Implicit
cursor cursor's attributes to check the status of DML
operations.
 Some of them are:
 %FOUND, %NOTFOUND, %ROWCOUNT and %ISOPEN.
S.
Attribute & description
No.

1 %FOUND
Returns TRUE if an INSERT, UPDATE, or DELETE
statement affected one or more rows or a SELECT
INTO statement returned one or more rows.
Otherwise, it returns FALSE.
Implicit 2 %NOTFOUND
The logical opposite of %FOUND. It returns TRUE if an
cursor INSERT, UPDATE, or DELETE statement affected no
rows, or a SELECT INTO statement returned no rows.
Otherwise, it returns FALSE.
3 %ISOPEN
Always returns FALSE for implicit cursors, because
Oracle closes the SQL cursor automatically after
executing its associated SQL statement.
4 %ROWCOUNT
Returns the number of rows affected by an INSERT,
UPDATE, or DELETE statement, or returned by a
SELECT INTO statement.
 The Explicit cursors are defined by the programmers
to gain more control over the context area.
 These cursors should be defined in the declaration
Explicit section of the PL/SQL block.
 It is created on a SELECT statement which returns
Cursor more than one row.
 SYNTAX:

CURSOR cursor_name IS select_statement;


 Declaring the Cursor

CURSOR c_customers IS
SELECT id, name, address FROM customers;
 Opening the Cursor

Explicit OPEN c_customers;

Cursor  Fetching the Cursor

FETCH c_customers INTO c_id, c_name, c_addr;

 Closing the Cursor

CLOSE c_customers;
 Locks in PL/SQL is a way to maintain data integrity
of the database.
 As oracle is a multi-user platform where tables used
in a database acts as a global resource being shared
by multiple users at the same time.
PL/SQL  There is a possibility that the data may become
Security inconsistent due to concurrent processing of data by
multiple user at the same time.
 Therefore, locks play an important role to maintain
concurrency control ensuring data integrity of stored
data in the database.
TYPES OF LOCKS DESCRIPTION
• Applied on a table when
data is being viewed i.e,
the stored data is just
being read.
• Multiple shared locks can
Shared Lock
be applied on the table at
the same time.
Type of • Used in case

locks of SELECT statements.

• Applied on a table when


the data is being changed
i.e, the data is being
written.
• Only one exclusive lock can
Exclusive Lock
be placed at one time.
• Used in case
of INSERT, UPDATE, DELETE
statements.
 Oracle provides the following three levels of Locking.
1. Row level
Level of 2. Page level

locks 3. Table level


 Row Level: It is used when a condition is applied in a
query on a single row(or record) using WHERE clause.

 Page Level: It is used when the condition is applied


Level of in a query on a certain set of data(certain records)
locks using WHERE clause.

 Table Level: It is used when the condition is applied


in a query on the entire table of data(certain records)
using WHERE clause.
 We can also acquire lock on a table by executing the Lock table
statement.
 Following is the syntax:

LOCK TABLE tablename in lock mode


WAIT/NOWAIT;
 Where, Lock mode can be one of the following:

Lock Table EXCLUSIVE: allow the queries on the locked table.


SHARE: allow queries but restricts UPDATE on a table.
statement ROW EXCLUSIVE: allow concurrent access to the table by
multiple users but restricts from locking table in
exclusive or share mode.
SHARE ROW EXCLUSIVE: allow to view the entire table
records but restricts locking the table in share mode and
also restricts UPDATE on a table.
 WAIT indicates that the oracle engine will wait till the resource is
freely available.
 NOWAIT indicates that the oracle engine will not wait for
resource to be available but would rather display the message
to the user that Resource is Busy.
 The PL/SQL stored procedure or simply a procedure is
a PL/SQL block which performs one or more specific
tasks. It is just like procedures in other programming
languages.

 The procedure contains a header and a body.


PL/SQL
 Header: The header contains the name of the
Procedure procedure and the parameters or variables
passed to the procedure.

 Body: The body contains a declaration section,


execution section and exception section similar to
a general PL/SQL block.
 When you want to create a procedure or function, you
have to define parameters .There is three ways to
pass parameters in procedure:
1. IN parameters: This parameter is used for giving
input to the subprograms. It is a read-only variable
inside the subprograms. Their values cannot be
changed inside the subprogram. By default, the
PL/SQL parameters are of IN type.

Procedure 2. OUT parameters: This parameter is used for


getting output from the subprograms. It is a read-
write variable inside the subprograms. Their values
can be changed inside the subprograms.
3. INOUT parameters: This parameter is used for
both giving input and for getting output from the
subprograms. It is a read-write variable inside the
subprograms. Their values can be changed inside
the subprograms.
 Syntax for creating procedure:

CREATE [OR REPLACE] PROCEDURE procedure_name


[ (parameter [,parameter]) ]
AS
[declaration_section]

PL/SQL BEGIN
executable_section
Procedure [EXCEPTION
exception_section]
END [procedure_name];
 In this example, we are going to insert record in user
table. So you need to create user table first.
 Table creation:

create table user(id number(10) primary key,

Create  Now
name
table.
varchar2(100));
write the procedure code to insert record in user

procedure  Procedure Code:


example create or replace procedure "INSERTUSER"
(id IN NUMBER,
name IN VARCHAR2)
AS
begin
insert into user values(id,name);
end;
/
 Let's see the code to call above created procedure.

BEGIN
insertuser(101,'Rahul');
PL/SQL dbms_output.put_line('record inserted su
program ccessfully');
END;
to call /

procedure
PL/SQL
 Syntax for drop procedure
Drop
Procedure DROP PROCEDURE procedure_name;
 The PL/SQL Function is very similar to PL/SQL
Procedure.
 The main difference between procedure and a
PL/SQL function is, a function must always return a value, and
Function on the other hand a procedure may or may not return
a value.
 Except this, all the other things of PL/SQL procedure
are true for PL/SQL function too.
 Syntax to create a function:

CREATE [OR REPLACE] FUNCTION function_name [param


eters]
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
PL/SQL RETURN return_datatype
{IS | AS}
Function BEGIN
< function_body >
END [function_name];
 Function name: specifies the name of the function.
 [OR REPLACE] option allows modifying an existing
function.
 The optional parameter list contains name, mode
and types of the parameters.
PL/SQL  The function must contain a return statement.
Function  RETURN clause specifies that data type you are going
to return from the function.
 Function body contains the executable part.
 The AS keyword is used instead of the IS keyword for
creating a standalone function.
PL/SQL
Drop  Syntax for removing your created function:

Function DROP FUNCTION function_name;


 A package is a way of logically storing the
subprograms like procedure, function, exception or
cursor into a single common unit.
 A package can be defined as an oracle object that is
PL/SQL compiled and stored in the database.
Package  Once it is compiled and stored in the database it can
be used by all the users of database who have
executable permissions on Oracle database.
 Components of Package

 Package has two basic components:


PL/SQL
Package  Specification: It is the declaration section of a
Package
 Body: It is the definition section of a Package.
 Following are the steps to declare and use a package in PL/SQL code
block:
CREATE
 STEP OR REPLACE PACKAGE <package_name>
1: Package specification or declaration
IS/AS
FUNCTION <function_name> (<list of
arguments>)

PL/SQL RETURN <datatype>;


PROCEDURE <procedure_name> (<list of
Package arguments>);
-- code statements
END <package_name>;
 CREATE OR REPLACE PACKAGE are keywords used to create a package
 FUNCTION and PROCEDURE are keywords used to declare function and
procedure while creating package.
 <package_name>, <function_name>, <procedure_name> are user-
defined names.
 IS/AS are keywords used to declare package.
 RETURN is a keyword specifying value returned by the function declared.
 STEP 2: Package Body
CREATE OR REPLACE PACKAGE BODY <package_name>
IS/AS
FUNCTION <function_name> (<list of arguments>) RETURN
<datatype>IS/AS
-- local variable declaration;
BEGIN
PL/SQL EXCEPTION
-- executable statements;

Package -- error handling statements;


END <function_name>;

PROCEDURE <procedure_name> (<list of arguments>)IS/AS


-- local variable declaration;
BEGIN
-- executable statements;
EXCEPTION
-- error handling statements;
END <procedure_name>;
END <package_name>;
 Creating a package only defines it, to use it we must
refer it using the package object.
PL/SQL  Following is the syntax for referring a package
Package object:
Packagename.objectname;
 Trigger is invoked by Oracle engine automatically
whenever a specified event occurs. Trigger is stored
into database and invoked repeatedly, when specific
PL/SQL condition match.
Trigger  Triggers are stored programs, which are automatically
executed or fired when some event occurs.
 Triggers are written to be executed in response to any
of the following events.

 A database manipulation (DML) statement


(DELETE, INSERT, or UPDATE).
PL/SQL  A database definition (DDL) statement (CREATE,
ALTER, or DROP).
Trigger  A database operation (SERVERERROR, LOGON,
LOGOFF, STARTUP, or SHUTDOWN).
 Triggers could be defined on the table, view, schema,
or database with which the event is associated.
 Syntax for creating trigger:

CREATE [OR REPLACE ] TRIGGER trigger_name


{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
PL/SQL [REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
Trigger WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
 CREATE [OR REPLACE] TRIGGER trigger_name: It creates or replaces
an existing trigger with the trigger_name.
 {BEFORE | AFTER | INSTEAD OF} : This specifies when the trigger
would be executed. The INSTEAD OF clause is used for creating
trigger on a view.
 {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML
operation.
 [OF col_name]: This specifies the column name that would be

PL/SQL updated.
 [ON table_name]: This specifies the name of the table associated
Trigger with the trigger.
 [REFERENCING OLD AS o NEW AS n]: This allows you to refer new and
old values for various DML statements, like INSERT, UPDATE, and
DELETE.
 [FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger
would be executed for each row being affected. Otherwise the trigger
will execute just once when the SQL statement is executed, which is
called a table level trigger.
 WHEN (condition): This provides a condition for rows for which the
trigger would fire. This clause is valid only for row level triggers.
 The four main types of triggers are:
 Row Level Trigger: This gets executed before or
after any value of a row changes
 Column Level Trigger: This gets executed before or
after the specified column changes
Types of  For Each Row Type: This trigger gets executed once
Trigger for each row of the result set affected by an
insert/update/delete
 For Each Statement Type: This trigger gets
executed only once for the entire result set, but also
fires each time the statement is executed.
THANK YOU

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy