SlideShare a Scribd company logo
SANJIVANI K. B. P. POLYTECHNIC, KOPARGAON
With NBA ACCREDIATED programs , Approved by AICTE, New Delhi,
Recognized by Govt. of Maharashtra, Affiliated to Maharashtra State Board of Technical Education, Mumbai,
ISO 9001:2015 Certified Institute
Department:- Computer Technology Class:-SYCM
Name of Subject:-Database Management System MSBTE Subject Code:- 22319
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 1
Unit 4
PL/SQL Programming
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 2
Unit Outcomes
• 4a.write simple PL/SQL code using control structure and handle various
exception in the given situation.
• 4b.Create cursor for retrieving multiple records in the given situation.
• 4c.Create and execute stored procedures and functions in the given
situation.
• 4d.Create and apply database trigger using PL/SQL in the given situation.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 3
• PL/SQL
• PL/SQL is a block of codes that used to write the entire program
blocks/ procedure/ function, etc.
• PL/SQL fully supports SQL data types. You need not convert
between PL/SQL and SQL data types.
• SQL is a non-procedural language that executes a single query at a
time whereas, PL/SQL is a procedural language and executes
blocks of code at once which consists of triggers, functions,
procedures.
• It helps reduce traffic and increases processing speed.
• Developed by Oracle Corporation in the 1990s, it was designed to
build server pages and web applications and exhibits features
such as abstraction and error handling.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 4
• Features of PL/SQL
• PL/SQL is tightly integrated with SQL.
• It offers extensive error checking.
• It offers numerous data types.
• It offers a variety of programming structures.
• It supports structured programming through functions and
procedures.
• It supports object-oriented programming.
• It supports developing web applications and server pages
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 5
• Advantages of PL/SQL
• PL/SQL supports both static and dynamic SQL. Static SQL supports
DML operations and transaction control from PL/SQL block. In
Dynamic SQL, SQL allows embedding DDL statements in PL/SQL
blocks.
• PL/SQL allows sending an entire block of statements to the
database at one time. This reduces network traffic and provides
high performance for the applications.
• PL/SQL gives high productivity to programmers as it can query,
transform, and update data in a database.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 6
• PL/SQL saves time on design and debugging by strong features, such
as exception handling, encapsulation, data hiding, and object-
oriented data types.
• Applications written in PL/SQL are fully portable.
• PL/SQL provides high security level.
• PL/SQL provides access to predefined SQL packages.
• PL/SQL provides support for Object-Oriented Programming.
• PL/SQL provides support for developing Web Applications and
Server Pages.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 7
• PL/SQL Block
• Each block of PL/SQL contains the following subparts −
• Declarations -
• This section contains all the items that needs to be declared before the
program such as variables, subprograms etc. This section contains the
keyword DECLARE at its start. In general, Declarations is an optional
subpart of the PL/SQL program.
• Executable Commands -
• This section of the PL/SQL code contains the executable statements. It
contains BEGIN and END at its starting and ending. Executable commands
is a compulsory section and it cannot be left blank. In case there are no
executable statements, NULL is written to signify this.
• Exception Handling -
• This section contains the code to handle all the errors or exceptions that
may arise during the course of the program. Exception handling section
starts with the keyword EXCEPTION.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 8
• Structure of a PL/SQL Block
• Every PL/SQL statement ends with a semicolon (;).
• The basic structure of a PL/SQL block is
• Hello world example
• it produces the following result
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 9
DECLARE
< Declarations section >
BEGIN
< Executable commands section >
EXCEPTION
< Exception handling section >
END;
DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN dbms_output.put_line(message);
END; /
Hello World
PL/SQL procedure successfully completed.
• PL/SQL - Data Types
• PL/SQL variables, constants and parameters must have a valid data
type, which specifies a storage format, constraints, and valid range
of values.
• SCALAR and LOB data types available in PL/SQL and other two data
types will be covered in other chapters.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 10
.
Category Description
Scalar Single values with no internal components, such as a
NUMBER, DATE, or BOOLEAN.
Large Object (LOB) Pointers to large objects that are stored separately from
other data items, such as text, graphic images, video
clips, and sound waveforms. It is used to store lengthy
documents.
Composite A composite type represents the structure of a row or
record. For example, collections and records.
Reference Pointers to other data items.
• PL/SQL Scalar Data Types and Subtypes
• PL/SQL Scalar Data Types and Subtypes come under the following
categories:
• PL/SQL provides subtypes of data types. For example, the data type
NUMBER has a subtype called INTEGER. You can use subtypes in
your PL/SQL program to make the data types compatible with data
types in other programs while embedding PL/SQL code in another
program, such as a Java program.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 11
.
Data type Description
Numeric Numeric values on which arithmetic
operations are performed.
Character Alphanumeric values that represent
single characters or strings of characters.
Boolean Logical values on which logical operations
are performed.
Datetime Dates and times.
• PL/SQL Numeric Data Types and Subtypes
• Following is the detail of PL/SQL pre-defined numeric data types
and their sub-types:
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 12
.
Data Type Description
PLS_INTEGER Signed integer in range -2,147,483,648
through 2,147,483,647, represented in 32
bits
BINARY_INTEGER Signed integer in range -2,147,483,648
through 2,147,483,647, represented in 32
bits
BINARY_FLOAT Single-precision IEEE 754-format floating-
point number
BINARY_DOUBLE Double-precision IEEE 754-format
floating-point number
NUMBER(prec, scale) Fixed-point or floating-point number with
absolute value in range 1E-130 to (but
not including) 1.0E126. A NUMBER
variable can also represent 0.
DEC(prec, scale) ANSI specific fixed-point type with
maximum precision of 38 decimal digits.
Data Type Description
DECIMAL(prec, scale) IBM specific fixed-point type with maximum
precision of 38 decimal digits.
NUMERIC(pre, secale) Floating type with maximum precision of 38 decimal
digits.
FLOAT ANSI and IBM specific floating-point type with
maximum precision of 126 binary digits
(approximately 38 decimal digits)
INT ANSI specific integer type with maximum precision
of 38 decimal digits
INTEGER ANSI and IBM specific integer type with maximum
precision of 38 decimal digits
SMALLINT ANSI and IBM specific integer type with maximum
precision of 38 decimal digits
REAL Floating-point type with maximum precision of 63
binary digits (approximately 18 decimal digits)
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 13
.
• Following is a valid declaration:
PL/SQL Character Data Types and Subtypes
Following is the detail of PL/SQL pre-defined character data types and
their sub-types:
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 14
.
DECLARE
num1 INTEGER;
num2 REAL;
num3 DOUBLE PRECISION;
BEGIN
null;
END; /
Data type Description
CHAR Fixed-length character string with maximum size of 32,767 bytes
VARCHAR2 Variable-length character string with maximum size of 32,767
bytes
RAW RAW datatype is used to store values in binary data format. The
maximum size for a raw in a table in 32767 bytes. (for example,
graphics or audio files)
Data Type Description
NCHAR Fixed-length national character string with maximum
size of 32,767 bytes
NVARCHAR2 Variable-length national character string with
maximum size of 32,767 bytes
LONG Variable-length character string with maximum size
of 32,760 bytes
LONG RAW Variable-length binary or byte string with maximum
size of 32,760 bytes, not interpreted by PL/SQL
ROWID A ROWID data type stores information related to
the disk location of table rows. They also uniquely
identify the rows in your table.
UROWID The Universal ROWID ( UROWID ) is a datatype that
can store both logical and physical rowids of Oracle
tables.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 15
.
• Boolean Data Types:
• The BOOLEAN data type stores logical values that are used in
logical operations. The logical values are the Boolean values
TRUE and FALSE and the value NULL.
• Datetime and interval types
• The default date format is set by the Oracle initialization
parameter NLS_DATE_FORMAT.
• For example, the default might be 'DD-MON-YY', which includes
a two-digit number for the day of the month, an abbreviation of
the month name, and the last two digits of the year, for example,
01-OCT-12.
• Each DATE includes the century, year, month, day, hour, minute,
and second. The following table shows the valid values for each
field:
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 16
• PL/SQL Large Object (LOB) Data Types
• Large object (LOB) data types refer large to data items such as
text, graphic images, video clips, and sound waveforms.
• LOB data types allow efficient, random, piecewise access to this
data. Following are the predefined PL/SQL LOB data types:
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 17
Data type Description Size
BFILE Used to store large binary
objects in operating
system files outside the
database.
System-dependent.
Cannot exceed 4 gigabytes
(GB).
BLOB Used to store large binary
objects in the database.
8 to 128 terabytes (TB)
CLOB Used to store large blocks
of character data in the
database.
8 to 128 TB
• PL/SQL User-Defined Subtypes
• A subtype is a definition of a type based on a built-in type.
• A subtype has the same valid operations as its base type, but
only a subset of its valid values.
• PL/SQL predefines several subtypes in package STANDARD. For
example, PL/SQL predefines the subtypes CHARACTER and
INTEGER as follows
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 18
SUBTYPE NAME IS CHAR;
SUBTYPE PHONE_NUMBER IS NUMBER(38,0);
• You can define and use your own subtypes. The following
program illustrates defining and using a user-defined subtype:
• When the above code is executed at SQL prompt, it produces the
following result:
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 19
DECLARE
SUBTYPE name IS char(20);
SUBTYPE message IS varchar2(100);
salutation name;
greetings message;
BEGIN
salutation := 'Reader ';
greetings := 'Welcome to the World of PL/SQL';
dbms_output.put_line('Hello ' || salutation ||
greetings);
END; /
Hello Reader Welcome to the World of PL/SQL PL/SQL
procedure successfully completed.
• PL/SQL Variable
• PL/SQL variables must be declared in the declaration section or
in a package as a global variable.
• When we declare a variable, PL/SQL allocates memory for the
variable's value and the storage location is identified by the
variable name.
• The syntax for declaring a variable is:
• variable_name datatype = [initial_value]
• Where, variable_name is a valid identifier in PL/SQL, datatype
must be a valid PL/SQL data type or any user defined data type.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 20
• Example
• It is a good programming practice to initialize variables properly otherwise,
sometimes program would produce unexpected result.
• Try the following example which makes use of various types of variables:
• DECLARE
• a integer := 10;
• b integer := 20;
• c integer;
• f real;
• BEGIN
• c := a + b;
• dbms_output.put_line('Value of c:' || c);
• f := 70.0/3.0; dbms_output.put_line('Value of f: ' || f);
• END; /
• When the above code is executed, it produces the following result:
• Value of c: 30 Value of f: 23.333333333333333333
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 21
• There are two types of variable scope
• Local Variable:
• Local variables are the inner block variables which are not
accessible to outer blocks.
• Global Variable:
• Global variables are declared in outermost block.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 22
• Variable scope in PL/SQL
• Following example shows the usage of Local and Global variables in its simple form:
• DECLARE
• -- Global variables
• num1 number := 95;
• num2 number := 85;
• BEGIN
• dbms_output.put_line('Outer Variable num1: ' || num1);
• dbms_output.put_line('Outer Variable num2: ' || num2);
• DECLARE
• -- Local variables
• num1 number := 195;
• num2 number := 185;
• BEGIN
• dbms_output.put_line('Inner Variable num1: ' || num1);
• dbms_output.put_line('Inner Variable num2: ' || num2); 23
When the above code is executed, it produces the
following result:
Outer Variable num1: 95 Outer Variable num2: 85
Inner Variable num1: 195 Inner Variable num2: 185
• PL/SQL Constant
• PL/SQL - Constants Declaring a Constant
• A constant is declared using the CONSTANT keyword. It requires an
initial value and does not allow that value to be changed.
• For example:
• General Syntax to declare a constant is:
• constant_name CONSTANT datatype := VALUE;
• constant_name is the name of the constant i.e. similar to a variable
name.
• The word CONSTANT is a reserved word and ensures that the value
does not change.
• VALUE - It is a value which must be assigned to a constant when it is
declared. You cannot assign a value later.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 24
.
• For example, to declare salary_increase, you can write code as follows:
• DECLARE
• salary_increase CONSTANT number (3) := 10;
• You must assign a value to a constant at the time you declare it.
• If you do not assign a value to a constant while declaring it and try to
assign a value in the execution section, you will get a error.
• If you execute the below Pl/SQL block you will get error.
• DECLARE
• salary_increase CONSTANT number(3);
• BEGIN
• salary_increase := 100;
• dbms_output.put_line (salary_increase);
• END;
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 25
• PL/SQL - Operators
• An operator is a symbol that tells the compiler to perform
specific mathematical or logical manipulation.
• PL/SQL language is rich in built-in operators and provides the
following types of operators:
• Arithmetic operators
• Relational operators
• Comparison operators
• Logical operators
• String operators
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 26
• Arithmetic Operators
• Following table shows all the arithmetic operators supported by
PL/SQL. Assume variable A holds 10 and variable B holds 5 then:
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 27
Operator Description Example
+ Adds two operands A + B will give 15
- Subtracts second operand
from the first
A - B will give 5
* Multiplies both operands A*B gives 50
/ Divides numerator by de-
numerator
A / B will give 2
** Exponentiation operator,
raises one operand to the
power of other
A ** B will give 100000
• Relational Operators
• Relational operators compare two expressions or values and
return a Boolean result.
• Following table shows all the relational operators supported by
PL/SQL. Assume variable A holds 10 and variable B holds 20,
then:
• Show Examples != <> ~=
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 28
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 29
Operator Description Example
= Checks if the values of two
operands are equal or not,
if yes then condition
becomes true.
(A = B) is not true.
!= Checks if the values of two
operands are equal or not,
if values are not equal
then condition
(A != B) is true.
> Checks if the value of left
operand is greater than
the value of right operand,
if yes then condition
becomes true.
(A > B) is not true.
< Checks if the value of left
operand is less than the
value of right operand, if
yes then condition
becomes true.
(A < B) is true.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 30
Operator Description Example
>= Checks if the value of left
operand is greater than or
equal to the value of right
operand, if yes then
condition becomes true.
(A >= B) is not true.
<= Checks if the value of left
operand is less than or
equal to the value of right
operand, if yes then
condition becomes true.
(A <= B) is true.
• Comparison Operators
• Comparison operators are used for comparing one expression to
another. The result is always either TRUE, FALSE OR NULL.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 31
Operator Description Example
LIKE The LIKE operator compares a
character, string, or CLOB value to
a pattern and returns TRUE if the
value matches the pattern and
FALSE if it does not.
If 'Zara Ali' like 'Z% A_i' returns a
Boolean true, whereas, 'Nuha Ali'
like 'Z% A_i' returns a Boolean
false
BETWEEN The BETWEEN operator tests
whether a value lies in a specified
range. x BETWEEN a AND b means
that x >= a and x <= b.
If x = 10 then, x between 5 and 20
returns true, x between 5 and 10
returns true, but x between 11 and
20 returns false.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 32
Operator Description Example
IN The IN operator tests set
membership. x IN (set) means that
x is equal to any member of set.
If x = 'm' then, x in ('a', 'b', 'c')
returns boolean false but x in ('m',
'n', 'o') returns Boolean true.
IS NULL The IS NULL operator returns the
BOOLEAN value TRUE if its
operand is NULL or FALSE if it is
not NULL. Comparisons involving
NULL values always yield NULL.
If x = 'm', then 'x is null' returns
Boolean false.
• Logical Operators
• Following table shows the Logical operators supported by PL/SQL.
All these operators work on Boolean operands and produces
Boolean results.
• Assume variable A holds true and variable B holds false, then:
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 33
Operator Description Example
AND Called logical AND operator. If both the
operands are true then condition becomes true.
(A and B) is false.
OR Called logical OR Operator. If any of the two
operands is true then condition becomes true.
(A or B) is true
not Called logical NOT Operator. Used to reverse the
logical state of its operand. If a condition is true
then Logical NOT operator will make it false.
not (A and B) is true.
• PL/SQL – Conditions
• IF statement It is the simplest form of IF control statement,
frequently used in decision making and changing the control flow of
the program execution.
• The IF statement associates a condition with a sequence of
statements enclosed by the keywords THEN and END IF.
• If the condition is TRUE, the statements get executed, and if the
condition is FALSE or NULL, then the IF statement does nothing.
• Syntax for IF-THEN statement is:
• IF condition THEN
• S;
• END IF;
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 34
• If the Boolean expression condition evaluates to true then the
block of code inside the if statement will be executed.
• If Boolean expression evaluates to false then the first set of code
after the end of the if statement (after the closing end if) will be
executed.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 35
• Example 1:
• DECLARE
• a number(2) := 10;
• BEGIN
• a:= 10;
• -- check the boolean condition using if statement
• IF( a < 20 )
• THEN
• -- if condition is true then print the following
• dbms_output.put_line('a is less than 20 ' );
• END IF;
• dbms_output.put_line('value of a is : ' || a);
• END; /
• When the above code is executed at SQL prompt, it produces the following result:
• a is less than 20 value of a is : 10
• PL/SQL procedure successfully completed.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 36
• IF-THEN-ELSE Statement
• A sequence of IF-THEN statements can be followed by an
optional sequence of ELSE statements, which execute when the
condition is FALSE.
• IF condition THEN
• S1;
• ELSE
• S2;
• END IF;
• Where, S1 and S2 are different sequence of statements. In the
IF-THEN-ELSE statements, when the test condition is TRUE, the
statement S1 is executed andS2 is skipped; when the test
condition is FALSE, then S1 is bypassed and statement S2 is
executed.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 37
• Flow Diagram
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 38
• Example
• Output
39
DECLARE
a NUMBER:=11;
BEGIN
dbms_output.put_line (‘Program started');
IF( mod(a,2)=0) THEN
dbms_output.put_line('a is even number' );
ELSE
dbms_output.put_line('a is odd number1);
END IF;
dbms_output.put_line (‘Program completed.’);
END; /
Program started.
a is odd number
Program completed.
• Example
• DECLARE a number(3) := 100;
• BEGIN
• -- check the boolean condition using if statement
• IF( a < 20 )
• THEN
• -- if condition is true then print the following
• dbms_output.put_line('a is less than 20 ' );
• ELSE
• dbms_output.put_line('a is not less than 20 ' );
• END IF;
• dbms_output.put_line('value of a is : ' || a);
• END; /
• When the above code is executed at SQL prompt, it produces the following result:
• a is not less than 20
• value of a is : 100
• PL/SQL procedure successfully completed
40
• IF-THEN-ELSIF
• The IF-THEN-ELSIF statement allows you to choose between
several alternatives.
• An IF-THEN statement can be followed by an optional
ELSIF...ELSE statement.
• The ELSIF clause lets you add additional conditions. When using
IF-THEN-ELSIF statements there are few points to keep in mind.
• It's ELSIF, not ELSEIF
• An IF-THEN statement can have zero to many ELSIF's and they
must come before the ELSE.
• Once an ELSIF succeeds, none of the remaining ELSIF's or ELSE's
will be tested.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 41
• Syntax:
• The syntax of an IF-THEN-ELSIF Statement in PL/SQL
programming language is:
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 42
IF(boolean_expression 1)THEN
S1; -- Executes when the boolean expression 1
is true
ELSIF( boolean_expression 2) THEN
S2; -- Executes when the boolean expression 2
is true
ELSIF( boolean_expression 3) THEN
S3; -- Executes when the boolean expression 3
is true
ELSE
S4; -- executes when the none of the above
condition is true
END IF;
• Example:
• When the above code is executed at SQL prompt, it produces the
following result:
• None of the values is matching Exact value of a is: 100
• PL/SQL procedure successfully completed.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 43
DECLARE
a number(3) := 100;
BEGIN
IF ( a = 10 ) THEN
dbms_output.put_line('Value of a is 10' );
ELSIF ( a = 20 ) THEN
dbms_output.put_line('Value of a is 20' );
ELSIF ( a = 30 ) THEN
dbms_output.put_line('Value of a is 30' );
ELSE
dbms_output.put_line('None of the values is matching');
END IF;
dbms_output.put_line('Exact value of a is: '|| a );
END; /
• PL/SQL - Searched CASE Statement
• The searched CASE statement has no selector and its WHEN
clauses contain search conditions that give Boolean values.
• Syntax: The syntax for searched case statement in PL/SQL is:
• CASE
• WHEN selector = 'value1' THEN S1;
• WHEN selector = 'value2' THEN S2;
• WHEN selector = 'value3' THEN S3;
• ... ELSE Sn; -- default case
• END CASE;
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 44
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 45
• Flow Structure
• Example
• DECLARE
• grade char(1) := 'B';
• BEGIN
• case
• when grade = 'A' then dbms_output.put_line('Excellent');
• when grade = 'B' then dbms_output.put_line('Very good');
• when grade = 'C' then dbms_output.put_line('Well done');
• when grade = 'D' then dbms_output.put_line('You passed');
• when grade = 'F' then dbms_output.put_line('Better try again');
• else dbms_output.put_line('No such grade');
• end case;
• END;
• /
• When the above code is executed at SQL prompt, it produces the following result:
• Very good
• PL/SQL procedure successfully completed.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 46
• PL/SQL - Nested IF-THEN-ELSE Statements
• It is always legal in PL/SQL programming to nest IF-ELSE statements,
which means you can use one IF or ELSE IF statement inside another
IF or ELSE IF statement(s).
• Syntax:
• IF( boolean_expression 1)THEN
• -- executes when the boolean expression 1 is true
• IF(boolean_expression 2) THEN
• -- executes when the boolean expression 2 is true
• sequence-of-statements;
• END IF;
• ELSE
• -- executes when the boolean expression 1 is not true
• else-statements;
• END IF;
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 47
• Example:
• DECLARE
• a number(3) := 100;
• b number(3) := 200;
• BEGIN -- check the boolean condition
• IF( a = 100 ) THEN -- if condition is true then check the following
• IF( b = 200 ) THEN -- if condition is true then print the following
dbms_output.put_line('Value of a is 100 and b is 200' );
• END IF;
• END IF;
• dbms_output.put_line('Exact value of a is : ' || a );
• dbms_output.put_line('Exact value of b is : ' || b );
• END; /
• When the above code is executed at SQL prompt, it produces the following result:
• Value of a is 100 and b is 200
• Exact value of a is : 100
• Exact value of b is : 200
• PL/SQL procedure successfully completed.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 48
• PL/SQL –Loops
• A loop statement allows us to execute a statement or group of
statements multiple times and following is the general form of a
loop statement in most of the programming languages:
• PL/SQL -Basic Loop Statement
• Basic loop structure encloses sequence of statements in
between the LOOP and END LOOP statements. With each
iteration, the sequence of statements is executed and then
control resumes at the top of the loop.
• Syntax:
• The syntax of a basic loop in PL/SQL programming language is:
• LOOP
• Sequence of statements;
• END LOOP;
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 49
• Flow Diagram
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 50
• PL/SQL -WHILE LOOP Statement
• A WHILE LOOP statement in PL/SQL programming language
repeatedly executes a target statement as long as a given
condition is true.
• Syntax:
• WHILE condition LOOP
• sequence_of_statements
• END LOOP;
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 51
• PL/SQL -WHILE LOOP Statement
• Example:
• DECLARE
• a number(2) := 10;
• BEGIN
• WHILE a < 20 LOOP
• dbms_output.put_line('value of a: ' || a);
• a := a + 1;
• END LOOP;
• END; /
• When the above code is executed at SQL prompt, it produces the
following result:
• value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14
value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19
PL/SQL procedure successfully completed
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 52
• PL/SQL - FOR LOOP Statement
• A FOR LOOP is a repetition control structure that allows you to
efficiently write a loop that needs to execute a specific number
of times.
• Syntax:
• FOR counter IN initial_value .. final_value LOOP
sequence_of_statements;
• END LOOP;
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 53
• Here is the flow of control in a for loop:
• The initial step is executed first, and only once. This step allows
you to declare and initialize any loop control variables.
• Next, the condition, i.e., initial_value .. final_value is evaluated.
If it is TRUE, the body of the loop is executed. If it is FALSE, the
body of the loop does not execute and flow of control jumps to
the next statement just after the for loop.
• After the body of the for loop executes, the value of the counter
variable is increased or decreased.
• The condition is now evaluated again. If it is TRUE, the loop
executes and the process repeats itself (body of loop, then
increment step, and then again condition).
• After the condition becomes FALSE, the FOR-LOOP terminates.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 54
• Example:
• DECLARE
• a number(2);
• BEGIN FOR a in 10 .. 20 LOOP
• dbms_output.put_line('value of a: ' || a);
• END LOOP;
• END; /
• When the above code is executed at SQL prompt, it produces the following result:
• value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15
value of a: 16 value of a: 17 value of a: 18 value of a: 19 value of a: 20
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 55
• Reverse FOR LOOP Statement
• By default, iteration proceeds from the initial value to the final value,
generally upward from the lower bound to the higher bound.
• You can reverse this order by using the REVERSE keyword. In such
case, iteration proceeds the other way. After each iteration, the loop
counter is decremented.
• However, you must write the range bounds in ascending (not
descending) order.
• DECLARE
• a number(2) ;
• BEGIN FOR a IN REVERSE 10 .. 20 LOOP
• dbms_output.put_line('value of a: ' || a);
• END LOOP;
• END; /
• When the above code is executed at the SQL prompt, it produces the
following result −
56
value of a: 20 value of a: 19 value of a: 18 value of a: 17 value of a: 16 value of a: 15 value of a: 14 value of a: 13 value of a: 12
value of a: 11 value of a: 10
• PL/SQL - Nested Loops
• PL/SQL allows using one loop inside another loop.
• Following section shows few examples to illustrate the concept.
The syntax for a nested basic LOOP statement in PL/SQL is as
follows:
• LOOP
• Sequence of statements1
• LOOP
• Sequence of statements2
• END LOOP;
• END LOOP;
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 57
• The syntax for a nested FOR LOOP statement in PL/SQL is as
follows:
• FOR counter1 IN initial_value1 .. final_value1 LOOP
sequence_of_statements1
• FOR counter2 IN initial_value2 .. final_value2 LOOP
sequence_of_statements2
• END LOOP;
• END LOOP;
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 58
• The syntax for a nested WHILE LOOP statement in Pascal is as
follows:
• WHILE condition1 LOOP
• sequence_of_statements1
• WHILE condition2 LOOP
• sequence_of_statements2
• END LOOP;
• END LOOP;
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 59
• The Loop Control Statements
• PL/SQL -EXIT Statement The EXIT statement in PL/SQL
programming language has following two usages:
• When the EXIT statement is encountered inside a loop, the loop
is immediately terminated and program control resumes at the
next statement following the loop.
• If you are using nested loops (i.e. one loop inside another loop),
the EXIT statement will stop the execution of the innermost loop
and start executing the next line of code after the block.
• Syntax: The syntax for an EXIT statement in PL/SQL is as follows:
• EXIT;
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 60
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 61
• The EXIT WHEN Statement
• The EXIT-WHEN statement allows the condition in the WHEN clause
to be evaluated.
• If the condition is true, the loop completes and control passes to the
statement immediately after END LOOP.
• Following are two important aspects for the EXIT WHEN statement:
• Until the condition is true, the EXIT-WHEN statement acts like a NULL
statement, except for evaluating the condition, and does not
terminate the loop.
• A statement inside the loop must change the value of the condition.
• Syntax:
• The syntax for an EXIT WHEN statement in PL/SQL is as follows:
• EXIT WHEN condition;
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 62
• Example:
• DECLARE
• a number(2) := 10;
• BEGIN -- while loop execution
• WHILE a < 20 LOOP
• dbms_output.put_line ('value of a: ' || a);
• a := a + 1;
• -- terminate the loop using the exit when statement
• EXIT WHEN a > 15;
• END LOOP;
• END; /
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 63
• When the above code is executed at SQL prompt, it produces the
following result:
• 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.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 64
• PL/SQL - CONTINUE Statement
• The CONTINUE statement causes the loop to skip the remainder
of its body and immediately retest its condition prior to
reiterating.
• The continue statement allows you to exit the current loop
iteration and immediately continue on to the next iteration of
that loop.
• Syntax:
• The syntax for a CONTINUE statement is as follows:
• CONTINUE;
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 65
• Flow Diagram
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 66
• Example:
• DECLARE
• a number(2) := 10;
• BEGIN -- while loop execution
• WHILE a < 20 LOOP
• dbms_output.put_line ('value of a: ' || a);
• a := a + 1;
• IF a = 15 THEN -- skip the loop using the
• CONTINUE statement
• a := a + 1;
• CONTINUE;
• END IF;
• END LOOP;
• END; /
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 67
• When the above code is executed at SQL prompt, it produces the
following result:
• value of a: 10
• value of a: 11
• value of a: 12
• value of a: 13
• value of a: 14
• value of a: 16
• value of a: 17
• value of a: 18
• value of a: 19
• PL/SQL procedure successfully completed.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 68
• PL/SQL - GOTO Statement
• A GOTO statement in PL/SQL programming language provides an
unconditional jump from the GOTO to a labeled statement in the
same subprogram.
• Syntax:
• The syntax for a GOTO statement in PL/SQL is as follows:
• GOTO
• label;
• ..
• ..
• << label >>
• statement;
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 69
• Flow Diagram
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 70
• Example:
• DECLARE
• a number(2) := 10;
• BEGIN
• <<loopstart>> -- while loop execution
• WHILE a < 20 LOOP
• dbms_output.put_line ('value of a: ' || a);
• a := a + 1;
• IF a = 15 THEN
• a := a + 1;
• GOTO loopstart;
• END IF;
• END LOOP;
• END; /
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 71
• When the above code is executed at SQL prompt, it produces the
following result:
• value of a: 10
• value of a: 11
• value of a: 12
• value of a: 13
• value of a: 14
• value of a: 16
• value of a: 17
• value of a: 18
• value of a: 19
• PL/SQL procedure successfully completed.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 72
• PL/SQL –Exceptions
• An error condition during a program execution is called an
exception in PL/SQL.
• PL/SQL supports programmers to catch such conditions using
EXCEPTION block in the program and an appropriate action is
taken against the error condition.
• There are two types of exceptions:
• System-defined exceptions
• User-defined exceptions
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 73
• Syntax for Exception Handling
• The General Syntax for exception handling is as follows. Here you can list down as many as
exceptions you want to handle. The default exception will be handled using WHEN others
THEN:
• DECLARE
• <declarations section>
• BEGIN
• <executable command(s)>
• EXCEPTION
• <exception handling goes here >
• WHEN exception1 THEN
• exception1-handling-statements
• WHEN exception2 THEN
• exception2-handling-statements
• WHEN exception3 THEN
• exception3-handling-statements ........
• WHEN others THEN
• exception-handling-statements END; 74
• Example of exception handling
• Let's take a simple example to demonstrate the concept of
exception handling. Here we are using the already created
CUSTOMERS table.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 75
ID Name Age Address Salary
1 Ramesh 10 Aurangabad 20000
2 Suresh 60 Kanpur 24000
3 Mahesh 30 Ghaziabad 28000
4 Ankita 20 Paris 30000
5 Nikita 40 Delhi 32000
6 Sunita 50 Nagpur 36000
• DECLARE
• c_id customers.id%type := 8;
• c_name customers.name%type;
• c_addr customers.address%type;
• BEGIN
• SELECT name, address INTO c_name, c_addr FROM customers WHERE id = c_id;
• DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
• DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
• EXCEPTION
• WHEN no_data_found THEN
• dbms_output.put_line('No such customer!');
• WHEN others THEN
• dbms_output.put_line('Error!');
• END;
• /
• %type attribute ensures that type compatibility between table column and PL/SQL
variables is maintained
• Syntax of Type
Variable name typed-attribute %Type
76
• When the above code is executed at the SQL prompt, it produces the following
result −
• No such customer! PL/SQL procedure successfully completed.
• The above program displays the name and address of a customer whose ID is
given.
• Since there is no customer with ID value 8 in our database, the program raises the
run-time exception NO_DATA_FOUND, which is captured in the EXCEPTION block.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 77
• User-defined Exceptions
• This type of users can create their own exceptions according to the
need and to raise these exceptions explicitly raise command is used.
Example:
• Divide non-negative integer x by y such that the result is greater than
or equal to 1.From the given question we can conclude that there
exist two exceptions
• Division be zero.
• If result is greater than or equal to 1 means y is less than or equal to x.
• The syntax for declaring an exception is:
• DECLARE
• my-exception EXCEPTION;
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 78
79
DECLARE
x int:=&x; /*taking value at run time*/
y int:=&y;
div_r float;
exp1 EXCEPTION;
exp2 EXCEPTION;
BEGIN
IF y=0 then
raise exp1;
ELSEIF y > x then
raise exp2;
ELSE
div_r:= x / y;
dbms_output.put_line('the result is '||div_r);
END IF;
EXCEPTION
WHEN exp1 THEN
dbms_output.put_line('Error');
dbms_output.put_line('division by zero not allowed');
WHEN exp2 THEN
dbms_output.put_line('Error');
dbms_output.put_line('y is greater than x please check the input');
80
• Input 1: x=20
• Y=10
• Output: the result is 2
• Input 2: x=20
• Y=0
• Output
• Error
• Division by zero not allowed
• Input 3: x=20
• Y=30
• Output:<.em>
• Error
• Y is greater than x please check the input
• Pre-defined Exceptions
• PL/SQL provides many pre-defined exceptions, which are executed
when any database rule is violated by a program.
• For example, the predefined exception NO_DATA_FOUND is raised
when a SELECT INTO statement returns no rows.
• System defined exceptions:
These exceptions are predefined in PL/SQL which get raised WHEN
certain database rule is violated.
System-defined exceptions are further divided into two categories:
• Named system exceptions.
• Unnamed system exceptions.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 81
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 82
• Named system exceptions: They have a predefined name by the
system like ACCESS_INTO_NULL, DUP_VAL_ON_INDEX,
LOGIN_DENIED etc. the list is quite big.So we will discuss some of the
most commonly used exceptions:
• Lets create a table geeks.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 83
• NO_DATA_FOUND:
• It is raised WHEN a SELECT INTO statement returns no rows. For
eg:
• Output:
DECLARE
temp varchar(20);
BEGIN
SELECT g_id into temp from geeks where
g_name='GeeksforGeeks';
exception
WHEN no_data_found THEN
dbms_output.put_line('ERROR');
dbms_output.put_line('there is no name as');
dbms_output.put_line('GeeksforGeeks in geeks
table');
end;
ERROR there is no name as GeeksforGeeks in geeks table
84
• TOO_MANY_ROWS:
• It is raised WHEN a SELECT INTO statement returns more than one
row.
• Output:
• Error trying to select too many rows
DECLARE
temp varchar(20);
BEGIN
-- raises an exception as SELECT
-- into trying to return too many rows
SELECT g_name into temp from geeks;
dbms_output.put_line(temp);
EXCEPTION
WHEN too_many_rows THEN
dbms_output.put_line('error trying to SELECT too
many rows');
end;
85
• VALUE_ERROR:
• This error is raised WHEN a statement is executed that resulted in an
arithmetic, numeric, string, conversion, or constraint error. This error
mainly results from programmer error or invalid data input.
Output
Error
Change data type of temp to varchar(20)
DECLARE
temp number;
BEGIN
SELECT g_name into temp from geeks where g_name='Suraj';
dbms_output.put_line('the g_name is '||temp);
EXCEPTION
WHEN value_error THEN
dbms_output.put_line('Error');
dbms_output.put_line('Change data type of temp to
varchar(20)');
END;
• Zero Divide
• raises exception WHEN dividing with zero.
• Output
• Dividing by zero please check the values again
• The value of a is 10
• The value of b is 0 86
DECLARE
a int:=10;
b int:=0;
answer int;
BEGIN
answer:=a/b;
dbms_output.put_line('the result after division is'||answer);
exception
WHEN zero_divide THEN
dbms_output.put_line('dividing by zero please check
the values again');
dbms_output.put_line('the value of a is '||a);
dbms_output.put_line('the value of b is '||b);
END;
• Cursor
• 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
statement.
• Cursor is a Temporary Memory or Temporary Work Station.
• It is Allocated by Database Server at the Time of Performing
DML(Data Manipulation Language) operations on Table by User.
Cursors are used to store Database Tables.
• There are 2 types of Cursors:
• Implicit Cursors(generated by Oracle)
• Explicit Cursors(generated by user)
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 87
• Implicit Cursors
• Implicit Cursors are also known as Default Cursors of SQL
SERVER.
• These Cursors are allocated by SQL SERVER when the user
performs DML operations.
• These are created by default to process the statements when
DML statements like INSERT, UPDATE, DELETE etc. are executed.
• Oracle provides some attributes known as Implicit cursor's
attributes to check the status of DML operations. Some of them
are: %FOUND, %NOTFOUND, %ROWCOUNT and %ISOPEN.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 88
Attribute Description
%FOUND Its return value is TRUE if DML statements like INSERT,
DELETE and UPDATE affect at least one row or more rows
or a SELECT INTO statement returned one or more rows.
Otherwise it returns FALSE.
%NOTFOUND Its return value is TRUE if DML statements like INSERT,
DELETE and UPDATE affect no row, or a SELECT INTO
statement return no rows. Otherwise it returns FALSE. It is
a just opposite of %FOUND.
%ISOPEN It always returns FALSE for implicit cursors, because the
SQL cursor is automatically closed after executing its
associated SQL statements.
%ROWCOUNT It returns the number of rows affected by DML statements
like INSERT, DELETE, and UPDATE or returned by a
SELECT INTO statement.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 89
• Customer
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 90
ID Name Age Address Salary
1 Ramesh 10 Aurangabad 20000
2 Suresh 60 Kanpur 24000
3 Mahesh 30 Ghaziabad 28000
4 Ankita 20 Paris 30000
5 Nikita 40 Delhi 32000
6 Sunita 50 Nagpur 36000
• DECLARE
• total_rows number(2);
• BEGIN
• UPDATE customers
• SET salary = salary + 5000;
• IF sql%notfound THEN
• dbms_output.put_line('no customers updated');
• ELSIF sql%found THEN
• total_rows := sql%rowcount;
• dbms_output.put_line( total_rows || ' customers updated ');
• END IF;
• END;
• /
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 91
• Output
• 6 rows are updated
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 92
ID Name Age Address Salary
1 Ramesh 10 Aurangabad 25000
2 Suresh 60 Kanpur 29000
3 Mahesh 30 Ghaziabad 33000
4 Ankita 20 Paris 35000
5 Nikita 40 Delhi 37000
6 Sunita 50 Nagpur 41000
• Explicit Cursors :
Explicit Cursors are Created by Users whenever the user requires
them.
• Explicit Cursors are used for Fetching data from Table in Row-By-
Row Manner.
• The Explicit cursors are defined by the programmers to gain
more control over the context area.
• These cursors should be defined in the declaration section of the
PL/SQL block. It is created on a SELECT statement which returns
more than one row.
• Syntax for Explicit Cursor
• CURSOR cursor_name IS select_statement;;
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 93
• Steps:
• You must follow these steps while working with an explicit
cursor.
• Declare the cursor to initialize in the memory.
• Open the cursor to allocate memory.
• Fetch the cursor to retrieve data.
• Close the cursor to release allocated memory.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 94
• Declaring the Cursor
• Declaring the cursor defines the cursor with a name and the
associated SELECT statement.
• Syntax for explicit cursor decleration
CURSOR name IS SELECT statement;
• For example:
• CURSOR c_customers IS SELECT id, name, address FROM customers;
• Opening the Cursor
• Opening the cursor allocates memory for the cursor and makes it
ready for fetching the rows returned by the SQL statement into it.
• Syntax for cursor open:
• OPEN cursor_name;
• For example, we will open above-defined cursor as follows:
• OPEN c_customers;
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 95
• Fetching the Cursor
• Fetching the cursor involves accessing one row at a time.
• Syntax for cursor fetch:
• FETCH cursor_name INTO variable_list;
• For example we will fetch rows from the above-opened cursor as
follows:
• FETCH c_customers INTO c_id, c_name, c_addr;
• Closing the Cursor
• Closing the cursor means releasing the allocated memory.
• Syntax for cursor close:
• Close cursor_name;
• For example, we will close aboveopened cursor as follows:
• CLOSE c_customers;
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 96
• PL/SQL Cursors For Loop
• PL/SQL cursor FOR loop has one great advantage of loop
continued until row not found. In sometime you require to use
explicit cursor with FOR loop instead of use OPEN, FETCH, and
CLOSE statement.
• FOR loop iterate repeatedly and fetches rows of values from
database until row not found.
• Explicit Cursor FOR LOOP Example
• Emp_information table
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 97
EMP_NO EMP_NAME EMP_DEPT EMP_SALARY
1 Aishwarya Web developer 45K
2 Vaishnavi Program developer 38K
3 Shilpa Program developer 50K
4 Shital Web developer 35K
• DECLARE
• cursor c is select * from emp_information where emp_no <=2;
• tmp emp_information%rowtype;
• If you do not use the %ROWTYPE datatype, then you have to declare
variables for each column separately.
• BEGIN
• OPEN c;
• FOR tmp IN c LOOP
• FETCH c into tmp;
• dbms_output.put_line('EMP_No: '||tmp.emp_no);
• dbms_output.put_line('EMP_Name: '||tmp.emp_name);
• dbms_output.put_line('EMP_Dept: '||tmp.emp_dept);
• dbms_output.put_line('EMP_Salary:'||tmp.emp_salary);
• END Loop;
• CLOSE c;
• END;
• / 98
• EMP_No: 1
• EMP_Name: Aishwarya
• EMP_Dept: Web Developer
• EMP_Salary:45k
• EMP_No: 2
• EMP_Name: Vaishnavi
• EMP_Dept: Program Developer
• EMP_Salary:38k
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 99
• PL/SQL Parameterized Cursor
• PL/SQL Parameterized cursor pass the parameters into a cursor
and use them in to query.
• PL/SQL Parameterized cursor define only datatype of parameter
and not need to define it's length.
• Default values is assigned to the Cursor parameters.
• Parameterized cursors are also saying static cursors that can
passed parameter value when cursor are opened.
• Syntax
CURSOR cursor_name (parameter_list)
IS
Select statement;
To open a cursor with parameters, you use the following syntax:
OPEN cursor_name (argument_list); 100
• Following example introduce the parameterized cursor. following
emp_information table
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 101
EMP_NO EMP_NAME EMP_DEPT EMP_SALARY
1 Aishwarya Web developer 45K
2 Vaishnavi Program developer 38K
3 Shilpa Program developer 50K
4 Shital Web developer 35K
• Cursor display employee information from emp_information table whose emp_no four (4).
• DECLARE
• cursor c(no number) is select * from emp_information where emp_no = no;
• tmp emp_information%rowtype;
• BEGIN
• OPEN c(4);
• FOR tmp IN c(4) LOOP
• dbms_output.put_line('EMP_No: '||tmp.emp_no);
• dbms_output.put_line('EMP_Name: '||tmp.emp_name);
• dbms_output.put_line('EMP_Dept: '||tmp.emp_dept);
• dbms_output.put_line('EMP_Salary:'||tmp.emp_salary);
• END Loop;
• CLOSE c;
• END;/
• EMP_No: 4
• EMP_Name: Shital
• EMP_Dept: Web Developer
• EMP_Salary: 35k
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 102
• PL/SQL Procedures
• The PL/SQL stored procedure or simply a procedure is a PL/SQL block which
performs one or more specific tasks.
• The procedure contains a header and a body.
• Header: The header contains the name of the 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.
• PL/SQL procedures create using CREATE PROCEDURE statement. The
major difference between PL/SQL function or procedure, function return
always value where as procedure may or may not return value.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 103
CREATE [OR REPLACE] PROCEDURE procedure_name [(parameter_name [IN | OUT | IN OUT]
type [, ...])] {IS | AS} BEGIN < procedure_body > END procedure_name;
• When you create a function or procedure, you have to define
IN/OUT/INOUT parameters.
• 1. IN :
• An IN parameter lets you pass a value to the subprogram. It is a read-only
parameter. It cannot be assigned a value.It is the default mode of
parameter passing.
• 2. OUT :
• An OUT parameter returns a value to the calling program. Inside the
subprogram, an OUT parameter acts like a variable. You can change its
value and reference the value after assigning it.
• 3. IN OUT :
• An IN OUT parameter passes an initial value to a subprogram and returns
an updated value to the caller. It can be assigned a value and the value can
be read.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 104
• PL/SQL Procedure Example
• In this example, we are going to insert record in user table. So you need to
create user table first.
• create table user(id number(10) primary key,name varchar2(100));
• Now write the procedure code to insert record in user table.
• Procedure Code:
• create or replace procedure "INSERTUSER"
• (id IN NUMBER,name IN VARCHAR2)
• is
• begin
• insert into user values(id,name);
• end; /
• Output:
• Procedure created.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 105
• PL/SQL program to call procedure
• Let's see the code to call above created procedure.
• BEGIN
• insertuser(101,'Rahul');
• dbms_output.put_line('record inserted successfully');
• END;
• /
• Now, see the "USER" table, you will see one record is inserted.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 106
ID Name
101 Rahul
• PL/SQL Drop Procedure
• Syntax for drop procedure
• DROP PROCEDURE procedure_name;
• Example of drop procedure
• DROP PROCEDURE pro1;
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 107
• PL/SQL Function
• PL/SQL functions block create using CREATE FUNCTION statement.
• The major difference between PL/SQL function or procedure, function
return always value where as procedure may or may not return value.
• When you create a function or procedure, you have to define
IN/OUT/INOUT parameters.
• 1. IN :An IN parameter lets you pass a value to the subprogram. It is a
read-only parameter. It cannot be assigned a value.It is the default mode of
parameter passing.
• 2. OUT : An OUT parameter returns a value to the calling program. Inside
the subprogram, an OUT parameter acts like a variable. You can change its
value and reference the value after assigning it.
• 3. IN OUT : An IN OUT parameter passes an initial value to a subprogram
and returns an updated value to the caller. It can be assigned a value and
the value can be read.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 108
• Syntax to create Function
• CREATE [OR REPLACE] FUNCTION function_name [parameters]
• [(parameter_name [IN | OUT | IN OUT] type [, ...])]
• RETURN return_datatype
• {IS | AS}
• 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.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 109
• PL/SQL Function Example
• Let's see a simple example to create a function.
• create or replace function adder(n1 in number, n2 in number)
• return number
• is
• n3 number(8);
• begin
• n3 :=n1+n2;
• return n3;
• end;
• /
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 110
• Now write another program to call the function
• DECLARE
• n3 number(2);
• BEGIN
• n3 := adder(11,22);
• dbms_output.put_line('Addition is: ' || n3);
• END;
• /
Output:
Addition is: 33
Statement processed.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 111
• PL/SQL Drop Function
• Functions Drop Syntax
• DROP FUNCTION function_name;
• DROP FUNCTION adder;
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 112
• PL/SQL Trigger
• Trigger is invoked by Oracle engine automatically whenever a specified
event occurs. Trigger is stored into database and invoked repeatedly, when
specific condition match.
• 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).
• A database definition (DDL) statement (CREATE, ALTER, or DROP).
• A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 113
• Syntax for creating trigger:
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 114
create trigger [trigger_name] [before | after] {insert | update | delete} on
[table_name] [for each row] [trigger_body]
create trigger [trigger_name]: Creates or replaces an existing trigger with the
trigger_name.
[before | after]: This specifies when the trigger will be executed.
{insert | update | delete}: This specifies the DML operation.
on [table_name]: This specifies the name of the table associated with the trigger.
[for each row]: This specifies a row-level trigger, i.e., the trigger will be executed
for each row being affected.
[trigger_body]: This provides the operation to be performed as trigger is fired
• PL/SQL Trigger Example
• Let's take a simple example to demonstrate the trigger. In this example, we
are using the following CUSTOMERS table:
• Create trigger:
• Let's take a program to create a row level trigger for the CUSTOMERS table
that would fire for INSERT or UPDATE or DELETE operations performed on
the CUSTOMERS table.
• This trigger will display the salary difference between the old values and
new values:
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 115
ID Name Age Address Salary
1 Ramesh 10 Aurangabad 20000
2 Suresh 60 Kanpur 25000
3 Mahesh 30 Ghaziabad 30000
4 Ankita 20 Paris 35000
• CREATE OR REPLACE TRIGGER display_salary_changes
• BEFORE DELETE OR INSERT OR UPDATE ON customers
• FOR EACH ROW
• WHEN (NEW.ID > 0)
• DECLARE
• sal_diff number;
• BEGIN
• sal_diff := :NEW.salary - :OLD.salary;
• dbms_output.put_line('Old salary: ' || :OLD.salary);
• dbms_output.put_line('New salary: ' || :NEW.salary);
• dbms_output.put_line('Salary difference: ' || sal_diff);
• END; /
• After the execution of the above code at SQL Prompt, it produces the
following result.
• Trigger created.
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 116
• Check the salary difference by procedure:
• Use the following code to get the old salary, new salary and salary
difference after the trigger created.
• DECLARE
• total_rows number(2);
• BEGIN
• UPDATE customers SET salary = salary + 5000;
• IF sql%notfound THEN
• dbms_output.put_line('no customers updated');
• ELSIF sql%found THEN
• total_rows := sql%rowcount;
• dbms_output.put_line( total_rows || ' customers updated ');
• END IF;
• END;
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 117
• Output:
• Old salary: 20000
• New salary: 25000
• Salary difference: 5000
• Old salary: 25000
• New salary: 30000
• Salary difference: 5000
• Old salary: 30000
• New salary: 35000
• Salary difference: 5000
• Old salary: 35000
• New salary: 40000
• Salary difference: 5000
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 118
References
• Book-Introduction to database management systems, ISRD
Group
119
Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 120

More Related Content

Similar to Unit4_DBMS.pptx

Subhabrata Deb Resume
Subhabrata Deb ResumeSubhabrata Deb Resume
Subhabrata Deb Resume
Subhabrata Deb
 
chetan_resume
chetan_resumechetan_resume
chetan_resume
CHETAN PATIL
 
Sangeetha_G
Sangeetha_GSangeetha_G
shibindas_Plsql2year
shibindas_Plsql2yearshibindas_Plsql2year
shibindas_Plsql2year
shibindas pk
 
vikram ch resume
vikram ch resumevikram ch resume
vikram ch resume
vikram cherukuri
 
cchoubey_resume
cchoubey_resumecchoubey_resume
cchoubey_resume
Chandra Bhushan Choubey
 
Presenter manual oracle D2K (specially for summer interns)
Presenter manual oracle D2K (specially for summer interns)Presenter manual oracle D2K (specially for summer interns)
Presenter manual oracle D2K (specially for summer interns)
XPERT INFOTECH
 
Exploring plsql new features best practices september 2013
Exploring plsql new features best practices   september 2013Exploring plsql new features best practices   september 2013
Exploring plsql new features best practices september 2013
Andrejs Vorobjovs
 
Aectl embedded-system-training-institute-bangalore
Aectl embedded-system-training-institute-bangaloreAectl embedded-system-training-institute-bangalore
Aectl embedded-system-training-institute-bangalore
AECTL Training
 
Plsql overview
Plsql overviewPlsql overview
Plsql overview
Gagan Deep
 
oracle plsql training | oracle online training | oracle plsql demo | oracle p...
oracle plsql training | oracle online training | oracle plsql demo | oracle p...oracle plsql training | oracle online training | oracle plsql demo | oracle p...
oracle plsql training | oracle online training | oracle plsql demo | oracle p...
Nancy Thomas
 
Shridhar_Bhat 3.8Years PLSQL
Shridhar_Bhat 3.8Years PLSQLShridhar_Bhat 3.8Years PLSQL
Shridhar_Bhat 3.8Years PLSQL
Shridhar Bhat
 
Understanding the SQL aspects of Spark - Spark SQL.pptx
Understanding the SQL aspects of Spark - Spark SQL.pptxUnderstanding the SQL aspects of Spark - Spark SQL.pptx
Understanding the SQL aspects of Spark - Spark SQL.pptx
Knoldus Inc.
 
RESUME of Avik 22nd Apr
RESUME of Avik 22nd AprRESUME of Avik 22nd Apr
RESUME of Avik 22nd Apr
Avik Mandal
 
Database management system chapter5
Database management system chapter5Database management system chapter5
Database management system chapter5
Pranab Dasgupta
 
Vineet Kurrewar
Vineet KurrewarVineet Kurrewar
Vineet Kurrewar
Vineet Kurrewar
 
ABHINAV KAUSHIK(IT Professional)
ABHINAV KAUSHIK(IT Professional)ABHINAV KAUSHIK(IT Professional)
ABHINAV KAUSHIK(IT Professional)
Abhinav Kaushik
 
Resume
ResumeResume
Resume
rajkarove
 
Kamal _Resume _edit
Kamal _Resume _editKamal _Resume _edit
Kamal _Resume _edit
kamal bhatia
 
Resume_Md ZakirHussain
Resume_Md ZakirHussainResume_Md ZakirHussain
Resume_Md ZakirHussain
zakir hussain
 

Similar to Unit4_DBMS.pptx (20)

Subhabrata Deb Resume
Subhabrata Deb ResumeSubhabrata Deb Resume
Subhabrata Deb Resume
 
chetan_resume
chetan_resumechetan_resume
chetan_resume
 
Sangeetha_G
Sangeetha_GSangeetha_G
Sangeetha_G
 
shibindas_Plsql2year
shibindas_Plsql2yearshibindas_Plsql2year
shibindas_Plsql2year
 
vikram ch resume
vikram ch resumevikram ch resume
vikram ch resume
 
cchoubey_resume
cchoubey_resumecchoubey_resume
cchoubey_resume
 
Presenter manual oracle D2K (specially for summer interns)
Presenter manual oracle D2K (specially for summer interns)Presenter manual oracle D2K (specially for summer interns)
Presenter manual oracle D2K (specially for summer interns)
 
Exploring plsql new features best practices september 2013
Exploring plsql new features best practices   september 2013Exploring plsql new features best practices   september 2013
Exploring plsql new features best practices september 2013
 
Aectl embedded-system-training-institute-bangalore
Aectl embedded-system-training-institute-bangaloreAectl embedded-system-training-institute-bangalore
Aectl embedded-system-training-institute-bangalore
 
Plsql overview
Plsql overviewPlsql overview
Plsql overview
 
oracle plsql training | oracle online training | oracle plsql demo | oracle p...
oracle plsql training | oracle online training | oracle plsql demo | oracle p...oracle plsql training | oracle online training | oracle plsql demo | oracle p...
oracle plsql training | oracle online training | oracle plsql demo | oracle p...
 
Shridhar_Bhat 3.8Years PLSQL
Shridhar_Bhat 3.8Years PLSQLShridhar_Bhat 3.8Years PLSQL
Shridhar_Bhat 3.8Years PLSQL
 
Understanding the SQL aspects of Spark - Spark SQL.pptx
Understanding the SQL aspects of Spark - Spark SQL.pptxUnderstanding the SQL aspects of Spark - Spark SQL.pptx
Understanding the SQL aspects of Spark - Spark SQL.pptx
 
RESUME of Avik 22nd Apr
RESUME of Avik 22nd AprRESUME of Avik 22nd Apr
RESUME of Avik 22nd Apr
 
Database management system chapter5
Database management system chapter5Database management system chapter5
Database management system chapter5
 
Vineet Kurrewar
Vineet KurrewarVineet Kurrewar
Vineet Kurrewar
 
ABHINAV KAUSHIK(IT Professional)
ABHINAV KAUSHIK(IT Professional)ABHINAV KAUSHIK(IT Professional)
ABHINAV KAUSHIK(IT Professional)
 
Resume
ResumeResume
Resume
 
Kamal _Resume _edit
Kamal _Resume _editKamal _Resume _edit
Kamal _Resume _edit
 
Resume_Md ZakirHussain
Resume_Md ZakirHussainResume_Md ZakirHussain
Resume_Md ZakirHussain
 

Recently uploaded

一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
nedcocy
 
SCALING OF MOS CIRCUITS m .pptx
SCALING OF MOS CIRCUITS m                 .pptxSCALING OF MOS CIRCUITS m                 .pptx
SCALING OF MOS CIRCUITS m .pptx
harshapolam10
 
Open Channel Flow: fluid flow with a free surface
Open Channel Flow: fluid flow with a free surfaceOpen Channel Flow: fluid flow with a free surface
Open Channel Flow: fluid flow with a free surface
Indrajeet sahu
 
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
upoux
 
Generative AI Use cases applications solutions and implementation.pdf
Generative AI Use cases applications solutions and implementation.pdfGenerative AI Use cases applications solutions and implementation.pdf
Generative AI Use cases applications solutions and implementation.pdf
mahaffeycheryld
 
Digital Twins Computer Networking Paper Presentation.pptx
Digital Twins Computer Networking Paper Presentation.pptxDigital Twins Computer Networking Paper Presentation.pptx
Digital Twins Computer Networking Paper Presentation.pptx
aryanpankaj78
 
Accident detection system project report.pdf
Accident detection system project report.pdfAccident detection system project report.pdf
Accident detection system project report.pdf
Kamal Acharya
 
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
Paris Salesforce Developer Group
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
21UME003TUSHARDEB
 
Object Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOADObject Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOAD
PreethaV16
 
Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...
Prakhyath Rai
 
Data Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason WebinarData Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason Webinar
UReason
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Sinan KOZAK
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
uqyfuc
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
ydzowc
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
ElakkiaU
 
SENTIMENT ANALYSIS ON PPT AND Project template_.pptx
SENTIMENT ANALYSIS ON PPT AND Project template_.pptxSENTIMENT ANALYSIS ON PPT AND Project template_.pptx
SENTIMENT ANALYSIS ON PPT AND Project template_.pptx
b0754201
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
Prakhyath Rai
 
Call For Paper -3rd International Conference on Artificial Intelligence Advan...
Call For Paper -3rd International Conference on Artificial Intelligence Advan...Call For Paper -3rd International Conference on Artificial Intelligence Advan...
Call For Paper -3rd International Conference on Artificial Intelligence Advan...
ijseajournal
 
Height and depth gauge linear metrology.pdf
Height and depth gauge linear metrology.pdfHeight and depth gauge linear metrology.pdf
Height and depth gauge linear metrology.pdf
q30122000
 

Recently uploaded (20)

一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
 
SCALING OF MOS CIRCUITS m .pptx
SCALING OF MOS CIRCUITS m                 .pptxSCALING OF MOS CIRCUITS m                 .pptx
SCALING OF MOS CIRCUITS m .pptx
 
Open Channel Flow: fluid flow with a free surface
Open Channel Flow: fluid flow with a free surfaceOpen Channel Flow: fluid flow with a free surface
Open Channel Flow: fluid flow with a free surface
 
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
 
Generative AI Use cases applications solutions and implementation.pdf
Generative AI Use cases applications solutions and implementation.pdfGenerative AI Use cases applications solutions and implementation.pdf
Generative AI Use cases applications solutions and implementation.pdf
 
Digital Twins Computer Networking Paper Presentation.pptx
Digital Twins Computer Networking Paper Presentation.pptxDigital Twins Computer Networking Paper Presentation.pptx
Digital Twins Computer Networking Paper Presentation.pptx
 
Accident detection system project report.pdf
Accident detection system project report.pdfAccident detection system project report.pdf
Accident detection system project report.pdf
 
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
 
Object Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOADObject Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOAD
 
Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...
 
Data Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason WebinarData Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason Webinar
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
原版制作(Humboldt毕业证书)柏林大学毕业证学位证一模一样
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
 
SENTIMENT ANALYSIS ON PPT AND Project template_.pptx
SENTIMENT ANALYSIS ON PPT AND Project template_.pptxSENTIMENT ANALYSIS ON PPT AND Project template_.pptx
SENTIMENT ANALYSIS ON PPT AND Project template_.pptx
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
 
Call For Paper -3rd International Conference on Artificial Intelligence Advan...
Call For Paper -3rd International Conference on Artificial Intelligence Advan...Call For Paper -3rd International Conference on Artificial Intelligence Advan...
Call For Paper -3rd International Conference on Artificial Intelligence Advan...
 
Height and depth gauge linear metrology.pdf
Height and depth gauge linear metrology.pdfHeight and depth gauge linear metrology.pdf
Height and depth gauge linear metrology.pdf
 

Unit4_DBMS.pptx

  • 1. SANJIVANI K. B. P. POLYTECHNIC, KOPARGAON With NBA ACCREDIATED programs , Approved by AICTE, New Delhi, Recognized by Govt. of Maharashtra, Affiliated to Maharashtra State Board of Technical Education, Mumbai, ISO 9001:2015 Certified Institute Department:- Computer Technology Class:-SYCM Name of Subject:-Database Management System MSBTE Subject Code:- 22319 Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 1
  • 2. Unit 4 PL/SQL Programming Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 2
  • 3. Unit Outcomes • 4a.write simple PL/SQL code using control structure and handle various exception in the given situation. • 4b.Create cursor for retrieving multiple records in the given situation. • 4c.Create and execute stored procedures and functions in the given situation. • 4d.Create and apply database trigger using PL/SQL in the given situation. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 3
  • 4. • PL/SQL • PL/SQL is a block of codes that used to write the entire program blocks/ procedure/ function, etc. • PL/SQL fully supports SQL data types. You need not convert between PL/SQL and SQL data types. • SQL is a non-procedural language that executes a single query at a time whereas, PL/SQL is a procedural language and executes blocks of code at once which consists of triggers, functions, procedures. • It helps reduce traffic and increases processing speed. • Developed by Oracle Corporation in the 1990s, it was designed to build server pages and web applications and exhibits features such as abstraction and error handling. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 4
  • 5. • Features of PL/SQL • PL/SQL is tightly integrated with SQL. • It offers extensive error checking. • It offers numerous data types. • It offers a variety of programming structures. • It supports structured programming through functions and procedures. • It supports object-oriented programming. • It supports developing web applications and server pages Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 5
  • 6. • Advantages of PL/SQL • PL/SQL supports both static and dynamic SQL. Static SQL supports DML operations and transaction control from PL/SQL block. In Dynamic SQL, SQL allows embedding DDL statements in PL/SQL blocks. • PL/SQL allows sending an entire block of statements to the database at one time. This reduces network traffic and provides high performance for the applications. • PL/SQL gives high productivity to programmers as it can query, transform, and update data in a database. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 6
  • 7. • PL/SQL saves time on design and debugging by strong features, such as exception handling, encapsulation, data hiding, and object- oriented data types. • Applications written in PL/SQL are fully portable. • PL/SQL provides high security level. • PL/SQL provides access to predefined SQL packages. • PL/SQL provides support for Object-Oriented Programming. • PL/SQL provides support for developing Web Applications and Server Pages. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 7
  • 8. • PL/SQL Block • Each block of PL/SQL contains the following subparts − • Declarations - • This section contains all the items that needs to be declared before the program such as variables, subprograms etc. This section contains the keyword DECLARE at its start. In general, Declarations is an optional subpart of the PL/SQL program. • Executable Commands - • This section of the PL/SQL code contains the executable statements. It contains BEGIN and END at its starting and ending. Executable commands is a compulsory section and it cannot be left blank. In case there are no executable statements, NULL is written to signify this. • Exception Handling - • This section contains the code to handle all the errors or exceptions that may arise during the course of the program. Exception handling section starts with the keyword EXCEPTION. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 8
  • 9. • Structure of a PL/SQL Block • Every PL/SQL statement ends with a semicolon (;). • The basic structure of a PL/SQL block is • Hello world example • it produces the following result Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 9 DECLARE < Declarations section > BEGIN < Executable commands section > EXCEPTION < Exception handling section > END; DECLARE message varchar2(20):= 'Hello, World!'; BEGIN dbms_output.put_line(message); END; / Hello World PL/SQL procedure successfully completed.
  • 10. • PL/SQL - Data Types • PL/SQL variables, constants and parameters must have a valid data type, which specifies a storage format, constraints, and valid range of values. • SCALAR and LOB data types available in PL/SQL and other two data types will be covered in other chapters. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 10 . Category Description Scalar Single values with no internal components, such as a NUMBER, DATE, or BOOLEAN. Large Object (LOB) Pointers to large objects that are stored separately from other data items, such as text, graphic images, video clips, and sound waveforms. It is used to store lengthy documents. Composite A composite type represents the structure of a row or record. For example, collections and records. Reference Pointers to other data items.
  • 11. • PL/SQL Scalar Data Types and Subtypes • PL/SQL Scalar Data Types and Subtypes come under the following categories: • PL/SQL provides subtypes of data types. For example, the data type NUMBER has a subtype called INTEGER. You can use subtypes in your PL/SQL program to make the data types compatible with data types in other programs while embedding PL/SQL code in another program, such as a Java program. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 11 . Data type Description Numeric Numeric values on which arithmetic operations are performed. Character Alphanumeric values that represent single characters or strings of characters. Boolean Logical values on which logical operations are performed. Datetime Dates and times.
  • 12. • PL/SQL Numeric Data Types and Subtypes • Following is the detail of PL/SQL pre-defined numeric data types and their sub-types: Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 12 . Data Type Description PLS_INTEGER Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32 bits BINARY_INTEGER Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32 bits BINARY_FLOAT Single-precision IEEE 754-format floating- point number BINARY_DOUBLE Double-precision IEEE 754-format floating-point number NUMBER(prec, scale) Fixed-point or floating-point number with absolute value in range 1E-130 to (but not including) 1.0E126. A NUMBER variable can also represent 0. DEC(prec, scale) ANSI specific fixed-point type with maximum precision of 38 decimal digits.
  • 13. Data Type Description DECIMAL(prec, scale) IBM specific fixed-point type with maximum precision of 38 decimal digits. NUMERIC(pre, secale) Floating type with maximum precision of 38 decimal digits. FLOAT ANSI and IBM specific floating-point type with maximum precision of 126 binary digits (approximately 38 decimal digits) INT ANSI specific integer type with maximum precision of 38 decimal digits INTEGER ANSI and IBM specific integer type with maximum precision of 38 decimal digits SMALLINT ANSI and IBM specific integer type with maximum precision of 38 decimal digits REAL Floating-point type with maximum precision of 63 binary digits (approximately 18 decimal digits) Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 13 .
  • 14. • Following is a valid declaration: PL/SQL Character Data Types and Subtypes Following is the detail of PL/SQL pre-defined character data types and their sub-types: Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 14 . DECLARE num1 INTEGER; num2 REAL; num3 DOUBLE PRECISION; BEGIN null; END; / Data type Description CHAR Fixed-length character string with maximum size of 32,767 bytes VARCHAR2 Variable-length character string with maximum size of 32,767 bytes RAW RAW datatype is used to store values in binary data format. The maximum size for a raw in a table in 32767 bytes. (for example, graphics or audio files)
  • 15. Data Type Description NCHAR Fixed-length national character string with maximum size of 32,767 bytes NVARCHAR2 Variable-length national character string with maximum size of 32,767 bytes LONG Variable-length character string with maximum size of 32,760 bytes LONG RAW Variable-length binary or byte string with maximum size of 32,760 bytes, not interpreted by PL/SQL ROWID A ROWID data type stores information related to the disk location of table rows. They also uniquely identify the rows in your table. UROWID The Universal ROWID ( UROWID ) is a datatype that can store both logical and physical rowids of Oracle tables. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 15 .
  • 16. • Boolean Data Types: • The BOOLEAN data type stores logical values that are used in logical operations. The logical values are the Boolean values TRUE and FALSE and the value NULL. • Datetime and interval types • The default date format is set by the Oracle initialization parameter NLS_DATE_FORMAT. • For example, the default might be 'DD-MON-YY', which includes a two-digit number for the day of the month, an abbreviation of the month name, and the last two digits of the year, for example, 01-OCT-12. • Each DATE includes the century, year, month, day, hour, minute, and second. The following table shows the valid values for each field: Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 16
  • 17. • PL/SQL Large Object (LOB) Data Types • Large object (LOB) data types refer large to data items such as text, graphic images, video clips, and sound waveforms. • LOB data types allow efficient, random, piecewise access to this data. Following are the predefined PL/SQL LOB data types: Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 17 Data type Description Size BFILE Used to store large binary objects in operating system files outside the database. System-dependent. Cannot exceed 4 gigabytes (GB). BLOB Used to store large binary objects in the database. 8 to 128 terabytes (TB) CLOB Used to store large blocks of character data in the database. 8 to 128 TB
  • 18. • PL/SQL User-Defined Subtypes • A subtype is a definition of a type based on a built-in type. • A subtype has the same valid operations as its base type, but only a subset of its valid values. • PL/SQL predefines several subtypes in package STANDARD. For example, PL/SQL predefines the subtypes CHARACTER and INTEGER as follows Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 18 SUBTYPE NAME IS CHAR; SUBTYPE PHONE_NUMBER IS NUMBER(38,0);
  • 19. • You can define and use your own subtypes. The following program illustrates defining and using a user-defined subtype: • When the above code is executed at SQL prompt, it produces the following result: Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 19 DECLARE SUBTYPE name IS char(20); SUBTYPE message IS varchar2(100); salutation name; greetings message; BEGIN salutation := 'Reader '; greetings := 'Welcome to the World of PL/SQL'; dbms_output.put_line('Hello ' || salutation || greetings); END; / Hello Reader Welcome to the World of PL/SQL PL/SQL procedure successfully completed.
  • 20. • PL/SQL Variable • PL/SQL variables must be declared in the declaration section or in a package as a global variable. • When we declare a variable, PL/SQL allocates memory for the variable's value and the storage location is identified by the variable name. • The syntax for declaring a variable is: • variable_name datatype = [initial_value] • Where, variable_name is a valid identifier in PL/SQL, datatype must be a valid PL/SQL data type or any user defined data type. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 20
  • 21. • Example • It is a good programming practice to initialize variables properly otherwise, sometimes program would produce unexpected result. • Try the following example which makes use of various types of variables: • DECLARE • a integer := 10; • b integer := 20; • c integer; • f real; • BEGIN • c := a + b; • dbms_output.put_line('Value of c:' || c); • f := 70.0/3.0; dbms_output.put_line('Value of f: ' || f); • END; / • When the above code is executed, it produces the following result: • Value of c: 30 Value of f: 23.333333333333333333 Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 21
  • 22. • There are two types of variable scope • Local Variable: • Local variables are the inner block variables which are not accessible to outer blocks. • Global Variable: • Global variables are declared in outermost block. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 22
  • 23. • Variable scope in PL/SQL • Following example shows the usage of Local and Global variables in its simple form: • DECLARE • -- Global variables • num1 number := 95; • num2 number := 85; • BEGIN • dbms_output.put_line('Outer Variable num1: ' || num1); • dbms_output.put_line('Outer Variable num2: ' || num2); • DECLARE • -- Local variables • num1 number := 195; • num2 number := 185; • BEGIN • dbms_output.put_line('Inner Variable num1: ' || num1); • dbms_output.put_line('Inner Variable num2: ' || num2); 23 When the above code is executed, it produces the following result: Outer Variable num1: 95 Outer Variable num2: 85 Inner Variable num1: 195 Inner Variable num2: 185
  • 24. • PL/SQL Constant • PL/SQL - Constants Declaring a Constant • A constant is declared using the CONSTANT keyword. It requires an initial value and does not allow that value to be changed. • For example: • General Syntax to declare a constant is: • constant_name CONSTANT datatype := VALUE; • constant_name is the name of the constant i.e. similar to a variable name. • The word CONSTANT is a reserved word and ensures that the value does not change. • VALUE - It is a value which must be assigned to a constant when it is declared. You cannot assign a value later. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 24 .
  • 25. • For example, to declare salary_increase, you can write code as follows: • DECLARE • salary_increase CONSTANT number (3) := 10; • You must assign a value to a constant at the time you declare it. • If you do not assign a value to a constant while declaring it and try to assign a value in the execution section, you will get a error. • If you execute the below Pl/SQL block you will get error. • DECLARE • salary_increase CONSTANT number(3); • BEGIN • salary_increase := 100; • dbms_output.put_line (salary_increase); • END; Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 25
  • 26. • PL/SQL - Operators • An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulation. • PL/SQL language is rich in built-in operators and provides the following types of operators: • Arithmetic operators • Relational operators • Comparison operators • Logical operators • String operators Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 26
  • 27. • Arithmetic Operators • Following table shows all the arithmetic operators supported by PL/SQL. Assume variable A holds 10 and variable B holds 5 then: Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 27 Operator Description Example + Adds two operands A + B will give 15 - Subtracts second operand from the first A - B will give 5 * Multiplies both operands A*B gives 50 / Divides numerator by de- numerator A / B will give 2 ** Exponentiation operator, raises one operand to the power of other A ** B will give 100000
  • 28. • Relational Operators • Relational operators compare two expressions or values and return a Boolean result. • Following table shows all the relational operators supported by PL/SQL. Assume variable A holds 10 and variable B holds 20, then: • Show Examples != <> ~= Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 28
  • 29. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 29 Operator Description Example = Checks if the values of two operands are equal or not, if yes then condition becomes true. (A = B) is not true. != Checks if the values of two operands are equal or not, if values are not equal then condition (A != B) is true. > Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true. < Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true.
  • 30. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 30 Operator Description Example >= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true. <= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true.
  • 31. • Comparison Operators • Comparison operators are used for comparing one expression to another. The result is always either TRUE, FALSE OR NULL. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 31 Operator Description Example LIKE The LIKE operator compares a character, string, or CLOB value to a pattern and returns TRUE if the value matches the pattern and FALSE if it does not. If 'Zara Ali' like 'Z% A_i' returns a Boolean true, whereas, 'Nuha Ali' like 'Z% A_i' returns a Boolean false BETWEEN The BETWEEN operator tests whether a value lies in a specified range. x BETWEEN a AND b means that x >= a and x <= b. If x = 10 then, x between 5 and 20 returns true, x between 5 and 10 returns true, but x between 11 and 20 returns false.
  • 32. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 32 Operator Description Example IN The IN operator tests set membership. x IN (set) means that x is equal to any member of set. If x = 'm' then, x in ('a', 'b', 'c') returns boolean false but x in ('m', 'n', 'o') returns Boolean true. IS NULL The IS NULL operator returns the BOOLEAN value TRUE if its operand is NULL or FALSE if it is not NULL. Comparisons involving NULL values always yield NULL. If x = 'm', then 'x is null' returns Boolean false.
  • 33. • Logical Operators • Following table shows the Logical operators supported by PL/SQL. All these operators work on Boolean operands and produces Boolean results. • Assume variable A holds true and variable B holds false, then: Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 33 Operator Description Example AND Called logical AND operator. If both the operands are true then condition becomes true. (A and B) is false. OR Called logical OR Operator. If any of the two operands is true then condition becomes true. (A or B) is true not Called logical NOT Operator. Used to reverse the logical state of its operand. If a condition is true then Logical NOT operator will make it false. not (A and B) is true.
  • 34. • PL/SQL – Conditions • IF statement It is the simplest form of IF control statement, frequently used in decision making and changing the control flow of the program execution. • The IF statement associates a condition with a sequence of statements enclosed by the keywords THEN and END IF. • If the condition is TRUE, the statements get executed, and if the condition is FALSE or NULL, then the IF statement does nothing. • Syntax for IF-THEN statement is: • IF condition THEN • S; • END IF; Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 34
  • 35. • If the Boolean expression condition evaluates to true then the block of code inside the if statement will be executed. • If Boolean expression evaluates to false then the first set of code after the end of the if statement (after the closing end if) will be executed. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 35
  • 36. • Example 1: • DECLARE • a number(2) := 10; • BEGIN • a:= 10; • -- check the boolean condition using if statement • IF( a < 20 ) • THEN • -- if condition is true then print the following • dbms_output.put_line('a is less than 20 ' ); • END IF; • dbms_output.put_line('value of a is : ' || a); • END; / • When the above code is executed at SQL prompt, it produces the following result: • a is less than 20 value of a is : 10 • PL/SQL procedure successfully completed. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 36
  • 37. • IF-THEN-ELSE Statement • A sequence of IF-THEN statements can be followed by an optional sequence of ELSE statements, which execute when the condition is FALSE. • IF condition THEN • S1; • ELSE • S2; • END IF; • Where, S1 and S2 are different sequence of statements. In the IF-THEN-ELSE statements, when the test condition is TRUE, the statement S1 is executed andS2 is skipped; when the test condition is FALSE, then S1 is bypassed and statement S2 is executed. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 37
  • 38. • Flow Diagram Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 38
  • 39. • Example • Output 39 DECLARE a NUMBER:=11; BEGIN dbms_output.put_line (‘Program started'); IF( mod(a,2)=0) THEN dbms_output.put_line('a is even number' ); ELSE dbms_output.put_line('a is odd number1); END IF; dbms_output.put_line (‘Program completed.’); END; / Program started. a is odd number Program completed.
  • 40. • Example • DECLARE a number(3) := 100; • BEGIN • -- check the boolean condition using if statement • IF( a < 20 ) • THEN • -- if condition is true then print the following • dbms_output.put_line('a is less than 20 ' ); • ELSE • dbms_output.put_line('a is not less than 20 ' ); • END IF; • dbms_output.put_line('value of a is : ' || a); • END; / • When the above code is executed at SQL prompt, it produces the following result: • a is not less than 20 • value of a is : 100 • PL/SQL procedure successfully completed 40
  • 41. • IF-THEN-ELSIF • The IF-THEN-ELSIF statement allows you to choose between several alternatives. • An IF-THEN statement can be followed by an optional ELSIF...ELSE statement. • The ELSIF clause lets you add additional conditions. When using IF-THEN-ELSIF statements there are few points to keep in mind. • It's ELSIF, not ELSEIF • An IF-THEN statement can have zero to many ELSIF's and they must come before the ELSE. • Once an ELSIF succeeds, none of the remaining ELSIF's or ELSE's will be tested. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 41
  • 42. • Syntax: • The syntax of an IF-THEN-ELSIF Statement in PL/SQL programming language is: Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 42 IF(boolean_expression 1)THEN S1; -- Executes when the boolean expression 1 is true ELSIF( boolean_expression 2) THEN S2; -- Executes when the boolean expression 2 is true ELSIF( boolean_expression 3) THEN S3; -- Executes when the boolean expression 3 is true ELSE S4; -- executes when the none of the above condition is true END IF;
  • 43. • Example: • When the above code is executed at SQL prompt, it produces the following result: • None of the values is matching Exact value of a is: 100 • PL/SQL procedure successfully completed. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 43 DECLARE a number(3) := 100; BEGIN IF ( a = 10 ) THEN dbms_output.put_line('Value of a is 10' ); ELSIF ( a = 20 ) THEN dbms_output.put_line('Value of a is 20' ); ELSIF ( a = 30 ) THEN dbms_output.put_line('Value of a is 30' ); ELSE dbms_output.put_line('None of the values is matching'); END IF; dbms_output.put_line('Exact value of a is: '|| a ); END; /
  • 44. • PL/SQL - Searched CASE Statement • The searched CASE statement has no selector and its WHEN clauses contain search conditions that give Boolean values. • Syntax: The syntax for searched case statement in PL/SQL is: • CASE • WHEN selector = 'value1' THEN S1; • WHEN selector = 'value2' THEN S2; • WHEN selector = 'value3' THEN S3; • ... ELSE Sn; -- default case • END CASE; Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 44
  • 45. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 45 • Flow Structure
  • 46. • Example • DECLARE • grade char(1) := 'B'; • BEGIN • case • when grade = 'A' then dbms_output.put_line('Excellent'); • when grade = 'B' then dbms_output.put_line('Very good'); • when grade = 'C' then dbms_output.put_line('Well done'); • when grade = 'D' then dbms_output.put_line('You passed'); • when grade = 'F' then dbms_output.put_line('Better try again'); • else dbms_output.put_line('No such grade'); • end case; • END; • / • When the above code is executed at SQL prompt, it produces the following result: • Very good • PL/SQL procedure successfully completed. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 46
  • 47. • PL/SQL - Nested IF-THEN-ELSE Statements • It is always legal in PL/SQL programming to nest IF-ELSE statements, which means you can use one IF or ELSE IF statement inside another IF or ELSE IF statement(s). • Syntax: • IF( boolean_expression 1)THEN • -- executes when the boolean expression 1 is true • IF(boolean_expression 2) THEN • -- executes when the boolean expression 2 is true • sequence-of-statements; • END IF; • ELSE • -- executes when the boolean expression 1 is not true • else-statements; • END IF; Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 47
  • 48. • Example: • DECLARE • a number(3) := 100; • b number(3) := 200; • BEGIN -- check the boolean condition • IF( a = 100 ) THEN -- if condition is true then check the following • IF( b = 200 ) THEN -- if condition is true then print the following dbms_output.put_line('Value of a is 100 and b is 200' ); • END IF; • END IF; • dbms_output.put_line('Exact value of a is : ' || a ); • dbms_output.put_line('Exact value of b is : ' || b ); • END; / • When the above code is executed at SQL prompt, it produces the following result: • Value of a is 100 and b is 200 • Exact value of a is : 100 • Exact value of b is : 200 • PL/SQL procedure successfully completed. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 48
  • 49. • PL/SQL –Loops • A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages: • PL/SQL -Basic Loop Statement • Basic loop structure encloses sequence of statements in between the LOOP and END LOOP statements. With each iteration, the sequence of statements is executed and then control resumes at the top of the loop. • Syntax: • The syntax of a basic loop in PL/SQL programming language is: • LOOP • Sequence of statements; • END LOOP; Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 49
  • 50. • Flow Diagram Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 50
  • 51. • PL/SQL -WHILE LOOP Statement • A WHILE LOOP statement in PL/SQL programming language repeatedly executes a target statement as long as a given condition is true. • Syntax: • WHILE condition LOOP • sequence_of_statements • END LOOP; Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 51
  • 52. • PL/SQL -WHILE LOOP Statement • Example: • DECLARE • a number(2) := 10; • BEGIN • WHILE a < 20 LOOP • dbms_output.put_line('value of a: ' || a); • a := a + 1; • END LOOP; • END; / • When the above code is executed at SQL prompt, it produces the following result: • value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19 PL/SQL procedure successfully completed Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 52
  • 53. • PL/SQL - FOR LOOP Statement • A FOR LOOP is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. • Syntax: • FOR counter IN initial_value .. final_value LOOP sequence_of_statements; • END LOOP; Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 53
  • 54. • Here is the flow of control in a for loop: • The initial step is executed first, and only once. This step allows you to declare and initialize any loop control variables. • Next, the condition, i.e., initial_value .. final_value is evaluated. If it is TRUE, the body of the loop is executed. If it is FALSE, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop. • After the body of the for loop executes, the value of the counter variable is increased or decreased. • The condition is now evaluated again. If it is TRUE, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). • After the condition becomes FALSE, the FOR-LOOP terminates. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 54
  • 55. • Example: • DECLARE • a number(2); • BEGIN FOR a in 10 .. 20 LOOP • dbms_output.put_line('value of a: ' || a); • END LOOP; • END; / • When the above code is executed at SQL prompt, it produces the following result: • value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19 value of a: 20 Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 55
  • 56. • Reverse FOR LOOP Statement • By default, iteration proceeds from the initial value to the final value, generally upward from the lower bound to the higher bound. • You can reverse this order by using the REVERSE keyword. In such case, iteration proceeds the other way. After each iteration, the loop counter is decremented. • However, you must write the range bounds in ascending (not descending) order. • DECLARE • a number(2) ; • BEGIN FOR a IN REVERSE 10 .. 20 LOOP • dbms_output.put_line('value of a: ' || a); • END LOOP; • END; / • When the above code is executed at the SQL prompt, it produces the following result − 56 value of a: 20 value of a: 19 value of a: 18 value of a: 17 value of a: 16 value of a: 15 value of a: 14 value of a: 13 value of a: 12 value of a: 11 value of a: 10
  • 57. • PL/SQL - Nested Loops • PL/SQL allows using one loop inside another loop. • Following section shows few examples to illustrate the concept. The syntax for a nested basic LOOP statement in PL/SQL is as follows: • LOOP • Sequence of statements1 • LOOP • Sequence of statements2 • END LOOP; • END LOOP; Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 57
  • 58. • The syntax for a nested FOR LOOP statement in PL/SQL is as follows: • FOR counter1 IN initial_value1 .. final_value1 LOOP sequence_of_statements1 • FOR counter2 IN initial_value2 .. final_value2 LOOP sequence_of_statements2 • END LOOP; • END LOOP; Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 58
  • 59. • The syntax for a nested WHILE LOOP statement in Pascal is as follows: • WHILE condition1 LOOP • sequence_of_statements1 • WHILE condition2 LOOP • sequence_of_statements2 • END LOOP; • END LOOP; Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 59
  • 60. • The Loop Control Statements • PL/SQL -EXIT Statement The EXIT statement in PL/SQL programming language has following two usages: • When the EXIT statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop. • If you are using nested loops (i.e. one loop inside another loop), the EXIT statement will stop the execution of the innermost loop and start executing the next line of code after the block. • Syntax: The syntax for an EXIT statement in PL/SQL is as follows: • EXIT; Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 60
  • 61. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 61
  • 62. • The EXIT WHEN Statement • The EXIT-WHEN statement allows the condition in the WHEN clause to be evaluated. • If the condition is true, the loop completes and control passes to the statement immediately after END LOOP. • Following are two important aspects for the EXIT WHEN statement: • Until the condition is true, the EXIT-WHEN statement acts like a NULL statement, except for evaluating the condition, and does not terminate the loop. • A statement inside the loop must change the value of the condition. • Syntax: • The syntax for an EXIT WHEN statement in PL/SQL is as follows: • EXIT WHEN condition; Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 62
  • 63. • Example: • DECLARE • a number(2) := 10; • BEGIN -- while loop execution • WHILE a < 20 LOOP • dbms_output.put_line ('value of a: ' || a); • a := a + 1; • -- terminate the loop using the exit when statement • EXIT WHEN a > 15; • END LOOP; • END; / Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 63
  • 64. • When the above code is executed at SQL prompt, it produces the following result: • 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. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 64
  • 65. • PL/SQL - CONTINUE Statement • The CONTINUE statement causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. • The continue statement allows you to exit the current loop iteration and immediately continue on to the next iteration of that loop. • Syntax: • The syntax for a CONTINUE statement is as follows: • CONTINUE; Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 65
  • 66. • Flow Diagram Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 66
  • 67. • Example: • DECLARE • a number(2) := 10; • BEGIN -- while loop execution • WHILE a < 20 LOOP • dbms_output.put_line ('value of a: ' || a); • a := a + 1; • IF a = 15 THEN -- skip the loop using the • CONTINUE statement • a := a + 1; • CONTINUE; • END IF; • END LOOP; • END; / Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 67
  • 68. • When the above code is executed at SQL prompt, it produces the following result: • value of a: 10 • value of a: 11 • value of a: 12 • value of a: 13 • value of a: 14 • value of a: 16 • value of a: 17 • value of a: 18 • value of a: 19 • PL/SQL procedure successfully completed. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 68
  • 69. • PL/SQL - GOTO Statement • A GOTO statement in PL/SQL programming language provides an unconditional jump from the GOTO to a labeled statement in the same subprogram. • Syntax: • The syntax for a GOTO statement in PL/SQL is as follows: • GOTO • label; • .. • .. • << label >> • statement; Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 69
  • 70. • Flow Diagram Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 70
  • 71. • Example: • DECLARE • a number(2) := 10; • BEGIN • <<loopstart>> -- while loop execution • WHILE a < 20 LOOP • dbms_output.put_line ('value of a: ' || a); • a := a + 1; • IF a = 15 THEN • a := a + 1; • GOTO loopstart; • END IF; • END LOOP; • END; / Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 71
  • 72. • When the above code is executed at SQL prompt, it produces the following result: • value of a: 10 • value of a: 11 • value of a: 12 • value of a: 13 • value of a: 14 • value of a: 16 • value of a: 17 • value of a: 18 • value of a: 19 • PL/SQL procedure successfully completed. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 72
  • 73. • PL/SQL –Exceptions • An error condition during a program execution is called an exception in PL/SQL. • PL/SQL supports programmers to catch such conditions using EXCEPTION block in the program and an appropriate action is taken against the error condition. • There are two types of exceptions: • System-defined exceptions • User-defined exceptions Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 73
  • 74. • Syntax for Exception Handling • The General Syntax for exception handling is as follows. Here you can list down as many as exceptions you want to handle. The default exception will be handled using WHEN others THEN: • DECLARE • <declarations section> • BEGIN • <executable command(s)> • EXCEPTION • <exception handling goes here > • WHEN exception1 THEN • exception1-handling-statements • WHEN exception2 THEN • exception2-handling-statements • WHEN exception3 THEN • exception3-handling-statements ........ • WHEN others THEN • exception-handling-statements END; 74
  • 75. • Example of exception handling • Let's take a simple example to demonstrate the concept of exception handling. Here we are using the already created CUSTOMERS table. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 75 ID Name Age Address Salary 1 Ramesh 10 Aurangabad 20000 2 Suresh 60 Kanpur 24000 3 Mahesh 30 Ghaziabad 28000 4 Ankita 20 Paris 30000 5 Nikita 40 Delhi 32000 6 Sunita 50 Nagpur 36000
  • 76. • DECLARE • c_id customers.id%type := 8; • c_name customers.name%type; • c_addr customers.address%type; • BEGIN • SELECT name, address INTO c_name, c_addr FROM customers WHERE id = c_id; • DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name); • DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr); • EXCEPTION • WHEN no_data_found THEN • dbms_output.put_line('No such customer!'); • WHEN others THEN • dbms_output.put_line('Error!'); • END; • / • %type attribute ensures that type compatibility between table column and PL/SQL variables is maintained • Syntax of Type Variable name typed-attribute %Type 76
  • 77. • When the above code is executed at the SQL prompt, it produces the following result − • No such customer! PL/SQL procedure successfully completed. • The above program displays the name and address of a customer whose ID is given. • Since there is no customer with ID value 8 in our database, the program raises the run-time exception NO_DATA_FOUND, which is captured in the EXCEPTION block. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 77
  • 78. • User-defined Exceptions • This type of users can create their own exceptions according to the need and to raise these exceptions explicitly raise command is used. Example: • Divide non-negative integer x by y such that the result is greater than or equal to 1.From the given question we can conclude that there exist two exceptions • Division be zero. • If result is greater than or equal to 1 means y is less than or equal to x. • The syntax for declaring an exception is: • DECLARE • my-exception EXCEPTION; Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 78
  • 79. 79 DECLARE x int:=&x; /*taking value at run time*/ y int:=&y; div_r float; exp1 EXCEPTION; exp2 EXCEPTION; BEGIN IF y=0 then raise exp1; ELSEIF y > x then raise exp2; ELSE div_r:= x / y; dbms_output.put_line('the result is '||div_r); END IF; EXCEPTION WHEN exp1 THEN dbms_output.put_line('Error'); dbms_output.put_line('division by zero not allowed'); WHEN exp2 THEN dbms_output.put_line('Error'); dbms_output.put_line('y is greater than x please check the input');
  • 80. 80 • Input 1: x=20 • Y=10 • Output: the result is 2 • Input 2: x=20 • Y=0 • Output • Error • Division by zero not allowed • Input 3: x=20 • Y=30 • Output:<.em> • Error • Y is greater than x please check the input
  • 81. • Pre-defined Exceptions • PL/SQL provides many pre-defined exceptions, which are executed when any database rule is violated by a program. • For example, the predefined exception NO_DATA_FOUND is raised when a SELECT INTO statement returns no rows. • System defined exceptions: These exceptions are predefined in PL/SQL which get raised WHEN certain database rule is violated. System-defined exceptions are further divided into two categories: • Named system exceptions. • Unnamed system exceptions. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 81
  • 82. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 82 • Named system exceptions: They have a predefined name by the system like ACCESS_INTO_NULL, DUP_VAL_ON_INDEX, LOGIN_DENIED etc. the list is quite big.So we will discuss some of the most commonly used exceptions: • Lets create a table geeks.
  • 83. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 83 • NO_DATA_FOUND: • It is raised WHEN a SELECT INTO statement returns no rows. For eg: • Output: DECLARE temp varchar(20); BEGIN SELECT g_id into temp from geeks where g_name='GeeksforGeeks'; exception WHEN no_data_found THEN dbms_output.put_line('ERROR'); dbms_output.put_line('there is no name as'); dbms_output.put_line('GeeksforGeeks in geeks table'); end; ERROR there is no name as GeeksforGeeks in geeks table
  • 84. 84 • TOO_MANY_ROWS: • It is raised WHEN a SELECT INTO statement returns more than one row. • Output: • Error trying to select too many rows DECLARE temp varchar(20); BEGIN -- raises an exception as SELECT -- into trying to return too many rows SELECT g_name into temp from geeks; dbms_output.put_line(temp); EXCEPTION WHEN too_many_rows THEN dbms_output.put_line('error trying to SELECT too many rows'); end;
  • 85. 85 • VALUE_ERROR: • This error is raised WHEN a statement is executed that resulted in an arithmetic, numeric, string, conversion, or constraint error. This error mainly results from programmer error or invalid data input. Output Error Change data type of temp to varchar(20) DECLARE temp number; BEGIN SELECT g_name into temp from geeks where g_name='Suraj'; dbms_output.put_line('the g_name is '||temp); EXCEPTION WHEN value_error THEN dbms_output.put_line('Error'); dbms_output.put_line('Change data type of temp to varchar(20)'); END;
  • 86. • Zero Divide • raises exception WHEN dividing with zero. • Output • Dividing by zero please check the values again • The value of a is 10 • The value of b is 0 86 DECLARE a int:=10; b int:=0; answer int; BEGIN answer:=a/b; dbms_output.put_line('the result after division is'||answer); exception WHEN zero_divide THEN dbms_output.put_line('dividing by zero please check the values again'); dbms_output.put_line('the value of a is '||a); dbms_output.put_line('the value of b is '||b); END;
  • 87. • Cursor • 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 statement. • Cursor is a Temporary Memory or Temporary Work Station. • It is Allocated by Database Server at the Time of Performing DML(Data Manipulation Language) operations on Table by User. Cursors are used to store Database Tables. • There are 2 types of Cursors: • Implicit Cursors(generated by Oracle) • Explicit Cursors(generated by user) Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 87
  • 88. • Implicit Cursors • Implicit Cursors are also known as Default Cursors of SQL SERVER. • These Cursors are allocated by SQL SERVER when the user performs DML operations. • These are created by default to process the statements when DML statements like INSERT, UPDATE, DELETE etc. are executed. • Oracle provides some attributes known as Implicit cursor's attributes to check the status of DML operations. Some of them are: %FOUND, %NOTFOUND, %ROWCOUNT and %ISOPEN. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 88
  • 89. Attribute Description %FOUND Its return value is TRUE if DML statements like INSERT, DELETE and UPDATE affect at least one row or more rows or a SELECT INTO statement returned one or more rows. Otherwise it returns FALSE. %NOTFOUND Its return value is TRUE if DML statements like INSERT, DELETE and UPDATE affect no row, or a SELECT INTO statement return no rows. Otherwise it returns FALSE. It is a just opposite of %FOUND. %ISOPEN It always returns FALSE for implicit cursors, because the SQL cursor is automatically closed after executing its associated SQL statements. %ROWCOUNT It returns the number of rows affected by DML statements like INSERT, DELETE, and UPDATE or returned by a SELECT INTO statement. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 89
  • 90. • Customer Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 90 ID Name Age Address Salary 1 Ramesh 10 Aurangabad 20000 2 Suresh 60 Kanpur 24000 3 Mahesh 30 Ghaziabad 28000 4 Ankita 20 Paris 30000 5 Nikita 40 Delhi 32000 6 Sunita 50 Nagpur 36000
  • 91. • DECLARE • total_rows number(2); • BEGIN • UPDATE customers • SET salary = salary + 5000; • IF sql%notfound THEN • dbms_output.put_line('no customers updated'); • ELSIF sql%found THEN • total_rows := sql%rowcount; • dbms_output.put_line( total_rows || ' customers updated '); • END IF; • END; • / Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 91
  • 92. • Output • 6 rows are updated Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 92 ID Name Age Address Salary 1 Ramesh 10 Aurangabad 25000 2 Suresh 60 Kanpur 29000 3 Mahesh 30 Ghaziabad 33000 4 Ankita 20 Paris 35000 5 Nikita 40 Delhi 37000 6 Sunita 50 Nagpur 41000
  • 93. • Explicit Cursors : Explicit Cursors are Created by Users whenever the user requires them. • Explicit Cursors are used for Fetching data from Table in Row-By- Row Manner. • The Explicit cursors are defined by the programmers to gain more control over the context area. • These cursors should be defined in the declaration section of the PL/SQL block. It is created on a SELECT statement which returns more than one row. • Syntax for Explicit Cursor • CURSOR cursor_name IS select_statement;; Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 93
  • 94. • Steps: • You must follow these steps while working with an explicit cursor. • Declare the cursor to initialize in the memory. • Open the cursor to allocate memory. • Fetch the cursor to retrieve data. • Close the cursor to release allocated memory. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 94
  • 95. • Declaring the Cursor • Declaring the cursor defines the cursor with a name and the associated SELECT statement. • Syntax for explicit cursor decleration CURSOR name IS SELECT statement; • For example: • CURSOR c_customers IS SELECT id, name, address FROM customers; • Opening the Cursor • Opening the cursor allocates memory for the cursor and makes it ready for fetching the rows returned by the SQL statement into it. • Syntax for cursor open: • OPEN cursor_name; • For example, we will open above-defined cursor as follows: • OPEN c_customers; Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 95
  • 96. • Fetching the Cursor • Fetching the cursor involves accessing one row at a time. • Syntax for cursor fetch: • FETCH cursor_name INTO variable_list; • For example we will fetch rows from the above-opened cursor as follows: • FETCH c_customers INTO c_id, c_name, c_addr; • Closing the Cursor • Closing the cursor means releasing the allocated memory. • Syntax for cursor close: • Close cursor_name; • For example, we will close aboveopened cursor as follows: • CLOSE c_customers; Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 96
  • 97. • PL/SQL Cursors For Loop • PL/SQL cursor FOR loop has one great advantage of loop continued until row not found. In sometime you require to use explicit cursor with FOR loop instead of use OPEN, FETCH, and CLOSE statement. • FOR loop iterate repeatedly and fetches rows of values from database until row not found. • Explicit Cursor FOR LOOP Example • Emp_information table Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 97 EMP_NO EMP_NAME EMP_DEPT EMP_SALARY 1 Aishwarya Web developer 45K 2 Vaishnavi Program developer 38K 3 Shilpa Program developer 50K 4 Shital Web developer 35K
  • 98. • DECLARE • cursor c is select * from emp_information where emp_no <=2; • tmp emp_information%rowtype; • If you do not use the %ROWTYPE datatype, then you have to declare variables for each column separately. • BEGIN • OPEN c; • FOR tmp IN c LOOP • FETCH c into tmp; • dbms_output.put_line('EMP_No: '||tmp.emp_no); • dbms_output.put_line('EMP_Name: '||tmp.emp_name); • dbms_output.put_line('EMP_Dept: '||tmp.emp_dept); • dbms_output.put_line('EMP_Salary:'||tmp.emp_salary); • END Loop; • CLOSE c; • END; • / 98
  • 99. • EMP_No: 1 • EMP_Name: Aishwarya • EMP_Dept: Web Developer • EMP_Salary:45k • EMP_No: 2 • EMP_Name: Vaishnavi • EMP_Dept: Program Developer • EMP_Salary:38k Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 99
  • 100. • PL/SQL Parameterized Cursor • PL/SQL Parameterized cursor pass the parameters into a cursor and use them in to query. • PL/SQL Parameterized cursor define only datatype of parameter and not need to define it's length. • Default values is assigned to the Cursor parameters. • Parameterized cursors are also saying static cursors that can passed parameter value when cursor are opened. • Syntax CURSOR cursor_name (parameter_list) IS Select statement; To open a cursor with parameters, you use the following syntax: OPEN cursor_name (argument_list); 100
  • 101. • Following example introduce the parameterized cursor. following emp_information table Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 101 EMP_NO EMP_NAME EMP_DEPT EMP_SALARY 1 Aishwarya Web developer 45K 2 Vaishnavi Program developer 38K 3 Shilpa Program developer 50K 4 Shital Web developer 35K
  • 102. • Cursor display employee information from emp_information table whose emp_no four (4). • DECLARE • cursor c(no number) is select * from emp_information where emp_no = no; • tmp emp_information%rowtype; • BEGIN • OPEN c(4); • FOR tmp IN c(4) LOOP • dbms_output.put_line('EMP_No: '||tmp.emp_no); • dbms_output.put_line('EMP_Name: '||tmp.emp_name); • dbms_output.put_line('EMP_Dept: '||tmp.emp_dept); • dbms_output.put_line('EMP_Salary:'||tmp.emp_salary); • END Loop; • CLOSE c; • END;/ • EMP_No: 4 • EMP_Name: Shital • EMP_Dept: Web Developer • EMP_Salary: 35k Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 102
  • 103. • PL/SQL Procedures • The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one or more specific tasks. • The procedure contains a header and a body. • Header: The header contains the name of the 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. • PL/SQL procedures create using CREATE PROCEDURE statement. The major difference between PL/SQL function or procedure, function return always value where as procedure may or may not return value. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 103 CREATE [OR REPLACE] PROCEDURE procedure_name [(parameter_name [IN | OUT | IN OUT] type [, ...])] {IS | AS} BEGIN < procedure_body > END procedure_name;
  • 104. • When you create a function or procedure, you have to define IN/OUT/INOUT parameters. • 1. IN : • An IN parameter lets you pass a value to the subprogram. It is a read-only parameter. It cannot be assigned a value.It is the default mode of parameter passing. • 2. OUT : • An OUT parameter returns a value to the calling program. Inside the subprogram, an OUT parameter acts like a variable. You can change its value and reference the value after assigning it. • 3. IN OUT : • An IN OUT parameter passes an initial value to a subprogram and returns an updated value to the caller. It can be assigned a value and the value can be read. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 104
  • 105. • PL/SQL Procedure Example • In this example, we are going to insert record in user table. So you need to create user table first. • create table user(id number(10) primary key,name varchar2(100)); • Now write the procedure code to insert record in user table. • Procedure Code: • create or replace procedure "INSERTUSER" • (id IN NUMBER,name IN VARCHAR2) • is • begin • insert into user values(id,name); • end; / • Output: • Procedure created. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 105
  • 106. • PL/SQL program to call procedure • Let's see the code to call above created procedure. • BEGIN • insertuser(101,'Rahul'); • dbms_output.put_line('record inserted successfully'); • END; • / • Now, see the "USER" table, you will see one record is inserted. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 106 ID Name 101 Rahul
  • 107. • PL/SQL Drop Procedure • Syntax for drop procedure • DROP PROCEDURE procedure_name; • Example of drop procedure • DROP PROCEDURE pro1; Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 107
  • 108. • PL/SQL Function • PL/SQL functions block create using CREATE FUNCTION statement. • The major difference between PL/SQL function or procedure, function return always value where as procedure may or may not return value. • When you create a function or procedure, you have to define IN/OUT/INOUT parameters. • 1. IN :An IN parameter lets you pass a value to the subprogram. It is a read-only parameter. It cannot be assigned a value.It is the default mode of parameter passing. • 2. OUT : An OUT parameter returns a value to the calling program. Inside the subprogram, an OUT parameter acts like a variable. You can change its value and reference the value after assigning it. • 3. IN OUT : An IN OUT parameter passes an initial value to a subprogram and returns an updated value to the caller. It can be assigned a value and the value can be read. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 108
  • 109. • Syntax to create Function • CREATE [OR REPLACE] FUNCTION function_name [parameters] • [(parameter_name [IN | OUT | IN OUT] type [, ...])] • RETURN return_datatype • {IS | AS} • 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. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 109
  • 110. • PL/SQL Function Example • Let's see a simple example to create a function. • create or replace function adder(n1 in number, n2 in number) • return number • is • n3 number(8); • begin • n3 :=n1+n2; • return n3; • end; • / Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 110
  • 111. • Now write another program to call the function • DECLARE • n3 number(2); • BEGIN • n3 := adder(11,22); • dbms_output.put_line('Addition is: ' || n3); • END; • / Output: Addition is: 33 Statement processed. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 111
  • 112. • PL/SQL Drop Function • Functions Drop Syntax • DROP FUNCTION function_name; • DROP FUNCTION adder; Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 112
  • 113. • PL/SQL Trigger • Trigger is invoked by Oracle engine automatically whenever a specified event occurs. Trigger is stored into database and invoked repeatedly, when specific condition match. • 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). • A database definition (DDL) statement (CREATE, ALTER, or DROP). • A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN). Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 113
  • 114. • Syntax for creating trigger: Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 114 create trigger [trigger_name] [before | after] {insert | update | delete} on [table_name] [for each row] [trigger_body] create trigger [trigger_name]: Creates or replaces an existing trigger with the trigger_name. [before | after]: This specifies when the trigger will be executed. {insert | update | delete}: This specifies the DML operation. on [table_name]: This specifies the name of the table associated with the trigger. [for each row]: This specifies a row-level trigger, i.e., the trigger will be executed for each row being affected. [trigger_body]: This provides the operation to be performed as trigger is fired
  • 115. • PL/SQL Trigger Example • Let's take a simple example to demonstrate the trigger. In this example, we are using the following CUSTOMERS table: • Create trigger: • Let's take a program to create a row level trigger for the CUSTOMERS table that would fire for INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. • This trigger will display the salary difference between the old values and new values: Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 115 ID Name Age Address Salary 1 Ramesh 10 Aurangabad 20000 2 Suresh 60 Kanpur 25000 3 Mahesh 30 Ghaziabad 30000 4 Ankita 20 Paris 35000
  • 116. • CREATE OR REPLACE TRIGGER display_salary_changes • BEFORE DELETE OR INSERT OR UPDATE ON customers • FOR EACH ROW • WHEN (NEW.ID > 0) • DECLARE • sal_diff number; • BEGIN • sal_diff := :NEW.salary - :OLD.salary; • dbms_output.put_line('Old salary: ' || :OLD.salary); • dbms_output.put_line('New salary: ' || :NEW.salary); • dbms_output.put_line('Salary difference: ' || sal_diff); • END; / • After the execution of the above code at SQL Prompt, it produces the following result. • Trigger created. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 116
  • 117. • Check the salary difference by procedure: • Use the following code to get the old salary, new salary and salary difference after the trigger created. • DECLARE • total_rows number(2); • BEGIN • UPDATE customers SET salary = salary + 5000; • IF sql%notfound THEN • dbms_output.put_line('no customers updated'); • ELSIF sql%found THEN • total_rows := sql%rowcount; • dbms_output.put_line( total_rows || ' customers updated '); • END IF; • END; Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 117
  • 118. • Output: • Old salary: 20000 • New salary: 25000 • Salary difference: 5000 • Old salary: 25000 • New salary: 30000 • Salary difference: 5000 • Old salary: 30000 • New salary: 35000 • Salary difference: 5000 • Old salary: 35000 • New salary: 40000 • Salary difference: 5000 Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 118
  • 119. References • Book-Introduction to database management systems, ISRD Group 119
  • 120. Sanjivani K.B.P. Polytechnic, Kopargaon Department of Computer Technology Miss.I.B.Tirse 120