DBMS UNIT V
DBMS UNIT V
UNIT - V
PL/SQL: Introduction, Shortcoming in SQL, Structure of PL/SQL, PL/SQL Language Elements, Data
Types, Operators Precedence, Control Structure, Steps to Create a PL/SQL, Program, Iterative Control,
, Procedure, Function, , Database Triggers, Types of Triggers.
--------------------------------------------------------------------------------------------------------------------------
Syntax:
Declare
Variable declaration
Begin
Process statements
Or execution statement
[Exception
Exception statement]
End;
A PL/SQL block can be divided into four sections. They are
1. Declaration section
2. Begin section
3. Exception section
4. End section
1. Declaration Section:
Code blocks start with a declaration section
In this block memory variable and other oracle objects can be declared
PATAN ARIFOON.,MCA(M.Tech)
UGC NET & APSET QUALIFIED
2
2. Begin Section:
It consists of a set of SQL and PL/SQL statements
It describes process that has to be applied to table data.
Actual data manipulation, retrieval, looping and branching constructs arespecified in this
section.
3. Exception Section:
This section deals with handling of errors
That arise during execution of the data manipulation statements
The errors can arise due to syntax and logic.
4. End Section:
a. This makes the end of a PL/SQL block.
Example:
Declare
a number(4);
b number(4);
c number(4);
begin
b:=20;
c:=a+b;
dbms_output.put_line(c);
end;
1. dbms_ouput: it is a package.
2. That includes a number of procedures and functions that accumulate informationin a buffer so
that it can be retrieved later.
3. These functions can also be used to display message.
4. put_line: put a piece of information in the package buffer followed by an end-of-line marker.
5. dbms_ouput.put_line(‘Hello’);
PATAN ARIFOON.,MCA(M.Tech)
UGC NET & APSET QUALIFIED
3
1. Character Set
1. A PL/SQL program consists of text having specific set of characters.
2. Character set may include the following characters:
a. Alphabets, both in upper case [A–Z] and lower case [a–z]
b. Numeric digits [0–9]
c. Special characters ( ) + − * /< >= ! ∼ ˆ ; : . _ @ %
d. Blank spaces, tabs, and carriage returns.
2. Lexical Units
1. A line of PL/SQL program contains groups of characters known as lexical units,which can be
classified as follows:
A. Delimiters
B. Identifiers
C. Literals
D. Comments
A. Delimiters
a. A delimiter is a simple or compound symbol
b. That has a special meaning to PL/SQL.
c. Simple symbol consists of one character
d. Compound symbol consists of more than one character.
B. Identifiers
a. Identifiers are used in the PL/SQL programs
PATAN ARIFOON.,MCA(M.Tech)
UGC NET & APSET QUALIFIED
4
C. Literals
a. A literal is an explicitly defined character, string, numeric, or Booleanvalue,
D. Comments
1. Comments are used in the PL/SQL program
2. It used to improve the readability and understandability of a program.
3. A comment can appear anywhere in the program code.
4. The compiler ignores comments.
5. Generally, comments are used to describe the purpose and use of eachcode segment.
Ex: /* Hello World! This is an example of multiline comments in PL/SQL */
Q) Introduction to PL/SQL data types
Each value in PL/SQL such as a constant, variable and parameter has a data type that determines the
storage format, valid values, and allowed operations.
PL/SQL has two kinds of data types: scalar and composite. The scalar types are types that store single
values such as number, Boolean, character, and datetime whereas the composite types are types that
store multiple values, for example, record and collection.
This tutorial explains the scalar data types that store values with no internal components.
Number
Boolean
Character
Datetime
A scalar data type may have subtypes. A subtype is a data type that is a subset of another data type,
which is its base type. A subtype further defines a base type by restricting the value or size of the base
data type.
PATAN ARIFOON.,MCA(M.Tech)
UGC NET & APSET QUALIFIED
5
The numeric data types represent real numbers, integers, and floating-point numbers. They are stored
as NUMBER, IEEE floating-point storage types (BINARY_FLOAT and BINARY_DOUBLE),
and PLS_INTEGER.
The BOOLEAN datatype has three data values: TRUE, FALSE, and NULL. Boolean values are
typically used in control flow structure such as IF-THEN, CASE, and loop statements like LOOP, FOR
LOOP, and WHILE LOOP.
SQL does not have the BOOLEAN data type, therefore, you cannot:
The character data types represent alphanumeric text. PL/SQL uses the SQL character data types such
as CHAR, VARCHAR2, LONG, RAW, LONG RAW, ROWID, and UROWID.
The date time data types represent dates, timestamp with or without time zone and intervals.
PL/SQL datetime data types are DATE, TIMESTAMP, TIMESTAMP WITH TIME
ZONE, TIMESTAMP WITH LOCAL TIME ZONE, INTERVAL YEAR TO MONTH,
and INTERVAL DAY TO SECOND.
Operator Description
** Exponentiation
*, / Multiplication, division
AND Conjunction
OR Inclusion
Conditional control
1. Conditional control, which run different statements for different data values.
2. It check the condition for single time only even it is true or false
PATAN ARIFOON.,MCA(M.Tech)
UGC NET & APSET QUALIFIED
7
Syntax:
if(condition) then
Statement 1;
…………… Statement n;
End if;
Example:
DECLARE
a number:=&a;
BEGIN
if(a<10)then
dbms_output.put_line(‘welcome to pl/sql’);
end if;
END;
Syntax:
if(condition) then
Statement 1;
else
end if;
statement 2;
PATAN ARIFOON.,MCA(M.Tech)
UGC NET & APSET QUALIFIED
8
Example:
declare
a integer;
b integer; begin
a:=&a; /* it take run time values*/
b:=&b; /* it take run time values*/
if(a>b) then
dbms_output.put_line(‘A is big’);
else
dbms_output.put_line(‘b is big’);
end if;
end;
Syntax:
if(condition) then
Statement 1;
elsif(condition) then
statement 2;
else
statement 3;
end if;
Example:
declare
a integer; b integer;
c integer;
begin
a:=&a;
b:=&b;
c:=&c;
PATAN ARIFOON.,MCA(M.Tech)
UGC NET & APSET QUALIFIED
9
Nested if statement
Inner if is called nested if. if condition is false it execute stamen 3. Other wise it is true its check for
another condition if it is true it execute statement 1 other wise execute statement 2.
Syntax:
if(condition) then
if(condition) then
statement 1;
else
statement 2;
end if;else
statement 3;
end if;
Case:
Syntax
case variable_name
When value1 then stmt; When value2 then stmt;
……………Else stmt;
End case;
1. The case statement runs the first statements for which value equals variablename remaining
conditions are not evaluated.
2. If no value equals to variable name, the case statements runs else statements.
PATAN ARIFOON.,MCA(M.Tech)
UGC NET & APSET QUALIFIED
10
Ex:
Declare
Grade char:=’&grade’;
Begin
case grade
when ‘A’ then
dbms_output.put_line(‘Excellent’);
when ‘B’ then
dbms_output.put_line(‘Very good’);
when ‘C’ then
dbms_output.put_line(‘Good’);
when ‘D’ then
dbms_output.put_line(‘Fair’);
when ‘F’ then
dbms_output.put_line(‘poor’);
else
dbms_output.put_line(‘no such grade’);
end case;
end;
The PL/SQL loops are used to repeat the execution of one or more statements for specified number of
times. These are also known as iterative control statements.
LOOP
Sequence of statements;
END LOOP;
PATAN ARIFOON.,MCA(M.Tech)
UGC NET & APSET QUALIFIED
11
PL/SQL exit loop is used when a set of statements is to be executed at least once before the termination
of the loop. There must be an EXIT condition specified in the loop, otherwise the loop will get into an
infinite number of iterations. After the occurrence of EXIT condition, the process exits the loop.
LOOP
Sequence of statements;
END LOOP;
LOOP
statements;
EXIT;
{or EXIT WHEN condition;} END LOOP;
PATAN ARIFOON.,MCA(M.Tech)
UGC NET & APSET QUALIFIED
12
Example :
DECLARE
i NUMBER := 1;
BEGIN
LOOP
EXIT WHEN i>10;
DBMS_OUTPUT.PUT_LINE(i);
i := i+1;
END LOOP;
END;
PL/SQL while loop is used when a set of statements has to be executed as long as a condition is true, the
While loop is used. The condition is decided at the beginning of each iteration and continues until the
condition becomes false.
WHILE <condition>
LOOP statements;
END LOOP;
DECLARE
i INTEGER := 1;
BEGIN
PATAN ARIFOON.,MCA(M.Tech)
UGC NET & APSET QUALIFIED
13
PL/SQL for loop is used when when you want to execute a set of statements for a predetermined number
of times. The loop is iterated between the start and end integer values. The counter is always incremented
by 1 and once the counter reaches the value of end integer, the loop ends.
o You don't need to declare the counter variable explicitly because it is declared implicitly in the
declaration section.
o The counter variable is incremented by 1 and does not need to be incremented explicitly.
o You can use EXIT WHEN statements and EXIT statements in FOR Loops but it is not done often.
Q) PL/SQL Procedure
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one or more
specific tasks. It is just like procedures in other programming languages.
o Header: The header contains the name of the procedure and the parameters or variables passed to
the procedure.
o Body: The body contains a declaration section, execution section and exception section similar to
a general PL/SQL block.
Creating a Procedure
A procedure is created with the CREATE OR REPLACE PROCEDURE statement. The simplified
syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −
Where,
PATAN ARIFOON.,MCA(M.Tech)
UGC NET & APSET QUALIFIED
15
Example :
The following example creates a simple procedure that displays the string 'Hello World!' on the screen
when executed.
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;
/
When the above code is executed using the SQL prompt, it will produce the following result −
Procedure created.
Executing a Standalone Procedure
The above procedure named 'greetings' can be called with the EXECUTE keyword as −
EXECUTE greetings;
Hello World
PL/SQL procedure successfully completed.
BEGIN
greetings;
END;
/
The above call will display − Hello World . PL/SQL procedure successfully completed.
A standalone procedure is deleted with the DROP PROCEDURE statement. Syntax for deleting a
procedure is −
PATAN ARIFOON.,MCA(M.Tech)
UGC NET & APSET QUALIFIED
16
You can drop the greetings procedure by using the following statement −
Q) PL/SQL Function
The PL/SQL Function is very similar to PL/SQL Procedure. The main difference between procedure and
a function is, a function must always return a value, and on the other hand a procedure may or may not
return a value. Except this, all the other things of PL/SQL procedure are true for PL/SQL function too.
Here:
EXAMPLE :
create or replace function adder(n1 in number, n2 in number)
return number
is
n3 number(8);
begin
n3 :=n1+n2;
return n3;
end;
/
Calling PL/SQL Function:While creating a function, you have to give a definition of what the function
has to do. To use a function, you will have to call that function to perform the defined task. Once the
function is called, the program control is transferred to the called function.
After the successful completion of the defined task, the call function returns program control back to the
main program.
To call a function you have to pass the required parameters along with function name and if function
returns a value then you can store returned value
Example
Create Function:
PATAN ARIFOON.,MCA(M.Tech)
UGC NET & APSET QUALIFIED
18
RETURN total;
END;
/
After the execution of above code, you will get the following result.
Function created.
Calling function code:
DECLARE
c number(2);
BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;
/
PL/SQL Drop Function
If you want to remove your created function from the database, you should use the following syntax.
Triggers are stored programs, which are automatically executed or fired when some events occur. Triggers
are, in fact, written to be executed in response to any of the following events −
Triggers can be defined on the table, view, schema, or database with which the event is associated.
Benefits of Triggers
Auditing
Synchronous replication of tables
Imposing security authorizations
Preventing invalid transactions
Creating a trigger:
Here,
o CREATE [OR REPLACE] TRIGGER trigger_name: It creates or replaces an existing trigger with
the trigger_name.
o {BEFORE | AFTER | INSTEAD OF} : This specifies when the trigger would be executed. The
INSTEAD OF clause is used for creating trigger on a view.
o {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.
o [OF col_name]: This specifies the column name that would be updated.
o [ON table_name]: This specifies the name of the table associated with the trigger.
PATAN ARIFOON.,MCA(M.Tech)
UGC NET & APSET QUALIFIED
20
o [REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old values for various
DML statements, like INSERT, UPDATE, and DELETE.
o [FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger would be executed for each
row being affected. Otherwise the trigger will execute just once when the SQL statement is
executed, which is called a table level trigger.
o WHEN (condition): This provides a condition for rows for which the trigger would fire. This
clause is valid only for row level triggers.
Type of Triggers
1. BEFORE Trigger: BEFORE trigger execute before the triggering DML statement (INSERT,
UPDATE, DELETE) execute. Triggering SQL statement is may or may not execute, depending
on the BEFORE trigger conditions block.
2. AFTER Trigger: AFTER trigger execute after the triggering DML statement (INSERT,
UPDATE, DELETE) executed. Triggering SQL statement is execute as soon as followed by the
code of trigger before performing Database operation.
3. ROW Trigger: ROW trigger fire for each and every record which are performing INSERT,
UPDATE, DELETE from the database table. If row deleting is define as trigger event, when
trigger file, deletes the five rows each times from the table.
4. Statement Trigger: Statement trigger fire only once for each statement. If row deleting is define
as trigger event, when trigger file, deletes the five rows at once from the table.
5. Combination Trigger: Combination trigger are combination of two trigger type,
1. Before Statement Trigger: Trigger fire only once for each statement before the
triggering DML statement.
2. Before Row Trigger : Trigger fire for each and every record before the triggering DML
statement.
3. After Statement Trigger: Trigger fire only once for each statement after the triggering
DML statement executing.
4. After Row Trigger: Trigger fire for each and every record after the triggering DML
statement executing.
PATAN ARIFOON.,MCA(M.Tech)
UGC NET & APSET QUALIFIED