SlideShare a Scribd company logo
SQL Programming
4.1 Introduction to PL/SQL :
PL/SQL is a block structured language that enables developers to
combine the power of SQL with procedural statements. All the
statements of a block are passed to oracle engine all at once which
increases processing speed and decreases the traffic.
PL/SQL is a highly structured and readable language. Its constructs
express the intent of the code clearly. Also, PL/SQL is a
straightforward language to learn.
PL/SQL is a standard and portable language for Oracle Database
development
Mrs. Ujjwala S Patil (SITCOE)
Mrs. Ujjwala S Patil (SITCOE)
Advantages of PL/SQL:
Reduces network traffic
Procedural language
Error handling
Declare variable
Intermediate Calculation
Portable application
Mrs. Ujjwala S Patil (SITCOE)
Features of PL/SQL:
• PL/SQL is basically a procedural language, which provides the
functionality of decision making, iteration and many more
features of procedural programming languages.
• PL/SQL can execute a number of queries in one block using
single command.
• One can create a PL/SQL unit such as procedures, functions,
packages, triggers, and types, which are stored in the database for
reuse by applications.
• PL/SQL provides a feature to handle the exception which occurs
in PL/SQL block known as exception handling block.
• Applications written in PL/SQL are portable to computer
hardware or operating system where Oracle is operational.
• PL/SQL Offers extensive error checking.
Mrs. Ujjwala S Patil (SITCOE)
Differences between SQL and PL/SQL:
SQL PL/SQL
SQL is a single query that is used to
perform DML and DDL operations.
PL/SQL is a block of codes that used to
write the entire program blocks/
procedure/ function, etc.
It is declarative, that defines what
needs to be done, rather than how
things need to be done.
PL/SQL is procedural that defines how
the things needs to be done.
Execute as a single statement. Execute as a whole block.
Mainly used to manipulate data. Mainly used to create an application.
Cannot contain PL/SQL code in it. It is an extension of SQL, so it can
contain SQL inside it.
Mrs. Ujjwala S Patil (SITCOE)
PL/SQL Block Structure:
OR
• Declare section starts with DECLARE keyword in which
variables, constants, records as cursors can be declared which
stores data temporarily. It basically consists definition of PL/SQL
identifiers. This part of the code is optional.
Mrs. Ujjwala S Patil (SITCOE)
PL/SQL Block structure cont…
• Execution section starts with BEGIN and ends
with END keyword. This is a mandatory section and here the
program logic is written to perform any task like loops and
conditional statements.
It supports all DML commands, DDL commands and SQL*PLUS
built-in functions as well.
• Exception section starts with EXCEPTION keyword. This
section is optional which contains statements that are executed
when a run-time error occurs. Any exceptions can be handled in
this section
Mrs. Ujjwala S Patil (SITCOE)
PL/SQL Execution Environment :
When a user submit an SQL statement to the database instance, it
will accept the SQL statement for execution in following phases:
Parse Phase
Execute Phase
Fetch Phase
Mrs. Ujjwala S Patil (SITCOE)
PL/SQL Execution Environment cont..
The PL/SQL engine resides in the Oracle engine. The Oracle
engine can process not only single SQL statement but also block of
many statements. The call to Oracle engine needs to be made only
once to execute any number of SQL statements if these SQL
statements are bundled inside a PL/SQL block.
Mrs. Ujjwala S Patil (SITCOE)
PL/SQL Data type:
There are various types of data types are there
Character Data types
Numeric Data types
Date/Time Data types
Mrs. Ujjwala S Patil (SITCOE)
PL/SQL Variable:
These are placeholders that store the values that can change
through the PL/SQL Block.
General Syntax to declare a variable is
variable_name datatype [NOT NULL := value ];
Mrs. Ujjwala S Patil (SITCOE)
4.2 Control Structure: Conditional Control, Iterative
Control, Sequential control:
Mrs. Ujjwala S Patil (SITCOE)
1. Selection control:
The selection structure tests a condition, then executes one
sequence of statements instead of another, depending on whether
the condition is true or false. A condition is any variable or
expression that returns a BOOLEAN value (TRUE or FALSE).
Conditional selection statements, which run different statements
for different data values.
The conditional selection statements are IF and CASE.
Mrs. Ujjwala S Patil (SITCOE)
Iteration Control:
The iteration structure executes a sequence of statements repeatedly
as long as a condition holds true.
Loop statements, which run the same statements with a series of
different data values.
The loop statements are the basic LOOP, FOR LOOP,
and WHILE LOOP.
The EXIT statement transfers control to the end of a loop.
The CONTINUE statement exits the current iteration of a loop and
transfers control to the next iteration.
Both EXIT and CONTINUE have an optional WHEN clause,
where you can specify a condition.
Mrs. Ujjwala S Patil (SITCOE)
Sequential Control:
The sequence-structure simply executes a sequence of statements in
the order in which they occur.
Sequential control statements, which are not crucial to PL/SQL
programming.
The sequential control statements are GOTO, which goes to a
specified statement, and NULL, which does nothing.
Mrs. Ujjwala S Patil (SITCOE)
Conditional Selection Statements:
The conditional selection statements, IF and CASE, run different
statements for different data values.
The IF statement either runs or skips a sequence of one or more
statements, depending on a condition. The IF statement has these
forms:
IF THEN
IF THEN ELSE
IF THEN ELSIF
Mrs. Ujjwala S Patil (SITCOE)
IF THEN Statement:
The IF THEN statement either runs or skips a sequence of one or
more statements, depending on a condition.
The IF THEN statement has this structure:
IF condition THEN
Statements
END IF;
If the condition is true, the statements run; otherwise,
the IF statement does nothing.
Mrs. Ujjwala S Patil (SITCOE)
IF THEN ELSE Statement :
The IF THEN ELSE statement has this structure:
IF condition THEN
Statements
ELSE
else_statements
END IF;
If the value of condition is true, the statements run; otherwise,
the else_statements run.
Mrs. Ujjwala S Patil (SITCOE)
Example for IF THEN ELSE:
Write a PL/SQL program to check given number is odd or
Even.
Declare
num int:=: num;
Begin
if(MOD(num,2))=0 then
Dbms_output.put_line(‘Given num is Even’);
Else
Dbms_output.put_line(‘Given num is Odd’);
END IF;
End;
Mrs. Ujjwala S Patil (SITCOE)
IF THEN ELSIF Statement
The IF THEN ELSIF statement has this structure:
IF condition_1 THEN
statements_1
ELSIF condition_2 THEN
statements_2
[ ELSIF condition_3 THEN statements_3]...
[ ELSE else_statements]
END IF;
The IF THEN ELSIF statement runs the first statements for
which condition is true. Remaining conditions are not evaluated. If
no condition is true, the else_statements run, if they exist;
otherwise, the IF THEN ELSIF statement does nothing.
Mrs. Ujjwala S Patil (SITCOE)
Example of IF THEN ELSIF Statement:
PL/SQL code to accept 3 numbers and display the largest number.
Declare
num1 int:=:num1;
num2 int:=:num2;
num3 int:=:num3;
Begin
IF (num1>num2 AND num1>num3)
THEN
Dbms_output.put_line('num1 is greater');
ELSIF (num2>num1 AND num2>num3)
THEN
Dbms_output.put_line('num2 is greater');
ELSIF (num3>num1 AND num3>num2)
THEN
Dbms_output.put_line('num3 is greater');
Else
Dbms_output.put_line('All numbers are equal');
END IF;
END;
Mrs. Ujjwala S Patil (SITCOE)
Simple CASE Statement :
The simple CASE statement has this structure:
CASE selector
WHEN selector_value_1 THEN statements_1
WHEN selector_value_2 THEN statements_2...
WHEN selector_value_n THEN statements_n
[ ELSE else_statements ]
END CASE;
The selector is an expression (typically a single variable).
Each selector_value can be either a literal or an expression.
The simple CASE statement runs the first statements for
which selector_value equals selector. Remaining conditions are
not evaluated. If no selector_value equals selector,
the CASE statement runs else_statements if they exist and raises
the predefined exception CASE_NOT_FOUND otherwise.
Mrs. Ujjwala S Patil (SITCOE)
Example For CASE Statement:
Declare a character variable assign any alphabet to it and display
whether the enter alphabet is vowel or consonant using CASE statement.
Declare
ch char:=:ch;
Begin
CASE
WHEN (ch='A' or ch='a' or ch='e' or ch='e' or ch='I' or ch='i' or ch='O' or
ch='o' or ch='U' or ch='u')
THEN
Dbms_output.put_line('Vowel');
ELSE
Dbms_output.put_line('Consonant');
END CASE;
End
Mrs. Ujjwala S Patil (SITCOE)
Iterative control:
Iterative control is used for executing the tasks that are
having repetitions.
Iterative controls are:
Loop Statement
While loop
For loop
Mrs. Ujjwala S Patil (SITCOE)
Loop Statement:
Loop statements let you execute a sequence of statements multiple
times.
The simple form of loop statement is the basic(or infinite) loop,
which enclose a sequence of statement between the keyword LOOP
and END LOOP.
Syntax:
LOOP <Commands>
IF <Condition> THEN
Statement;
EXIT;
End IF;
END LOOP;
Mrs. Ujjwala S Patil (SITCOE)
Example for Simple LOOP:
Declare
i number :=0;
Begin
LOOP
i := i+1;
If (i<=10) THEN
dbms_output.put_line(i);
EXIT;
END IF;
END LOOP;
END;
Mrs. Ujjwala S Patil (SITCOE)
While Loop:
The while loop statement associates a condition with a sequence of
statement.
Syntax:
WHILE <Condition> LOOP
<Commands> /* List of Statements*/
END LOOP
Mrs. Ujjwala S Patil (SITCOE)
Example for While LOOP:
Declare
i number :=0;
Begin
While i<=10 LOOP
i:=i+1;
Dbms_output.put_line(i);
END LOOP;
END;
Mrs. Ujjwala S Patil (SITCOE)
For Loop:
Where as the number of iterations through a while loop is unknown
until the loop completes, the number of iterations through a for
loop is known before the loop is entered.
For loop iterates over a specific range of integers. The range is a
part of an iteration scheme which is enclosed by the keyword FOR
and LOOP.
A double dots (..) serves as the range operator.
Syntax:
For <variable> IN [reverse] <min value> .. < max value> LOOP
List of statements;
END LOOP;
Mrs. Ujjwala S Patil (SITCOE)
For Loop Example:
Print I to 10 numbers using for loop.
declare
i int;
Begin
For i in 1..10 loop
Dbms_output.put_line(i);
End loop;
End;
Mrs. Ujjwala S Patil (SITCOE)
For Loop Example:
Print 10 to 1 numbers using for loop.
declare
i int;
Begin
For i in REVERSE 1..10 loop
dbms_output.put_line(i);
End loop;
End;
:
Mrs. Ujjwala S Patil (SITCOE)
Sequential control:( GOTO and NULL)
Unlike the IF and LOOP statements, the sequential control
statements GOTO and NULL are not crucial to PL/SQL
programming.
The GOTO is used for transferring the control. Overuse of GOTO
statements can result in complex, unstructured code that is hard to
understand and maintain.
The NULL statement does nothing other than pass control to the
next statement. The NULL statement can improve readability by
making the meaning and action of conditional statement clear.
Mrs. Ujjwala S Patil (SITCOE)
GOTO Statement:
The GOTO statement transfers control to a label unconditionally.
The label must be unique in its scope and must precede an
executable statement or a PL/SQL block. When run,
the GOTO statement transfers control to the labeled statement or
block.
Syntax:
GOTO label_name;
where label_name is the name of a label identifying the target
statement. This GOTO label is defined in the program as follows:
<<label_name>>
Mrs. Ujjwala S Patil (SITCOE)
Example for GOTO Statement:
BEGIN
GOTO second_output;
DBMS_OUTPUT.PUT_LINE('This line will never execute.');
<<second_output>>
DBMS_OUTPUT.PUT_LINE('We are here!');
END;
Mrs. Ujjwala S Patil (SITCOE)
Restrictions of GOTO Statement:
There are several restrictions on the GOTO statement:
At least one executable statement must follow a label.
The target label must be in the same scope as the GOTO statement.
The target label must be in the same part of the PL/SQL block as
the GOTO.
The GOTO statement can come in handy. There are cases where a
GOTO statement can simplify the logic in your program. On the
other hand, because PL/SQL provides so many different control
constructs and modularization techniques, you can almost always
find a better way to do something than with a GOTO.
Mrs. Ujjwala S Patil (SITCOE)
NULL Statement:
The NULL statement does nothing other than pass control
to the next statement. The NULL statement can improve
readability by making the meaning and action of
conditional statement clear.
Some uses for the NULL statement are:
• To provide a target for a GOTO statement.
• To improve readability by making the meaning and
action of conditional statements clear.
• To create placeholders and stub subprograms.
• To show that you are aware of a possibility, but that no
action is necessary.
Mrs. Ujjwala S Patil (SITCOE)
The NULL statement has the following format:
NULL;
Example :
Compute the bonus for employee whose rating is greater
than 90%
If rating is >90 then
Compute_bonus(emp_id);
Else
NULL;
End IF;
Mrs. Ujjwala S Patil (SITCOE)
4.3 Exception Handling: Predefined and user defined
Exception:
An exception occurs when the PL/SQL engine encounters an
instruction which it cannot execute due to an error that occurs at
run-time. These errors will not be captured at the time of
compilation and hence these needed to handle only at the run-time.
Exceptions will stop the program from executing further, so to
avoid such condition, they need to be captured and handled
separately. This process is called as Exception-Handling, in which
the programmer handles the exception that can occur at the run
time.
Mrs. Ujjwala S Patil (SITCOE)
Exception-Handling Syntax:
Exceptions are handled at the block, level, i.e., once if any
exception occurs in any block then the control will come out of
execution part of that block. The exception will then be handled at
the exception handling part of that block. After handling the
exception, it is not possible to resend control back to the execution
section of that block.
The below syntax explains how to catch and handle the exception.
Mrs. Ujjwala S Patil (SITCOE)
Types of Exception
There are two types of Exceptions in Pl/SQL.
Predefined Exceptions
User-defined Exception
Predefined Exceptions
Oracle has predefined some common exception. These exceptions
have a unique exception name and error number. These exceptions
are already defined in the 'STANDARD' package in Oracle.
User-defined Exception
In Oracle, other than the above-predefined exceptions, the
programmer can create their own exception and handle them. They
can be created at a subprogram level in the declaration part.
Mrs. Ujjwala S Patil (SITCOE)
Predefined Exceptions
Oracle has predefined some common exception. These exceptions
have a unique exception name and error number. These exceptions
are already defined in the 'STANDARD' package in Oracle. In
code, we can directly use these predefined exception name to
handle them.
Exception Error
Code
Exception Reason
ACCESS_INTO
_NULL
ORA-
06530
Assign a value to the attributes of uninitialized
objects
CASE_NOT_F
OUND
ORA-
06592
None of the 'WHEN' clause in CASE statement
satisfied and no 'ELSE' clause is specified
COLLECTION_
IS_NULL
ORA-
06531
Using collection methods (except EXISTS) or
accessing collection attributes on a uninitialized
collections
Mrs. Ujjwala S Patil (SITCOE)
Exception Error
Code
Exception Reason
CURSOR_ALREA
DY_OPEN
ORA-06511 Trying to open a cursor which is already opened
INVALID_CURSO
R
ORA-01001 Illegal cursor operations like closing an unopened
cursor
INVALID_NUMB
ER
ORA-01722 Conversion of character to a number failed due to
invalid number character
TOO_MANY_RO
WS
ORA-01422 When a 'SELECT' statement with INTO clause
returns more than one row
VALUE_ERROR ORA-06502 Arithmetic or size constraint error (eg: assigning
a value to a variable that is larger than the
variable size)
ZERO_DIVIDE ORA-01476 Dividing a number by '0'
Mrs. Ujjwala S Patil (SITCOE)
Examples for Predefined Exception:
NO_DATA_FOUND
declare
emp_no EMP.EMPNO%type;
begin
select SAL into emp_no from EMP where EMPNO=736;
exception
when NO_DATA_FOUND then
dbms_output.put_line('Employee not available');
end;
Mrs. Ujjwala S Patil (SITCOE)
Example for Predefined Exception:
ZERO_DIVIDE
declare
a number:=:a;
b number:=:b;
c number;
begin
c:=a/b;
dbms_output.put_line('Result' || c);
exception
when ZERO_DIVIDE then
dbms_output.put_line('Number can not divide by zero');
end;
Mrs. Ujjwala S Patil (SITCOE)
User Defined Exceptions:
In Oracle, other than the above-predefined exceptions, the programmer
can create their own exception and handle them. They can be created at
a subprogram level in the declaration part. These exceptions are visible
only in that subprogram. The exception that is defined in the package
specification is public exception, and it is visible wherever the package
is accessible.
DECLARE<exception_name>
EXCEPTION;
BEGIN
<Execution block>
EXCEPTION
WHEN <exception_name> THEN
<Handler>
END;
Mrs. Ujjwala S Patil (SITCOE)
Example for User defined Exception:
declare
emp_sal EMP.SAL%type;
less_sal exception;
begin
select SAL into emp_sal from EMP where EMPNO=7369;
if emp_sal<3000
then raise less_sal;
else
dbms_output.put_line('salary greater than 3000');
end if;
exception
when less_sal then
dbms_output.put_line('sal less than 3000');
end;
Mrs. Ujjwala S Patil (SITCOE)
4.4. Cursors:
A cursor is a temporary work area created in the system memory
when a SQL statement is executed. A cursor contains information
on a select statement and the rows of data accessed by it.
This temporary work area is used to store the data retrieved from
the database, and manipulate this data. A cursor can hold more than
one row, but can process only one row at a time. The set of rows
the cursor holds is called the active set.
There are 2 types of Cursors:
Implicit Cursors
Explicit Cursors.
Mrs. Ujjwala S Patil (SITCOE)
Implicit Cursors:
Implicit Cursors are also known as Default Cursors of SQL
SERVER. These are created by default when DML statements like,
INSERT, UPDATE, and DELETE statements are executed. They
are also created when a SELECT statement that returns just one
row is executed.
Explicit cursor:
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.
Mrs. Ujjwala S Patil (SITCOE)
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, like Insert, Update, delete. Implicit
cursors are used by oracle engine even if SELECT statement
returns single row.
For example, When you execute INSERT, UPDATE, or DELETE
statements the cursor attributes tell us whether any rows are
affected and how many have been affected.
When a SELECT... INTO statement is executed in a PL/SQL
Block, implicit cursor attributes can be used to find out whether
any row has been returned by the SELECT statement. PL/SQL
returns an error when no data is selected.
Mrs. Ujjwala S Patil (SITCOE)
Attributes of Implicit Cursor:
1. %FOUND
2. %NOTFOUND
3. %ISOPEN
4. %ROWCOUNT
Mrs. Ujjwala S Patil (SITCOE)
Example for Implici Cursors:
DECLARE var_rows number(5);
BEGIN
UPDATE employee SET salary = salary + 1000;
IF SQL%NOTFOUND THEN
dbms_output.put_line('None of the salaries where updated');
ELSIF SQL%FOUND THEN
var_rows := SQL%ROWCOUNT;
dbms_output.put_line('Salaries for ' || var_rows || 'employees are
updated');
END IF;
END;
Mrs. Ujjwala S Patil (SITCOE)
Explicit Cursors:
An explicit cursor is defined in the declaration section of the PL/SQL
Block. It is created on a SELECT Statement which returns more than
one row. We can provide a suitable name for the cursor.
General Syntax for Explicit cursor :
DECLARE
variables;
records;
create a cursor;
BEGIN
OPEN cursor;
FETCH cursor;
process the records;
CLOSE cursor;
END;
Mrs. Ujjwala S Patil (SITCOE)
How to use Explicit Cursor?
There are four steps in using an Explicit Cursor.
DECLARE the cursor in the declaration section.
OPEN the cursor in the Execution Section.
FETCH the data from cursor into PL/SQL variables or records in
the Execution Section.
CLOSE the cursor in the Execution Section before you end the
PL/SQL Block.
Mrs. Ujjwala S Patil (SITCOE)
1. Declaring Cursor:
Declare the cursor in declaration section:
Syntax:
Declare cursor cursor_name is Select statement;
cursor_name – A suitable name for the cursor.
select_statement – A select query which returns multiple
rows.
Example:
DECLARE
CURSOR emp_cur IS SELECT * FROM emp_tbl WHERE salary
> 5000;
Mrs. Ujjwala S Patil (SITCOE)
2. OPEN the cursor in the Execution Section:
Syntax
OPEN Cursor_Name;
Example:
OPEN emp_cur;
Mrs. Ujjwala S Patil (SITCOE)
3. Fetch the records in the cursor one at a time:
Syntax:
FETCH cursor_name INTO record_name;
OR
FETCH cursor_name INTO variable_list;
Example:
Fetch emp_cur into sal;
Mrs. Ujjwala S Patil (SITCOE)
4. Close the Cursors:
Syntax:
CLOSE cursor_name;
Example:
Close emp_cur;
When a cursor is opened, the first row becomes the current row.
When the data is fetched it is copied to the record or variables and
the logical pointer moves to the next row and it becomes the
current row. On every fetch statement, the pointer moves to the
next row. If you want to fetch after the last row, the program will
throw an error. When there is more than one row in a cursor we can
use loops along with explicit cursor attributes to fetch all the
records.
Mrs. Ujjwala S Patil (SITCOE)
Example for Explicit Cursors:
DECLARE
emp_rec emp_tbl%rowtype;
CURSOR emp_cur IS
SELECT * FROM emp_tbl WHERE salary > 10000;
BEGIN
OPEN emp_cur;
FETCH emp_cur INTO emp_rec;
dbms_output.put_line (emp_rec.first_name || ' ' ||
emp_rec.last_name);
CLOSE emp_cur;
END;
Mrs. Ujjwala S Patil (SITCOE)
Explicit Cursor Attributes:
We use these attributes to avoid errors while accessing cursors
through OPEN, FETCH and CLOSE Statements
Attributes Return values Example
%FOUND TRUE, if fetch statement returns at least one row. Cursor_name%FOUND
FALSE, if fetch statement doesn’t return a row.
%NOTFOUNDTRUE, , if fetch statement doesn’t return a row. Cursor_name
%NOTFOUND
FALSE, if fetch statement returns at least one row.
%ROWCOUN
T
The number of rows fetched by the fetch statement Cursor_name
%ROWCOUNT
If no row is returned, the PL/SQL statement returns an
error.
%ISOPEN TRUE, if the cursor is already open in the program Cursor_name%ISNAME
FALSE, if the cursor is not opened in the program.
Mrs. Ujjwala S Patil (SITCOE)
Cursor with a FOR Loop:
When using FOR LOOP you need not declare a record or
variables to store the cursor values, need not open, fetch
and close the cursor. These functions are accomplished by
the FOR LOOP automatically.
General Syntax for using FOR LOOP:
FOR record_name IN cusror_name LOOP
process the row...
END LOOP;
Mrs. Ujjwala S Patil (SITCOE)
Example for Cursor wit FOR LOOP:
DECLARE
CURSOR emp_cur IS
SELECT first_name, last_name, salary FROM emp_tbl;
emp_rec emp_cur%rowtype;
BEGIN
FOR emp_cur in emp_rec LOOP
dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name
|| ' ' ||emp_cur.salary);
END LOOP;
END;
Mrs. Ujjwala S Patil (SITCOE)
Parameterized Cursor:
Mrs. Ujjwala S Patil (SITCOE)
Procedures:
A procedure can be defined as a subprogram that perform a specific
task or actions.
A stored procedure or in simple a procedure is a named PL/SQL
block which performs one or more specific task. This is similar to a
procedure in other programming languages.
A procedure has a header and a body. The header consists of the
name of the procedure and the parameters or variables passed to the
procedure. The body consists or declaration section, execution
section and exception section similar to a general PL/SQL Block.
Mrs. Ujjwala S Patil (SITCOE)
General Syntax to create a procedure is:
CREATE [OR REPLACE] PROCEDURE proc_name [list of
parameters] IS
Declaration section
BEGIN
Execution section
EXCEPTION
Exception section
END;
Mrs. Ujjwala S Patil (SITCOE)
Example for Procedure:
CREATE OR REPLACE PROCEDURE checksal(eno number)
IS salcom number;
BEGIN
Select salary+comm into salcom from employee where empno=eno;
If (salcom>30000) then
Dbms_output.put_line(‘salary and commission is greater than 30000’);
Else
Dbms_output.put_line(‘salary and commission is less than 30000’);
End if;
Exception
When NO_DATA_FOUND then
Dbms_output.put_line(‘No data Found’);
END;
Mrs. Ujjwala S Patil (SITCOE)
How to execute a Stored Procedure?
There are two ways to execute a procedure.
1) From the SQL prompt.
EXECUTE [or EXEC] procedure_name;
2) Within another procedure – simply use the procedure name.
procedure_name;
Example:
Declare
Begin
Checksal(0968);
End;
Mrs. Ujjwala S Patil (SITCOE)
Deleting Procedure:
Procedure can be dropped using drop procedure command.
Syntax:
Drop procedure procedure_name;
Example:
Drop procedure checksal;
Output:
Procedure dropped
1.01 seconds
Mrs. Ujjwala S Patil (SITCOE)
Advantages of Procedure:
Better Performance
Higher Productivity
Ease of Use
Scalability
Maintainability
Security
Mrs. Ujjwala S Patil (SITCOE)
4.6 Functions :
Function is a subprogram that is used for the purpose of code
reusability. A function is a named PL/SQL Block which is similar
to a procedure.
The procedure and functions are almost same from the point of
view of purpose. The major difference between a procedure and a
function is, a function must always return a value, but a procedure
may or may not return a value.
Mrs. Ujjwala S Patil (SITCOE)
General Syntax to create a function is
CREATE [OR REPLACE] FUNCTION function_name [parameters]
RETURN return_datatype;
IS
Declaration_section
BEGIN
Execution_section
Return return_variable;
EXCEPTION exception section
Return return_variable;
END;
Mrs. Ujjwala S Patil (SITCOE)
Example for creating Function:
Create or replace function salcnt(minsal number , maxsal number)
Return number
Is
Cnt number;
Begin
Select count (*) into cnt from emp where sal between minsal and
maxsal;
Return cnt;
End;
Mrs. Ujjwala S Patil (SITCOE)
Executing Function:
To execute the above function write the calling body,
Declare
Count1 number;
Begin
Count1:=salcnt(30000, 50000);
Dbms_output.put_line(‘number of records are :’ || Count1);
End;
Mrs. Ujjwala S Patil (SITCOE)
Deleting Function:
Function can be dropped using drop function command.
Syntax:
Drop function function_Name;
Example:
Drop function salcnt;
Output:
Function dropped
1.01 seconds
Mrs. Ujjwala S Patil (SITCOE)
Advantages of Function:
• We can make a single call to the database to run a block of
statements thus it improves the performance against running SQL
multiple times. This will reduce the number of calls between the
database and the application.
• We can divide the overall work into small modules which
becomes quite manageable also enhancing the readability of the
code.
• It promotes reusability.
• It is secure since the code stays inside the database thus hiding
internal database details from the application(user).
• Works better in client server type of operations.
• Increase the flexibility of the program.
• It saves time and cost.
Mrs. Ujjwala S Patil (SITCOE)
Difference between Procedure and Function:
Sr.
No
PROCEDURE FUNCTION
1
Used mainly to execute certain business
logic with DML statements
Used mainly to perform some computational process
and returning the result of that process.
2
Procedure can return zero or more values
as output.
Function can return only single value as output
3
Procedure cannot call with select
statement, but can call from a block or
from a procedure
Function can call with select statement , if function
doesnot contain any DML statements and DDL
statements..
function with DML and DDL statements can call with
select statement with some special cases (using Pragma
autonomous transaction)
4
OUT keyword is used to return a value
from procedure
RETURN keyword is used to return a value from a
function.
5 It is not mandatory to return the value It is mandatory to return the value
6
RETURN will simply exit the control
from subprogram
RETURN will exit the control from subprogram and
also returns the value
7
Return datatype will not be specified at
the time of creation
Return datatype is mandatory at the time of creation
Mrs. Ujjwala S Patil (SITCOE)
4.7 Database Triggers:
A trigger is a stored procedure in database which automatically
invokes whenever a special event in the database occurs.
Database trigger can be referred as stored procedure that are fired
or executed when an insert, update or delete statement is given
against the associated table.
For example, a trigger can be invoked when a row is inserted into a
specified table or when certain table columns are being updated.
Mrs. Ujjwala S Patil (SITCOE)
Use of Database Trigger:
• Automatically generate derived column values
• To execute the data automatically.
• To implement complicated integrity constraints.
• Modify table data when DML statements are issued against
views
• Publish information about database events, user events, and
SQL statements to subscribing applications
• Restrict DML operations against a table to those issued
during regular business hours
• Enforce security authorizations
• Prevent invalid transactions
• To check the data modification.
Mrs. Ujjwala S Patil (SITCOE)
Creating Database Trigger:
Trigger is a stored procedure, they can be created in the same way
like we create the stored procedure.
Syntax:
CREATE [OR REPLACE ] TRIGGER <trigger_name>
[BEFORE / AFTER ] [INSERT / UPDATE / DELETE]
ON table_name [for each statement / for each row]
[<WHEN condition>];
Example:
Create or replace trigger bill_trig berfore delete on bill where
bill_no <=100;
Mrs. Ujjwala S Patil (SITCOE)
Deleting Trigger:
Trigger can be deleted using drop trigger command.
Syntax:
Drop trigger <trigger name>;
Example:
Drop trigger bill_trig;
Output:
Trigger Dropped
0.12 seconds.
Mrs. Ujjwala S Patil (SITCOE)
How to Apply Database Trigger?
Trigger is a stored procedure, they can be created in the same way
like we create the stored procedure.
We need to use raise_application_error() statemnt to show user
defined error or error created because of user defined trigger.
Then syntax for raise_application_error( ) is
raise_application_error( error_number, message);
Mrs. Ujjwala S Patil (SITCOE)
Example of Trigger use:
Create or replace trigger bill_trig before delete
on bill where bill_no<=100;
Declare
Begin
Raise_application_error(-20000, ‘You can not delete the record’);
End;
Output:
Trigger created
0.21 seconds.
Mrs. Ujjwala S Patil (SITCOE)
When we try to run the following command
Delete from bill where bill_no=90;
Output:
ORA-20000: You can not delete the record
ORA-06512 : at ‘UJJWALA.BILL_TRIG’ Line 2
ORA-04088 : error during execution of trigger
‘UJJWALA.BILL_TRIG’
1. Delete from bill where bill_no=90;
Mrs. Ujjwala S Patil (SITCOE)
Types of Trigger:
• Statement-level trigger
• Row-level trigger
• Before triggers
• After triggers
Mrs. Ujjwala S Patil (SITCOE)
Thank You
Ad

Recommended

PL SQL.pptx in computer language in database
PL SQL.pptx in computer language in database
ironman82715
 
pl_sql.ppt
pl_sql.ppt
Prabhat106214
 
L9 l10 server side programming
L9 l10 server side programming
Rushdi Shams
 
PLSQL.pptx
PLSQL.pptx
git21is061t
 
PL/SQL for Beginners - PL/SQL Tutorial 1
PL/SQL for Beginners - PL/SQL Tutorial 1
Gurpreet singh
 
SQL / PL
SQL / PL
srijanani2030
 
B.Sc. II (IV Sem) RDBMS & PL/SQL Unit-5 PL/SQL, Cursor and Trigger
B.Sc. II (IV Sem) RDBMS & PL/SQL Unit-5 PL/SQL, Cursor and Trigger
Assistant Professor, Shri Shivaji Science College, Amravati
 
Oracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online Training
suresh
 
UNIT 1- RELATIONAL DATABASE DESIGN USING PLSQL.pdf
UNIT 1- RELATIONAL DATABASE DESIGN USING PLSQL.pdf
KavitaShinde26
 
ORACLE PL/SQL
ORACLE PL/SQL
ASHABOOPATHY
 
Lecture Notes Unit5 chapter 15 PL/SQL Programming
Lecture Notes Unit5 chapter 15 PL/SQL Programming
Murugan146644
 
Pl sql
Pl sql
nikhilsh66131
 
Pl sql
Pl sql
nikhilsh66131
 
Pl sql
Pl sql
nikhilsh66131
 
Procedural Language/Structured Query Language
Procedural Language/Structured Query Language
allinzone1
 
rdbms.pdf plsql database system notes for students to study
rdbms.pdf plsql database system notes for students to study
rarelyused
 
PL-SQL.pdf
PL-SQL.pdf
Anas Nakash
 
Pl sql
Pl sql
Hitesh Kumar Markam
 
10g plsql slide
10g plsql slide
Tanu_Manu
 
plsql.ppt
plsql.ppt
faizan992426
 
PLSQL Tutorial
PLSQL Tutorial
Quang Minh Đoàn
 
Dbms 2011
Dbms 2011
Atiqa Khan
 
Ppt on plssql study aboutnsmsmskskwkwkwkwk
Ppt on plssql study aboutnsmsmskskwkwkwkwk
DrStrange634619
 
PL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics Covered
Danish Mehraj
 
PL/SQL is a block structured language that enables developers to combine the ...
PL/SQL is a block structured language that enables developers to combine the ...
renuka b
 
Ch as pbdasdadssadsadsadasdasdasdas fdt .pptx
Ch as pbdasdadssadsadsadasdasdasdas fdt .pptx
sharmilasatishpore
 
PLSQL Note
PLSQL Note
Arun Sial
 
PL_pgSQL_Control_Structures__An_Introduction.pdf
PL_pgSQL_Control_Structures__An_Introduction.pdf
RezaZulman
 
special_edition_using_visual_foxpro_6.pdf
special_edition_using_visual_foxpro_6.pdf
Shabista Imam
 
Data Structures Module 3 Binary Trees Binary Search Trees Tree Traversals AVL...
Data Structures Module 3 Binary Trees Binary Search Trees Tree Traversals AVL...
resming1
 

More Related Content

Similar to SQL Programming in database Management System (20)

UNIT 1- RELATIONAL DATABASE DESIGN USING PLSQL.pdf
UNIT 1- RELATIONAL DATABASE DESIGN USING PLSQL.pdf
KavitaShinde26
 
ORACLE PL/SQL
ORACLE PL/SQL
ASHABOOPATHY
 
Lecture Notes Unit5 chapter 15 PL/SQL Programming
Lecture Notes Unit5 chapter 15 PL/SQL Programming
Murugan146644
 
Pl sql
Pl sql
nikhilsh66131
 
Pl sql
Pl sql
nikhilsh66131
 
Pl sql
Pl sql
nikhilsh66131
 
Procedural Language/Structured Query Language
Procedural Language/Structured Query Language
allinzone1
 
rdbms.pdf plsql database system notes for students to study
rdbms.pdf plsql database system notes for students to study
rarelyused
 
PL-SQL.pdf
PL-SQL.pdf
Anas Nakash
 
Pl sql
Pl sql
Hitesh Kumar Markam
 
10g plsql slide
10g plsql slide
Tanu_Manu
 
plsql.ppt
plsql.ppt
faizan992426
 
PLSQL Tutorial
PLSQL Tutorial
Quang Minh Đoàn
 
Dbms 2011
Dbms 2011
Atiqa Khan
 
Ppt on plssql study aboutnsmsmskskwkwkwkwk
Ppt on plssql study aboutnsmsmskskwkwkwkwk
DrStrange634619
 
PL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics Covered
Danish Mehraj
 
PL/SQL is a block structured language that enables developers to combine the ...
PL/SQL is a block structured language that enables developers to combine the ...
renuka b
 
Ch as pbdasdadssadsadsadasdasdasdas fdt .pptx
Ch as pbdasdadssadsadsadasdasdasdas fdt .pptx
sharmilasatishpore
 
PLSQL Note
PLSQL Note
Arun Sial
 
PL_pgSQL_Control_Structures__An_Introduction.pdf
PL_pgSQL_Control_Structures__An_Introduction.pdf
RezaZulman
 
UNIT 1- RELATIONAL DATABASE DESIGN USING PLSQL.pdf
UNIT 1- RELATIONAL DATABASE DESIGN USING PLSQL.pdf
KavitaShinde26
 
Lecture Notes Unit5 chapter 15 PL/SQL Programming
Lecture Notes Unit5 chapter 15 PL/SQL Programming
Murugan146644
 
Procedural Language/Structured Query Language
Procedural Language/Structured Query Language
allinzone1
 
rdbms.pdf plsql database system notes for students to study
rdbms.pdf plsql database system notes for students to study
rarelyused
 
10g plsql slide
10g plsql slide
Tanu_Manu
 
Ppt on plssql study aboutnsmsmskskwkwkwkwk
Ppt on plssql study aboutnsmsmskskwkwkwkwk
DrStrange634619
 
PL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics Covered
Danish Mehraj
 
PL/SQL is a block structured language that enables developers to combine the ...
PL/SQL is a block structured language that enables developers to combine the ...
renuka b
 
Ch as pbdasdadssadsadsadasdasdasdas fdt .pptx
Ch as pbdasdadssadsadsadasdasdasdas fdt .pptx
sharmilasatishpore
 
PL_pgSQL_Control_Structures__An_Introduction.pdf
PL_pgSQL_Control_Structures__An_Introduction.pdf
RezaZulman
 

Recently uploaded (20)

special_edition_using_visual_foxpro_6.pdf
special_edition_using_visual_foxpro_6.pdf
Shabista Imam
 
Data Structures Module 3 Binary Trees Binary Search Trees Tree Traversals AVL...
Data Structures Module 3 Binary Trees Binary Search Trees Tree Traversals AVL...
resming1
 
دراسة حاله لقرية تقع في جنوب غرب السودان
دراسة حاله لقرية تقع في جنوب غرب السودان
محمد قصص فتوتة
 
Solar thermal – Flat plate and concentrating collectors .pptx
Solar thermal – Flat plate and concentrating collectors .pptx
jdaniabraham1
 
Call For Papers - 17th International Conference on Wireless & Mobile Networks...
Call For Papers - 17th International Conference on Wireless & Mobile Networks...
hosseinihamid192023
 
FUNDAMENTALS OF COMPUTER ORGANIZATION AND ARCHITECTURE
FUNDAMENTALS OF COMPUTER ORGANIZATION AND ARCHITECTURE
Shabista Imam
 
Tally.ERP 9 at a Glance.book - Tally Solutions .pdf
Tally.ERP 9 at a Glance.book - Tally Solutions .pdf
Shabista Imam
 
How to Un-Obsolete Your Legacy Keypad Design
How to Un-Obsolete Your Legacy Keypad Design
Epec Engineered Technologies
 
Generative AI & Scientific Research : Catalyst for Innovation, Ethics & Impact
Generative AI & Scientific Research : Catalyst for Innovation, Ethics & Impact
AlqualsaDIResearchGr
 
May 2025: Top 10 Read Articles in Data Mining & Knowledge Management Process
May 2025: Top 10 Read Articles in Data Mining & Knowledge Management Process
IJDKP
 
Tesla-Stock-Analysis-and-Forecast.pptx (1).pptx
Tesla-Stock-Analysis-and-Forecast.pptx (1).pptx
moonsony54
 
Introduction to sensing and Week-1.pptx
Introduction to sensing and Week-1.pptx
KNaveenKumarECE
 
20CE404-Soil Mechanics - Slide Share PPT
20CE404-Soil Mechanics - Slide Share PPT
saravananr808639
 
Complete University of Calculus :: 2nd edition
Complete University of Calculus :: 2nd edition
Shabista Imam
 
retina_biometrics ruet rajshahi bangdesh.pptx
retina_biometrics ruet rajshahi bangdesh.pptx
MdRakibulIslam697135
 
Cadastral Maps
Cadastral Maps
Google
 
Rapid Prototyping for XR: Lecture 2 - Low Fidelity Prototyping.
Rapid Prototyping for XR: Lecture 2 - Low Fidelity Prototyping.
Mark Billinghurst
 
CST413 KTU S7 CSE Machine Learning Clustering K Means Hierarchical Agglomerat...
CST413 KTU S7 CSE Machine Learning Clustering K Means Hierarchical Agglomerat...
resming1
 
Fatality due to Falls at Working at Height
Fatality due to Falls at Working at Height
ssuserb8994f
 
Modern multi-proposer consensus implementations
Modern multi-proposer consensus implementations
François Garillot
 
special_edition_using_visual_foxpro_6.pdf
special_edition_using_visual_foxpro_6.pdf
Shabista Imam
 
Data Structures Module 3 Binary Trees Binary Search Trees Tree Traversals AVL...
Data Structures Module 3 Binary Trees Binary Search Trees Tree Traversals AVL...
resming1
 
دراسة حاله لقرية تقع في جنوب غرب السودان
دراسة حاله لقرية تقع في جنوب غرب السودان
محمد قصص فتوتة
 
Solar thermal – Flat plate and concentrating collectors .pptx
Solar thermal – Flat plate and concentrating collectors .pptx
jdaniabraham1
 
Call For Papers - 17th International Conference on Wireless & Mobile Networks...
Call For Papers - 17th International Conference on Wireless & Mobile Networks...
hosseinihamid192023
 
FUNDAMENTALS OF COMPUTER ORGANIZATION AND ARCHITECTURE
FUNDAMENTALS OF COMPUTER ORGANIZATION AND ARCHITECTURE
Shabista Imam
 
Tally.ERP 9 at a Glance.book - Tally Solutions .pdf
Tally.ERP 9 at a Glance.book - Tally Solutions .pdf
Shabista Imam
 
Generative AI & Scientific Research : Catalyst for Innovation, Ethics & Impact
Generative AI & Scientific Research : Catalyst for Innovation, Ethics & Impact
AlqualsaDIResearchGr
 
May 2025: Top 10 Read Articles in Data Mining & Knowledge Management Process
May 2025: Top 10 Read Articles in Data Mining & Knowledge Management Process
IJDKP
 
Tesla-Stock-Analysis-and-Forecast.pptx (1).pptx
Tesla-Stock-Analysis-and-Forecast.pptx (1).pptx
moonsony54
 
Introduction to sensing and Week-1.pptx
Introduction to sensing and Week-1.pptx
KNaveenKumarECE
 
20CE404-Soil Mechanics - Slide Share PPT
20CE404-Soil Mechanics - Slide Share PPT
saravananr808639
 
Complete University of Calculus :: 2nd edition
Complete University of Calculus :: 2nd edition
Shabista Imam
 
retina_biometrics ruet rajshahi bangdesh.pptx
retina_biometrics ruet rajshahi bangdesh.pptx
MdRakibulIslam697135
 
Cadastral Maps
Cadastral Maps
Google
 
Rapid Prototyping for XR: Lecture 2 - Low Fidelity Prototyping.
Rapid Prototyping for XR: Lecture 2 - Low Fidelity Prototyping.
Mark Billinghurst
 
CST413 KTU S7 CSE Machine Learning Clustering K Means Hierarchical Agglomerat...
CST413 KTU S7 CSE Machine Learning Clustering K Means Hierarchical Agglomerat...
resming1
 
Fatality due to Falls at Working at Height
Fatality due to Falls at Working at Height
ssuserb8994f
 
Modern multi-proposer consensus implementations
Modern multi-proposer consensus implementations
François Garillot
 
Ad

SQL Programming in database Management System

  • 1. SQL Programming 4.1 Introduction to PL/SQL : PL/SQL is a block structured language that enables developers to combine the power of SQL with procedural statements. All the statements of a block are passed to oracle engine all at once which increases processing speed and decreases the traffic. PL/SQL is a highly structured and readable language. Its constructs express the intent of the code clearly. Also, PL/SQL is a straightforward language to learn. PL/SQL is a standard and portable language for Oracle Database development Mrs. Ujjwala S Patil (SITCOE)
  • 2. Mrs. Ujjwala S Patil (SITCOE) Advantages of PL/SQL: Reduces network traffic Procedural language Error handling Declare variable Intermediate Calculation Portable application
  • 3. Mrs. Ujjwala S Patil (SITCOE) Features of PL/SQL: • PL/SQL is basically a procedural language, which provides the functionality of decision making, iteration and many more features of procedural programming languages. • PL/SQL can execute a number of queries in one block using single command. • One can create a PL/SQL unit such as procedures, functions, packages, triggers, and types, which are stored in the database for reuse by applications. • PL/SQL provides a feature to handle the exception which occurs in PL/SQL block known as exception handling block. • Applications written in PL/SQL are portable to computer hardware or operating system where Oracle is operational. • PL/SQL Offers extensive error checking.
  • 4. Mrs. Ujjwala S Patil (SITCOE) Differences between SQL and PL/SQL: SQL PL/SQL SQL is a single query that is used to perform DML and DDL operations. PL/SQL is a block of codes that used to write the entire program blocks/ procedure/ function, etc. It is declarative, that defines what needs to be done, rather than how things need to be done. PL/SQL is procedural that defines how the things needs to be done. Execute as a single statement. Execute as a whole block. Mainly used to manipulate data. Mainly used to create an application. Cannot contain PL/SQL code in it. It is an extension of SQL, so it can contain SQL inside it.
  • 5. Mrs. Ujjwala S Patil (SITCOE) PL/SQL Block Structure: OR • Declare section starts with DECLARE keyword in which variables, constants, records as cursors can be declared which stores data temporarily. It basically consists definition of PL/SQL identifiers. This part of the code is optional.
  • 6. Mrs. Ujjwala S Patil (SITCOE) PL/SQL Block structure cont… • Execution section starts with BEGIN and ends with END keyword. This is a mandatory section and here the program logic is written to perform any task like loops and conditional statements. It supports all DML commands, DDL commands and SQL*PLUS built-in functions as well. • Exception section starts with EXCEPTION keyword. This section is optional which contains statements that are executed when a run-time error occurs. Any exceptions can be handled in this section
  • 7. Mrs. Ujjwala S Patil (SITCOE) PL/SQL Execution Environment : When a user submit an SQL statement to the database instance, it will accept the SQL statement for execution in following phases: Parse Phase Execute Phase Fetch Phase
  • 8. Mrs. Ujjwala S Patil (SITCOE) PL/SQL Execution Environment cont.. The PL/SQL engine resides in the Oracle engine. The Oracle engine can process not only single SQL statement but also block of many statements. The call to Oracle engine needs to be made only once to execute any number of SQL statements if these SQL statements are bundled inside a PL/SQL block.
  • 9. Mrs. Ujjwala S Patil (SITCOE) PL/SQL Data type: There are various types of data types are there Character Data types Numeric Data types Date/Time Data types
  • 10. Mrs. Ujjwala S Patil (SITCOE) PL/SQL Variable: These are placeholders that store the values that can change through the PL/SQL Block. General Syntax to declare a variable is variable_name datatype [NOT NULL := value ];
  • 11. Mrs. Ujjwala S Patil (SITCOE) 4.2 Control Structure: Conditional Control, Iterative Control, Sequential control:
  • 12. Mrs. Ujjwala S Patil (SITCOE) 1. Selection control: The selection structure tests a condition, then executes one sequence of statements instead of another, depending on whether the condition is true or false. A condition is any variable or expression that returns a BOOLEAN value (TRUE or FALSE). Conditional selection statements, which run different statements for different data values. The conditional selection statements are IF and CASE.
  • 13. Mrs. Ujjwala S Patil (SITCOE) Iteration Control: The iteration structure executes a sequence of statements repeatedly as long as a condition holds true. Loop statements, which run the same statements with a series of different data values. The loop statements are the basic LOOP, FOR LOOP, and WHILE LOOP. The EXIT statement transfers control to the end of a loop. The CONTINUE statement exits the current iteration of a loop and transfers control to the next iteration. Both EXIT and CONTINUE have an optional WHEN clause, where you can specify a condition.
  • 14. Mrs. Ujjwala S Patil (SITCOE) Sequential Control: The sequence-structure simply executes a sequence of statements in the order in which they occur. Sequential control statements, which are not crucial to PL/SQL programming. The sequential control statements are GOTO, which goes to a specified statement, and NULL, which does nothing.
  • 15. Mrs. Ujjwala S Patil (SITCOE) Conditional Selection Statements: The conditional selection statements, IF and CASE, run different statements for different data values. The IF statement either runs or skips a sequence of one or more statements, depending on a condition. The IF statement has these forms: IF THEN IF THEN ELSE IF THEN ELSIF
  • 16. Mrs. Ujjwala S Patil (SITCOE) IF THEN Statement: The IF THEN statement either runs or skips a sequence of one or more statements, depending on a condition. The IF THEN statement has this structure: IF condition THEN Statements END IF; If the condition is true, the statements run; otherwise, the IF statement does nothing.
  • 17. Mrs. Ujjwala S Patil (SITCOE) IF THEN ELSE Statement : The IF THEN ELSE statement has this structure: IF condition THEN Statements ELSE else_statements END IF; If the value of condition is true, the statements run; otherwise, the else_statements run.
  • 18. Mrs. Ujjwala S Patil (SITCOE) Example for IF THEN ELSE: Write a PL/SQL program to check given number is odd or Even. Declare num int:=: num; Begin if(MOD(num,2))=0 then Dbms_output.put_line(‘Given num is Even’); Else Dbms_output.put_line(‘Given num is Odd’); END IF; End;
  • 19. Mrs. Ujjwala S Patil (SITCOE) IF THEN ELSIF Statement The IF THEN ELSIF statement has this structure: IF condition_1 THEN statements_1 ELSIF condition_2 THEN statements_2 [ ELSIF condition_3 THEN statements_3]... [ ELSE else_statements] END IF; The IF THEN ELSIF statement runs the first statements for which condition is true. Remaining conditions are not evaluated. If no condition is true, the else_statements run, if they exist; otherwise, the IF THEN ELSIF statement does nothing.
  • 20. Mrs. Ujjwala S Patil (SITCOE) Example of IF THEN ELSIF Statement: PL/SQL code to accept 3 numbers and display the largest number. Declare num1 int:=:num1; num2 int:=:num2; num3 int:=:num3; Begin IF (num1>num2 AND num1>num3) THEN Dbms_output.put_line('num1 is greater'); ELSIF (num2>num1 AND num2>num3) THEN Dbms_output.put_line('num2 is greater'); ELSIF (num3>num1 AND num3>num2) THEN Dbms_output.put_line('num3 is greater'); Else Dbms_output.put_line('All numbers are equal'); END IF; END;
  • 21. Mrs. Ujjwala S Patil (SITCOE) Simple CASE Statement : The simple CASE statement has this structure: CASE selector WHEN selector_value_1 THEN statements_1 WHEN selector_value_2 THEN statements_2... WHEN selector_value_n THEN statements_n [ ELSE else_statements ] END CASE; The selector is an expression (typically a single variable). Each selector_value can be either a literal or an expression. The simple CASE statement runs the first statements for which selector_value equals selector. Remaining conditions are not evaluated. If no selector_value equals selector, the CASE statement runs else_statements if they exist and raises the predefined exception CASE_NOT_FOUND otherwise.
  • 22. Mrs. Ujjwala S Patil (SITCOE) Example For CASE Statement: Declare a character variable assign any alphabet to it and display whether the enter alphabet is vowel or consonant using CASE statement. Declare ch char:=:ch; Begin CASE WHEN (ch='A' or ch='a' or ch='e' or ch='e' or ch='I' or ch='i' or ch='O' or ch='o' or ch='U' or ch='u') THEN Dbms_output.put_line('Vowel'); ELSE Dbms_output.put_line('Consonant'); END CASE; End
  • 23. Mrs. Ujjwala S Patil (SITCOE) Iterative control: Iterative control is used for executing the tasks that are having repetitions. Iterative controls are: Loop Statement While loop For loop
  • 24. Mrs. Ujjwala S Patil (SITCOE) Loop Statement: Loop statements let you execute a sequence of statements multiple times. The simple form of loop statement is the basic(or infinite) loop, which enclose a sequence of statement between the keyword LOOP and END LOOP. Syntax: LOOP <Commands> IF <Condition> THEN Statement; EXIT; End IF; END LOOP;
  • 25. Mrs. Ujjwala S Patil (SITCOE) Example for Simple LOOP: Declare i number :=0; Begin LOOP i := i+1; If (i<=10) THEN dbms_output.put_line(i); EXIT; END IF; END LOOP; END;
  • 26. Mrs. Ujjwala S Patil (SITCOE) While Loop: The while loop statement associates a condition with a sequence of statement. Syntax: WHILE <Condition> LOOP <Commands> /* List of Statements*/ END LOOP
  • 27. Mrs. Ujjwala S Patil (SITCOE) Example for While LOOP: Declare i number :=0; Begin While i<=10 LOOP i:=i+1; Dbms_output.put_line(i); END LOOP; END;
  • 28. Mrs. Ujjwala S Patil (SITCOE) For Loop: Where as the number of iterations through a while loop is unknown until the loop completes, the number of iterations through a for loop is known before the loop is entered. For loop iterates over a specific range of integers. The range is a part of an iteration scheme which is enclosed by the keyword FOR and LOOP. A double dots (..) serves as the range operator. Syntax: For <variable> IN [reverse] <min value> .. < max value> LOOP List of statements; END LOOP;
  • 29. Mrs. Ujjwala S Patil (SITCOE) For Loop Example: Print I to 10 numbers using for loop. declare i int; Begin For i in 1..10 loop Dbms_output.put_line(i); End loop; End;
  • 30. Mrs. Ujjwala S Patil (SITCOE) For Loop Example: Print 10 to 1 numbers using for loop. declare i int; Begin For i in REVERSE 1..10 loop dbms_output.put_line(i); End loop; End; :
  • 31. Mrs. Ujjwala S Patil (SITCOE) Sequential control:( GOTO and NULL) Unlike the IF and LOOP statements, the sequential control statements GOTO and NULL are not crucial to PL/SQL programming. The GOTO is used for transferring the control. Overuse of GOTO statements can result in complex, unstructured code that is hard to understand and maintain. The NULL statement does nothing other than pass control to the next statement. The NULL statement can improve readability by making the meaning and action of conditional statement clear.
  • 32. Mrs. Ujjwala S Patil (SITCOE) GOTO Statement: The GOTO statement transfers control to a label unconditionally. The label must be unique in its scope and must precede an executable statement or a PL/SQL block. When run, the GOTO statement transfers control to the labeled statement or block. Syntax: GOTO label_name; where label_name is the name of a label identifying the target statement. This GOTO label is defined in the program as follows: <<label_name>>
  • 33. Mrs. Ujjwala S Patil (SITCOE) Example for GOTO Statement: BEGIN GOTO second_output; DBMS_OUTPUT.PUT_LINE('This line will never execute.'); <<second_output>> DBMS_OUTPUT.PUT_LINE('We are here!'); END;
  • 34. Mrs. Ujjwala S Patil (SITCOE) Restrictions of GOTO Statement: There are several restrictions on the GOTO statement: At least one executable statement must follow a label. The target label must be in the same scope as the GOTO statement. The target label must be in the same part of the PL/SQL block as the GOTO. The GOTO statement can come in handy. There are cases where a GOTO statement can simplify the logic in your program. On the other hand, because PL/SQL provides so many different control constructs and modularization techniques, you can almost always find a better way to do something than with a GOTO.
  • 35. Mrs. Ujjwala S Patil (SITCOE) NULL Statement: The NULL statement does nothing other than pass control to the next statement. The NULL statement can improve readability by making the meaning and action of conditional statement clear. Some uses for the NULL statement are: • To provide a target for a GOTO statement. • To improve readability by making the meaning and action of conditional statements clear. • To create placeholders and stub subprograms. • To show that you are aware of a possibility, but that no action is necessary.
  • 36. Mrs. Ujjwala S Patil (SITCOE) The NULL statement has the following format: NULL; Example : Compute the bonus for employee whose rating is greater than 90% If rating is >90 then Compute_bonus(emp_id); Else NULL; End IF;
  • 37. Mrs. Ujjwala S Patil (SITCOE) 4.3 Exception Handling: Predefined and user defined Exception: An exception occurs when the PL/SQL engine encounters an instruction which it cannot execute due to an error that occurs at run-time. These errors will not be captured at the time of compilation and hence these needed to handle only at the run-time. Exceptions will stop the program from executing further, so to avoid such condition, they need to be captured and handled separately. This process is called as Exception-Handling, in which the programmer handles the exception that can occur at the run time.
  • 38. Mrs. Ujjwala S Patil (SITCOE) Exception-Handling Syntax: Exceptions are handled at the block, level, i.e., once if any exception occurs in any block then the control will come out of execution part of that block. The exception will then be handled at the exception handling part of that block. After handling the exception, it is not possible to resend control back to the execution section of that block. The below syntax explains how to catch and handle the exception.
  • 39. Mrs. Ujjwala S Patil (SITCOE) Types of Exception There are two types of Exceptions in Pl/SQL. Predefined Exceptions User-defined Exception Predefined Exceptions Oracle has predefined some common exception. These exceptions have a unique exception name and error number. These exceptions are already defined in the 'STANDARD' package in Oracle. User-defined Exception In Oracle, other than the above-predefined exceptions, the programmer can create their own exception and handle them. They can be created at a subprogram level in the declaration part.
  • 40. Mrs. Ujjwala S Patil (SITCOE) Predefined Exceptions Oracle has predefined some common exception. These exceptions have a unique exception name and error number. These exceptions are already defined in the 'STANDARD' package in Oracle. In code, we can directly use these predefined exception name to handle them. Exception Error Code Exception Reason ACCESS_INTO _NULL ORA- 06530 Assign a value to the attributes of uninitialized objects CASE_NOT_F OUND ORA- 06592 None of the 'WHEN' clause in CASE statement satisfied and no 'ELSE' clause is specified COLLECTION_ IS_NULL ORA- 06531 Using collection methods (except EXISTS) or accessing collection attributes on a uninitialized collections
  • 41. Mrs. Ujjwala S Patil (SITCOE) Exception Error Code Exception Reason CURSOR_ALREA DY_OPEN ORA-06511 Trying to open a cursor which is already opened INVALID_CURSO R ORA-01001 Illegal cursor operations like closing an unopened cursor INVALID_NUMB ER ORA-01722 Conversion of character to a number failed due to invalid number character TOO_MANY_RO WS ORA-01422 When a 'SELECT' statement with INTO clause returns more than one row VALUE_ERROR ORA-06502 Arithmetic or size constraint error (eg: assigning a value to a variable that is larger than the variable size) ZERO_DIVIDE ORA-01476 Dividing a number by '0'
  • 42. Mrs. Ujjwala S Patil (SITCOE) Examples for Predefined Exception: NO_DATA_FOUND declare emp_no EMP.EMPNO%type; begin select SAL into emp_no from EMP where EMPNO=736; exception when NO_DATA_FOUND then dbms_output.put_line('Employee not available'); end;
  • 43. Mrs. Ujjwala S Patil (SITCOE) Example for Predefined Exception: ZERO_DIVIDE declare a number:=:a; b number:=:b; c number; begin c:=a/b; dbms_output.put_line('Result' || c); exception when ZERO_DIVIDE then dbms_output.put_line('Number can not divide by zero'); end;
  • 44. Mrs. Ujjwala S Patil (SITCOE) User Defined Exceptions: In Oracle, other than the above-predefined exceptions, the programmer can create their own exception and handle them. They can be created at a subprogram level in the declaration part. These exceptions are visible only in that subprogram. The exception that is defined in the package specification is public exception, and it is visible wherever the package is accessible. DECLARE<exception_name> EXCEPTION; BEGIN <Execution block> EXCEPTION WHEN <exception_name> THEN <Handler> END;
  • 45. Mrs. Ujjwala S Patil (SITCOE) Example for User defined Exception: declare emp_sal EMP.SAL%type; less_sal exception; begin select SAL into emp_sal from EMP where EMPNO=7369; if emp_sal<3000 then raise less_sal; else dbms_output.put_line('salary greater than 3000'); end if; exception when less_sal then dbms_output.put_line('sal less than 3000'); end;
  • 46. Mrs. Ujjwala S Patil (SITCOE) 4.4. Cursors: A cursor is a temporary work area created in the system memory when a SQL statement is executed. A cursor contains information on a select statement and the rows of data accessed by it. This temporary work area is used to store the data retrieved from the database, and manipulate this data. A cursor can hold more than one row, but can process only one row at a time. The set of rows the cursor holds is called the active set. There are 2 types of Cursors: Implicit Cursors Explicit Cursors.
  • 47. Mrs. Ujjwala S Patil (SITCOE) Implicit Cursors: Implicit Cursors are also known as Default Cursors of SQL SERVER. These are created by default when DML statements like, INSERT, UPDATE, and DELETE statements are executed. They are also created when a SELECT statement that returns just one row is executed. Explicit cursor: 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.
  • 48. Mrs. Ujjwala S Patil (SITCOE) 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, like Insert, Update, delete. Implicit cursors are used by oracle engine even if SELECT statement returns single row. For example, When you execute INSERT, UPDATE, or DELETE statements the cursor attributes tell us whether any rows are affected and how many have been affected. When a SELECT... INTO statement is executed in a PL/SQL Block, implicit cursor attributes can be used to find out whether any row has been returned by the SELECT statement. PL/SQL returns an error when no data is selected.
  • 49. Mrs. Ujjwala S Patil (SITCOE) Attributes of Implicit Cursor: 1. %FOUND 2. %NOTFOUND 3. %ISOPEN 4. %ROWCOUNT
  • 50. Mrs. Ujjwala S Patil (SITCOE) Example for Implici Cursors: DECLARE var_rows number(5); BEGIN UPDATE employee SET salary = salary + 1000; IF SQL%NOTFOUND THEN dbms_output.put_line('None of the salaries where updated'); ELSIF SQL%FOUND THEN var_rows := SQL%ROWCOUNT; dbms_output.put_line('Salaries for ' || var_rows || 'employees are updated'); END IF; END;
  • 51. Mrs. Ujjwala S Patil (SITCOE) Explicit Cursors: An explicit cursor is defined in the declaration section of the PL/SQL Block. It is created on a SELECT Statement which returns more than one row. We can provide a suitable name for the cursor. General Syntax for Explicit cursor : DECLARE variables; records; create a cursor; BEGIN OPEN cursor; FETCH cursor; process the records; CLOSE cursor; END;
  • 52. Mrs. Ujjwala S Patil (SITCOE) How to use Explicit Cursor? There are four steps in using an Explicit Cursor. DECLARE the cursor in the declaration section. OPEN the cursor in the Execution Section. FETCH the data from cursor into PL/SQL variables or records in the Execution Section. CLOSE the cursor in the Execution Section before you end the PL/SQL Block.
  • 53. Mrs. Ujjwala S Patil (SITCOE) 1. Declaring Cursor: Declare the cursor in declaration section: Syntax: Declare cursor cursor_name is Select statement; cursor_name – A suitable name for the cursor. select_statement – A select query which returns multiple rows. Example: DECLARE CURSOR emp_cur IS SELECT * FROM emp_tbl WHERE salary > 5000;
  • 54. Mrs. Ujjwala S Patil (SITCOE) 2. OPEN the cursor in the Execution Section: Syntax OPEN Cursor_Name; Example: OPEN emp_cur;
  • 55. Mrs. Ujjwala S Patil (SITCOE) 3. Fetch the records in the cursor one at a time: Syntax: FETCH cursor_name INTO record_name; OR FETCH cursor_name INTO variable_list; Example: Fetch emp_cur into sal;
  • 56. Mrs. Ujjwala S Patil (SITCOE) 4. Close the Cursors: Syntax: CLOSE cursor_name; Example: Close emp_cur; When a cursor is opened, the first row becomes the current row. When the data is fetched it is copied to the record or variables and the logical pointer moves to the next row and it becomes the current row. On every fetch statement, the pointer moves to the next row. If you want to fetch after the last row, the program will throw an error. When there is more than one row in a cursor we can use loops along with explicit cursor attributes to fetch all the records.
  • 57. Mrs. Ujjwala S Patil (SITCOE) Example for Explicit Cursors: DECLARE emp_rec emp_tbl%rowtype; CURSOR emp_cur IS SELECT * FROM emp_tbl WHERE salary > 10000; BEGIN OPEN emp_cur; FETCH emp_cur INTO emp_rec; dbms_output.put_line (emp_rec.first_name || ' ' || emp_rec.last_name); CLOSE emp_cur; END;
  • 58. Mrs. Ujjwala S Patil (SITCOE) Explicit Cursor Attributes: We use these attributes to avoid errors while accessing cursors through OPEN, FETCH and CLOSE Statements Attributes Return values Example %FOUND TRUE, if fetch statement returns at least one row. Cursor_name%FOUND FALSE, if fetch statement doesn’t return a row. %NOTFOUNDTRUE, , if fetch statement doesn’t return a row. Cursor_name %NOTFOUND FALSE, if fetch statement returns at least one row. %ROWCOUN T The number of rows fetched by the fetch statement Cursor_name %ROWCOUNT If no row is returned, the PL/SQL statement returns an error. %ISOPEN TRUE, if the cursor is already open in the program Cursor_name%ISNAME FALSE, if the cursor is not opened in the program.
  • 59. Mrs. Ujjwala S Patil (SITCOE) Cursor with a FOR Loop: When using FOR LOOP you need not declare a record or variables to store the cursor values, need not open, fetch and close the cursor. These functions are accomplished by the FOR LOOP automatically. General Syntax for using FOR LOOP: FOR record_name IN cusror_name LOOP process the row... END LOOP;
  • 60. Mrs. Ujjwala S Patil (SITCOE) Example for Cursor wit FOR LOOP: DECLARE CURSOR emp_cur IS SELECT first_name, last_name, salary FROM emp_tbl; emp_rec emp_cur%rowtype; BEGIN FOR emp_cur in emp_rec LOOP dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name || ' ' ||emp_cur.salary); END LOOP; END;
  • 61. Mrs. Ujjwala S Patil (SITCOE) Parameterized Cursor:
  • 62. Mrs. Ujjwala S Patil (SITCOE) Procedures: A procedure can be defined as a subprogram that perform a specific task or actions. A stored procedure or in simple a procedure is a named PL/SQL block which performs one or more specific task. This is similar to a procedure in other programming languages. A procedure has a header and a body. The header consists of the name of the procedure and the parameters or variables passed to the procedure. The body consists or declaration section, execution section and exception section similar to a general PL/SQL Block.
  • 63. Mrs. Ujjwala S Patil (SITCOE) General Syntax to create a procedure is: CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters] IS Declaration section BEGIN Execution section EXCEPTION Exception section END;
  • 64. Mrs. Ujjwala S Patil (SITCOE) Example for Procedure: CREATE OR REPLACE PROCEDURE checksal(eno number) IS salcom number; BEGIN Select salary+comm into salcom from employee where empno=eno; If (salcom>30000) then Dbms_output.put_line(‘salary and commission is greater than 30000’); Else Dbms_output.put_line(‘salary and commission is less than 30000’); End if; Exception When NO_DATA_FOUND then Dbms_output.put_line(‘No data Found’); END;
  • 65. Mrs. Ujjwala S Patil (SITCOE) How to execute a Stored Procedure? There are two ways to execute a procedure. 1) From the SQL prompt. EXECUTE [or EXEC] procedure_name; 2) Within another procedure – simply use the procedure name. procedure_name; Example: Declare Begin Checksal(0968); End;
  • 66. Mrs. Ujjwala S Patil (SITCOE) Deleting Procedure: Procedure can be dropped using drop procedure command. Syntax: Drop procedure procedure_name; Example: Drop procedure checksal; Output: Procedure dropped 1.01 seconds
  • 67. Mrs. Ujjwala S Patil (SITCOE) Advantages of Procedure: Better Performance Higher Productivity Ease of Use Scalability Maintainability Security
  • 68. Mrs. Ujjwala S Patil (SITCOE) 4.6 Functions : Function is a subprogram that is used for the purpose of code reusability. A function is a named PL/SQL Block which is similar to a procedure. The procedure and functions are almost same from the point of view of purpose. The major difference between a procedure and a function is, a function must always return a value, but a procedure may or may not return a value.
  • 69. Mrs. Ujjwala S Patil (SITCOE) General Syntax to create a function is CREATE [OR REPLACE] FUNCTION function_name [parameters] RETURN return_datatype; IS Declaration_section BEGIN Execution_section Return return_variable; EXCEPTION exception section Return return_variable; END;
  • 70. Mrs. Ujjwala S Patil (SITCOE) Example for creating Function: Create or replace function salcnt(minsal number , maxsal number) Return number Is Cnt number; Begin Select count (*) into cnt from emp where sal between minsal and maxsal; Return cnt; End;
  • 71. Mrs. Ujjwala S Patil (SITCOE) Executing Function: To execute the above function write the calling body, Declare Count1 number; Begin Count1:=salcnt(30000, 50000); Dbms_output.put_line(‘number of records are :’ || Count1); End;
  • 72. Mrs. Ujjwala S Patil (SITCOE) Deleting Function: Function can be dropped using drop function command. Syntax: Drop function function_Name; Example: Drop function salcnt; Output: Function dropped 1.01 seconds
  • 73. Mrs. Ujjwala S Patil (SITCOE) Advantages of Function: • We can make a single call to the database to run a block of statements thus it improves the performance against running SQL multiple times. This will reduce the number of calls between the database and the application. • We can divide the overall work into small modules which becomes quite manageable also enhancing the readability of the code. • It promotes reusability. • It is secure since the code stays inside the database thus hiding internal database details from the application(user). • Works better in client server type of operations. • Increase the flexibility of the program. • It saves time and cost.
  • 74. Mrs. Ujjwala S Patil (SITCOE) Difference between Procedure and Function: Sr. No PROCEDURE FUNCTION 1 Used mainly to execute certain business logic with DML statements Used mainly to perform some computational process and returning the result of that process. 2 Procedure can return zero or more values as output. Function can return only single value as output 3 Procedure cannot call with select statement, but can call from a block or from a procedure Function can call with select statement , if function doesnot contain any DML statements and DDL statements.. function with DML and DDL statements can call with select statement with some special cases (using Pragma autonomous transaction) 4 OUT keyword is used to return a value from procedure RETURN keyword is used to return a value from a function. 5 It is not mandatory to return the value It is mandatory to return the value 6 RETURN will simply exit the control from subprogram RETURN will exit the control from subprogram and also returns the value 7 Return datatype will not be specified at the time of creation Return datatype is mandatory at the time of creation
  • 75. Mrs. Ujjwala S Patil (SITCOE) 4.7 Database Triggers: A trigger is a stored procedure in database which automatically invokes whenever a special event in the database occurs. Database trigger can be referred as stored procedure that are fired or executed when an insert, update or delete statement is given against the associated table. For example, a trigger can be invoked when a row is inserted into a specified table or when certain table columns are being updated.
  • 76. Mrs. Ujjwala S Patil (SITCOE) Use of Database Trigger: • Automatically generate derived column values • To execute the data automatically. • To implement complicated integrity constraints. • Modify table data when DML statements are issued against views • Publish information about database events, user events, and SQL statements to subscribing applications • Restrict DML operations against a table to those issued during regular business hours • Enforce security authorizations • Prevent invalid transactions • To check the data modification.
  • 77. Mrs. Ujjwala S Patil (SITCOE) Creating Database Trigger: Trigger is a stored procedure, they can be created in the same way like we create the stored procedure. Syntax: CREATE [OR REPLACE ] TRIGGER <trigger_name> [BEFORE / AFTER ] [INSERT / UPDATE / DELETE] ON table_name [for each statement / for each row] [<WHEN condition>]; Example: Create or replace trigger bill_trig berfore delete on bill where bill_no <=100;
  • 78. Mrs. Ujjwala S Patil (SITCOE) Deleting Trigger: Trigger can be deleted using drop trigger command. Syntax: Drop trigger <trigger name>; Example: Drop trigger bill_trig; Output: Trigger Dropped 0.12 seconds.
  • 79. Mrs. Ujjwala S Patil (SITCOE) How to Apply Database Trigger? Trigger is a stored procedure, they can be created in the same way like we create the stored procedure. We need to use raise_application_error() statemnt to show user defined error or error created because of user defined trigger. Then syntax for raise_application_error( ) is raise_application_error( error_number, message);
  • 80. Mrs. Ujjwala S Patil (SITCOE) Example of Trigger use: Create or replace trigger bill_trig before delete on bill where bill_no<=100; Declare Begin Raise_application_error(-20000, ‘You can not delete the record’); End; Output: Trigger created 0.21 seconds.
  • 81. Mrs. Ujjwala S Patil (SITCOE) When we try to run the following command Delete from bill where bill_no=90; Output: ORA-20000: You can not delete the record ORA-06512 : at ‘UJJWALA.BILL_TRIG’ Line 2 ORA-04088 : error during execution of trigger ‘UJJWALA.BILL_TRIG’ 1. Delete from bill where bill_no=90;
  • 82. Mrs. Ujjwala S Patil (SITCOE) Types of Trigger: • Statement-level trigger • Row-level trigger • Before triggers • After triggers
  • 83. Mrs. Ujjwala S Patil (SITCOE) Thank You