0% found this document useful (0 votes)
8 views

Dms Unit4 Notesmzr

Uploaded by

vahaneaniket
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Dms Unit4 Notesmzr

Uploaded by

vahaneaniket
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

PL/SQL Programming

CO1: Write PL/SQL code for given database

S.V.BAHALE 1
Concept Explanation- Introduction of PL/SQL
• PL/SQL is a procedural language developed in the late 1980s as extension to Structured Query Language
(SQL). The purpose of PL/SQL is to combine database language and procedural programming language.
• PL/SQL is a completely portable, high-performance transaction-processing language.
• PL/SQL provides a built-in, interpreted and OS independent programming environment.
• PL/SQL can also directly be called from the command-line SQL*Plus interface.
• Direct call can also be made from external programming language calls to database.

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 the development of web applications and server pages.

S.V.BAHALE 1
Concept Explanation- Introduction of PL/SQL
Advantages of PL/SQL :
• SQL is the standard database language and PL/SQL is strongly integrated with 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.
• 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.

S.V.BAHALE 2
Concept Explanation- Introduction of PL/SQL
• The basic unit in PL/SQL is called a block and is made up of three parts: a declarative part, an executable part
and an exception-building part.
• Every PL/SQL statement ends with a semicolon (;).
• PL/SQL blocks can be nested within other PL/SQL blocks using BEGIN and END.

S.No Sections & Description


1 Declarations
This section starts with the keyword DECLARE. It is an optional section and defines all variables,
cursors, subprograms, and other elements to be used in the program.
2 Executable Commands
This section is enclosed between the keywords BEGIN and END and it is a mandatory section. It
consists of the executable PL/SQL statements of the program. It should have at least one executable
line of code, which may be just a NULL command to indicate that nothing should be executed.
3 Exception Handling
This section starts with the keyword EXCEPTION. This optional section contains exception(s) that
handle errors in the program.

S.V.BAHALE 3
Concept Explanation- Introduction of PL/SQL
Following is the basic structure of a PL/SQL block −
DECLARE <declarations section>
BEGIN <executable command(s)>
EXCEPTION <exception handling>
END;

The 'Hello World' Example :


DECLARE message varchar2(20):= 'Hello, World!';
BEGIN dbms_output.put_line(message);
END;
/

S.V.BAHALE 4
Concept Explanation- Introduction of PL/SQL
The PL/SQL Identifiers :
• PL/SQL identifiers are constants, variables, exceptions, procedures, cursors, and reserved words.
• Identifiers should not exceed 30 characters.
• By default, identifiers are not case-sensitive.
• Reserved keyword cannot be used as an identifier.
The PL/SQL Delimiters :
• A delimiter is a symbol with a special meaning. Following is the list of delimiters in PL/SQL −

Delimiter Description
+, -, *, / Addition, subtraction/negation, multiplication, division
% Attribute indicator
' Character string delimiter
. Component selector
(,) Expression or list delimiter
: Host variable indicator
, Item separator
" Quoted identifier delimiter
= Relational operator

S.V.BAHALE 5
Concept Explanation- The PL/SQL Delimiters :
Delimiter Description
@ Remote access indicator
; Statement terminator
:= Assignment operator
=> Association operator
|| Concatenation operator
** Exponentiation operator
<<, >> Label delimiter (begin and end)
/*, */ Multi-line comment delimiter (begin and end)
-- Single-line comment indicator
.. Range operator
<, >, <=, >= Relational operators
<>, '=, ~=, ^= Different versions of NOT EQUAL

S.V.BAHALE 6
Concept Explanation- PL/SQL Data Types
S.No Date Type & Description
1 Numeric :-Numeric values on which arithmetic operations are performed.

2 Character:-Alphanumeric values that represent single characters or strings of characters.

3 Boolean :-Logical values on which logical operations are performed.


4 Datetime :-Dates and times.
5 INTEGER / INT :-ANSI and IBM specific integer type with maximum precision of 38 decimal digits

6 CHAR :-Fixed-length character string with maximum size of 32,767 bytes

7 VARCHAR2 :-Variable-length character string with maximum size of 32,767 bytes

RAW :-Variable-length binary or byte string with maximum size of 32,767 bytes, not
8
interpreted by PL/SQL

9 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
10
interpreted by PL/SQL

11 ROWID :-Physical row identifier, the address of a row in an ordinary table

%Type :- Declare a variable or constant to have same data type as that of previously defined
12
variable or column in a table.

%rowtype :- The %ROWTYPE attribute provides a record type that represents a row in a
13
database table.
S.V.BAHALE 7
Concept Explanation- Variable Declaration in PL/SQL
• PL/SQL variables must be declared in the declaration section or in a package as a global variable.
Syntax :
variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]
Examples:
sales number(10, 2);
name varchar2(25);

Initializing Variables in PL/SQL :


• Whenever you declare a variable, PL/SQL assigns it a default value of NULL.
• Use DEFAULT keyword or assignment operator to initialize variables.
Examples:
Branch varchar2(10) DEFAULT ‘Computer';
a integer := 10 ;

Fetching Table data values into variables :


select studname INTO b from student where rollno=111;

Variable Scope in PL/SQL :

There are two types of variable scope −


Local variables − Variables declared in an inner block and not accessible to outer blocks.
Global variables − Variables declared in the outermost block or a package.

S.V.BAHALE 8
Concept Explanation- Variable Declaration in PL/SQL
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);
END;
END;
/

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.

Syntax :
Variable_name CONSTANT datatype := defined value ;

Example:
pi constant number := 3.141592654;
X CONSTANT number(3,2) := 0.10;
Y CONSTANT varchar2(10) := ‘WELCOME’;

S.V.BAHALE 9
Concept Explanation- Literals
There are Numeric , String, Character or Logical literals
Numeric Literals : These can be either integers or floats.
e.g. 25, 6.34, -5, 25e-03 etc.
String Literals : These are represented by one or more legal characters and must be enclosed within single
quotes. e.g. 'Hello, world!‘ , ‘19-Nov-2020’ etc.
Character Literals :
These are string literals consisting of single character. e.g ‘*’, ‘4’, ‘A’ etc.
Logical Literals : These are predetermined constants. The values it can take are True, False, NULL.

Displaying PL/SQL Output :

• The procedure dbms_output.put_line() is used to place the results in a buffer , which SQL*PLUS will retrieve
and display.
• The SET SERVEROUTPUT ON command causes SQL*PLUS to retrieve and display the contents of the buffer.
• Example:
• SQL> SET SERVEROUTPUT ON ;
dbms_output.put_line(‘hello’);
dbms_output.put_line(variable_name);
dbms_output.put_line(‘Welcome ‘||variable_name);
dbms_output.put_line(‘Welcome &variable_name’);

S.V.BAHALE 10
Concept Explanation- Examples
Examples :
DECLARE
message varchar2(20);
BEGIN
message := 'Hello, World!';
dbms_output.put_line(message);
END;
/

S.V.BAHALE 11
Concept Explanation- Examples
Examples :
 BEGIN
dbms_output.put_line(‘Hello&a’);
END;
/
Enter value for a: Everyone
Hello Everyone
 DECLARE
X branch_details.fees%type;
BEGIN
Select fees into X from branch_details where branch_code=‘CO’;
dbms_output.put_line(X);
END;
/

S.V.BAHALE 12
Concept Explanation- Examples
Examples :
DECLARE
name varchar2(20):= &str;
BEGIN
dbms_output.put_line(‘Hello’ || name);
END;
/
DECLARE
V_firstname varchar2(20);
V_sid Number := 111;
BEGIN
select studname, rollno INTO V_firstname, V_sid from student where rollno=111;
dbms_output.put_line(‘Student Name=’ || V_firstname || ‘having ID’ || v_sid);
END;
/

S.V.BAHALE 13
Concept Explanation-Pl/SQL Control Statements

PL/SQL has three categories of control statements:


• Conditional selection statements, which run different statements for different data values.
 The conditional selection statements are IF and CASE.
• 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.
• 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.

S.V.BAHALE 14
Concept Explanation-Conditional Control Statements
• 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

 IF - THEN statement :
• 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.
• Structure:
IF condition THEN
statements
END IF;

S.V.BAHALE 15
Concept Explanation-Conditional Control Statements
IF-THEN-ELSE statement :
Structure :
IF condition THEN
statement 1;
ELSE
statement 2;
END IF;

• IF statement adds the keyword ELSE followed by an alternative sequence of statement.


• If the condition is false or NULL, then only the alternative sequence of statements get executed.
Example :
DECLARE
Age number(11);
Begin
Age:=&age;
If age>18 then
dbms_output.put_line(‘u can vote’);
Else
dbms_output.put_line(‘u cannot vote’);
End if;
End;

S.V.BAHALE 16
Concept Explanation-Conditional Control Statements
IF-THEN-ELSIF statement :
• It allows you to choose between several alternatives.
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.

S.V.BAHALE 17
Concept Explanation-Conditional Control Statements
Example :
DECLARE
mark NUMBER :=55;
BEGIN
dbms_output.put_line(‘Program started.’ );
IF( mark >= 70) THEN
dbms_output.put_line(‘Grade A’);
ELSIF(mark >= 40 AND mark < 70) THEN
dbms_output.put_line(‘Grade B');
ELSIF(mark >=35 AND mark < 40) THEN
dbms_output.put_line(‘Grade C’);
END IF;
dbms_output.put_line(‘Program completed.’);
END;

 Nested IF-THEN-ELSE :
• You can use one IF-THEN or IF-THEN-ELSIF statement inside another IF-THEN or IF-THEN-ELSIF statement(s).

S.V.BAHALE 18
Concept Explanation-Conditional Control Statements
 Use of IF with SQL Table :
• Example :
Declare
a number(11);
Begin
Select salary into a from emp where name=‘ram’;
If a>1000 then
Update emp set bonus=bonus+1000 where name=‘ram’;
Else
Update emp set bonus=bonus+500 where name=‘ram’;
End if;
End;

S.V.BAHALE 19
Concept Explanation-Conditional Control Statements
 Case statement :

• The CASE statement uses a selector rather than multiple Boolean expressions. A selector is an expression,
the value of which is used to select one of several alternatives.

Syntax :
CASE selector
WHEN 'value1' THEN S1;
WHEN 'value2' THEN S2;
WHEN 'value3' THEN S3;
... ELSE Sn; -- default case
END CASE;

Example :

DECLARE grade char(1) := 'A';


BEGIN
CASE grade
when 'A' then dbms_output.put_line('Excellent');
when 'B' then dbms_output.put_line('Very good');
when 'C' then dbms_output.put_line('Well done');
when 'D' then dbms_output.put_line('You passed');
when 'F' then dbms_output.put_line('Better try again');
else dbms_output.put_line('No such grade');
END CASE;
END;

S.V.BAHALE 20
Concept Explanation-Loop Statements
• 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 −
1) SIMPLE LOOP
2) WHILE LOOP
3) FOR LOOP

PL/SQL Basic LOOP :


• In this loop structure, sequence of statements is enclosed between the LOOP and the END LOOP statements.
• At each iteration, the sequence of statements is executed and then control resumes at the top of the loop.

Structure :
LOOP
Statement 1;
Statement 2;
Exit condition
End loop;

S.V.BAHALE 21
Concept Explanation-Loop Statements
 PL/SQL WHILE LOOP :
• Repeats a statement or group of statements while a given condition is true.
• It tests the condition before executing the loop body.
• If the condition is true, the statements run and control returns to the top of the loop,
where condition is evaluated again.
• If the condition is not true, control transfers to the statement after the WHILE LOOP statement.
Structure :
[ label ] WHILE condition LOOP
statements
END LOOP [ label ];

 PRINT NUMBERS FROM 1 TO 10 USING WHILE LOOP


Declare
i number(3):=0;
Begin
While i<=10 loop
i:=i+1;
dbms_output.put_line(i);
End loop;
End;

S.V.BAHALE 22
Concept Explanation-Loop Statements
PL/SQL FOR LOOP :
• Execute a sequence of statements multiple times and abbreviates the code that manages the loop
variable.
• Without REVERSE, the value of index starts at lower_bound and increases by one with each iteration
of the loop until it reaches upper_bound. If lower_bound is greater than upper_bound, then
the statements never run.
• With REVERSE, the value of index starts at upper_bound and decreases by one with each iteration of
the loop until it reaches lower_bound. If upper_bound is less than lower_bound, then
the statements never run.
Structure :
[ label ] FOR index IN [ REVERSE ] lower_bound..upper_bound LOOP
statements
END LOOP [ label ];
 Print number from 1 to 10 using for loop
BEGIN
FOR i in 1 .. 10 loop
dbms_output.put_line(i);
End loop
End;
 Display even numbers between 1 to 10
Begin
For I in 1..10 loop
If (mod(I,2)=0) then
dbms_output.put_line(‘I is ‘ || to_char(I));
Enf if;
End loop; end; /
S.V.BAHALE 23
Concept Explanation-Loop Statements
PL/SQL LOOP EXIT WHEN :
• In Loop-Exit-When is terminated when the condition after the when is evaluated to TRUE.

Declare
amt number(10,2);
I number;
BEGIN
amt:=200;
I:=1;
Loop
amt:=amt + amt*0.10;
I:=I+1;
EXIT WHEN (I>14);
dbms_output.put_line(amt);
End loop;
End;

 Nested loops in PL/SQL :


You can use one or more loop inside any another basic loop, while, or for loop.

S.V.BAHALE 24
Concept Explanation-Loop Control Statements
The Loop Control Statements:
Loop control statements change execution from its normal sequence.

 EXIT statement :
The Exit statement completes the loop and control passes to the statement immediately after the
END LOOP.

 CONTINUE statement :
Causes the loop to skip the remainder of its body and immediately retest its condition prior to
reiterating.

 GOTO statement :
Transfers control to the labeled statement. Though it is not advised to use the GOTO statement in
your program.

S.V.BAHALE 25
Concept Explanation-Sequential Control Statements
GOTO Statement :
• The GOTO statement transfers control to a label unconditionally.
Syntax :
DECLARE
valid BOOLEAN := TRUE;
BEGIN
GOTO update_row;

IF valid THEN
<<update_row>>
NULL;
END IF;
END;
/

DECLARE
p VARCHAR2(30);
n PLS_INTEGER := 37;
BEGIN
FOR j in 2..ROUND(SQRT(n)) LOOP
IF n MOD j = 0 THEN
p := ' is not a prime number';
GOTO print_now;
END IF;
END LOOP;
p := ' is a prime number';
<<print_now>>
DBMS_OUTPUT.PUT_LINE(TO_CHAR(n) || p);
END;
/

S.V.BAHALE 26
Concept Explanation-Sequential Control Statements
Example:
S:=0
i:=0
<<abc>>
S:=s+I;
i:=i+1;
If i<=10 then
goto abc;
End if;

NULL Statement :
• The NULL statement only passes control to the next statement.
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 NULL;
END CASE;
END;
S.V.BAHALE 27
Concept Explanation-Exception Handling
• An exception is an error condition during a program execution.
• PL/SQL supports programmers to catch such conditions using EXCEPTION block.
• There are two types of exceptions −
1) System-defined exceptions/Predefined exceptions/Built-in exceptions
2) User-defined exception

1) Predefined exceptions-
• PL/SQL provides predefined Exception, which are executed when any database rule is violated by a
program.
• Example: NO_DATA_FOUND, ZERO_DIVIDE.

• Syntax for Predefined Exception Handling:


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 others THEN exception3-handling-statements
END;

S.V.BAHALE 28
Concept Explanation-Exception Handling
Example :
DECLARE
A number:=20;
B number:=0;
C number;
BEGIN
dbms_output.put_line(‘First Num : ’||A);
dbms_output.put_line(‘Second Num : ’||B);
C:= A / B;
--Raise built in Exception if B is 0
dbms_output.put_line(‘ Result ’ || C);-- and then Result will not be displayed
EXCEPTION
WHEN ZERO_DIVIDE THEN
dbms_output.put_line(‘ Trying to Divide by zero :: Error ’);
END;

S.V.BAHALE 29
Concept Explanation-Predefined Exceptions
Exception name Oracle Database SQLCODE Description
error number
ACCESS_INTO_NULL ORA-06530 -6530 Program attempted to assign values to the
attributes of an uninitialized object.
CASE_NOT_FOUND ORA-06592 -6592 None of the choices in the WHEN clauses of
a CASE statement were selected and there is
no ELSE clause.
COLLECTION_IS_NULL ORA-06531 -6531 Program attempted to apply collection methods
other than EXISTS to an uninitialized nested table
or varray, or program attempted to assign values
to the elements of an uninitialized nested table or
varray.
CURSOR_ALREADY_OPENED ORA-06511 -6511 Program attempted to open an already opened
cursor.
DUP_VAL_ON_INDEX ORA-00001 -1 Program attempted to insert duplicate values in a
column that is constrained by a unique index.
INVALID_CURSOR ORA-01001 -1001 There is an illegal cursor operation.
INVALID_NUMBER ORA-01722 -1722 Conversion of character string to number failed.
NO_DATA_FOUND ORA-01403 +100 Single row SELECT returned no rows or your
program referenced a deleted element in a nested
table or an uninitialized element in an associative
array (index-by table).
PROGRAM_ERROR ORA-06501 -6501
S.V.BAHALE PL/SQL has an internal problem. 5
Concept Explanation-Predefined Exceptions
Exception name Oracle Database SQLCODE Description
error number
ROWTYPE_MISMATCH ORA-06504 -6504 Host cursor variable and PL/SQL cursor variable
involved in an assignment statement have
incompatible return types.
STORAGE_ERROR ORA-06500 -6500 PL/SQL ran out of memory or memory was
corrupted.
SUBSCRIPT_BEYOND_COUNT ORA-06533 -6533 A program referenced a nested table or varray
using an index number larger than the number of
elements in the collection.
SUBSCRIPT_OUTSIDE_LIMIT ORA-06532 -6532 A program referenced a nested table or varray
element using an index number that is outside the
legal range (for example, -1).
SYS_INVALID_ROWID ORA-01410 -1410 The conversion of a character string into a
universal rowid failed because the character string
does not represent a ROWID value.
TOO_MANY_ROWS ORA-01422 -1422 Single row SELECT returned multiple rows.
VALUE_ERROR ORA-06502 -6502 An arithmetic, conversion, truncation, or size
constraint error occurred.
ZERO_DIVIDE ORA-01476 -1476 A program attempted to divide a number by zero.

S.V.BAHALE 31
Concept Explanation-Exception Handling
2) User defined Exceptions:
• PL/SQL allow us to define our own exception according to the need of our program.
• A user defined exception must be declared and then raised explicitly.
• Syntax for User defined Exception:
DECLARE exception_name EXCEPTION;
BEGIN IF condition THEN RAISE exception_name;
END IF;
EXCEPTION WHEN exception_name THEN statement;
END;

Raising Exceptions :
• Exceptions are raised by the database server automatically whenever there is any internal database error.
• Exceptions can be raised explicitly by the programmer by using the command RAISE.
Syntax:
DECLARE
exception_name EXCEPTION; BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;

S.V.BAHALE 32
Concept Explanation-Exception Handling

Example :
Write a PL/SQL program which accepts the customer_ID from the user. If the enters an invalid ID then
the exception invalid_id is raised using exception handling.

DECLARE
c_id numeric(10);
invalid_id_Exception Exception;
BEGIN
c_id:=&c_id;
if(c_id<0) then
raise invalid_id_Exception;
end if;
EXCEPTION
WHEN invalid_id_Exception THEN
dbms_output.put_line('Invalid customer id');
END;

S.V.BAHALE 33
Concept Explanation-Cursor
• A cursor is a temporary work area created in system memory when an SQL statement is executed.
• A cursor is a set of rows together with a pointer that identifies a current row.
• It is a database object to retrieve data from result set on row at a time.
• A cursor can hold more than one row, but can process only one row at a time.
• There are two types of cursor −
1) Implicit
2) Explicit

Implicit cursor:
• This type of cursors are generated and used by the system during the manipulation of a DML query.
• An implicit cursor is also generated by the system when a single row is selected by a SELECT command.

Explicit cursor:
• This type of cursor is created by the user when the select command returns more than one row, and
only one row is to be processed at a time.
• To create an explicit cursor the following steps are used.
1. Declare cursor: In this part we declare variables and return a set of values
2. Open: This step is done before the cursor is used to fetch the records.
3. Fetch: Used to retrieve data row by row from the cursor.
4. Close: Once the processing of the data is done, the cursor can be closed.

S.V.BAHALE 34
Concept Explanation-Cursor
Declaring:
This term is used to declare a cursor so that memory initialization will take place.
A cursor is declared by defining the SQL statement that returns a result set.
Example:
1)Declare CURSOR c1 IS SELECT roll_no, std_name, percentage FROM
student;
2) Cursor c1(code number) is select * from branch where brcode=code;

Opening: A Cursor is opened and populates data by executing the SQL statement defined by the cursor.
Example:
Open c1;

Closing a Cursor: This forces cursor for releasing the allocated memory assigned/occupied by cursor.
Example:
CLOSE c1;

S.V.BAHALE 35
Concept Explanation-Cursor
Attributes :
Cursor attributes provide current information about cursor.
Each cursor has four attributes, %FOUND, %ISOPEN, %NOTFOUND, %ROWCOUNT.
Syntax:
Cursorname%attribute
e.g. c1%FOUND

The %FOUND Attribute:


This attribute provides information about recent fetch operation , if fetch operation returns rows it returns
TRUE otherwise FALSE. It returns TRUE if INSERT, UPDATE, DELETE and SELECT statement affects at least one
row.

The %NOTFOUND Attribute:


The %NOTFOUND attribute returns FALSE when fetch operation returns rows and TRUE if no rows returns.
The %ISOPEN Attribute:
The %ISOPEN attribute returns true if the cursor is open otherwise it returns FALSE.
The %ROWCOUNT attribute :
The %ROWCOUNT attribute provides the number of rows which are currently fetched from the cursor.
When cursor is open %ROWCOUNT is equal to zero.

S.V.BAHALE 36
Concept Explanation-Cursor
Example :

declare
e_rec emp2%rowtype;
cursor cc is select * from emp2;
Begin
open cc;
Loop
Fetch cc into e_rec;
dbms_output.put_line('Number= '|| e_rec.empno);
dbms_output.put_line('Name ='|| e_rec.ename);
dbms_output.put_line('Salary='|| e_rec.salary);

Exit when cc%NOTFOUND;


End loop;
close cc;
End;
/
S.V.BAHALE 37
Concept Explanation-Cursor
Example :

Declare
Cursor c1 is select * from emp where branch=‘CO’;
Begin
For result in c1
Loop
Exit when c1%NOTFOUND;
If result.sal>50000 then
dbms_output.put_line(result.sal ||’ ‘ ||result.ename);
End if;
End loop;
End;
/

S.V.BAHALE 38
Concept Explanation-Cursor
Example :

Declare
enum emp.eno%type;
en emp.ename%type;
Cursor cur is select eno, ename from emp where jobname = “mgr”;
Begin
Open cur;
Loop Fetch cur into enum, en;
Exit when cur%NOTFOUND;
Dbms_output.put_line(„emp num ‟||enum||‟ emp name „||en);
End loop;
Close cur;
End;
/

S.V.BAHALE 39
Concept Explanation-Procedure
 A subprogram is a program unit/module that performs a particular task.
 It is created with the CREATE PROCEDURE or the CREATE FUNCTION statement.
 PL/SQL provides two kinds of subprograms −
 Procedures − These subprograms do not return a value directly; mainly used to perform an action.
 Functions − These subprograms return a single value; mainly used to compute and return a value.

Benefits of procedure and Function :


1. Modularity
Subprograms let you break a program into manageable, well-defined modules.
2. Easier Application Design
When designing an application, you can defer the implementation details of the subprograms until
you have tested the main program, and then refine them one step at a time.
3. Maintainability
You can change the implementation details of a subprogram without changing its invokers.
4. Packageability
Subprograms can be grouped into packages.
5. Reusability
Any number of applications, in many different environments, can use the same package
subprogram or standalone subprogram.
6. Better Performance
Each subprogram is compiled and stored in executable form, which can be invoked repeatedly.

S.V.BAHALE 40
Concept Explanation-Procedure
Creating a Procedure :
A procedure is created with the CREATE OR REPLACE PROCEDURE statement.
Syntax:
CREATE [OR REPLACE] PROCEDURE procedure_name [(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS} BEGIN < procedure_body > END procedure_name;

procedure-name specifies the name of the procedure.


[OR REPLACE] option allows the modification of an existing procedure.
The optional parameter list contains name, mode and types of the parameters.
IN represents the value that will be passed from outside and OUT represents the parameter that will be
used to return a value outside of the procedure.
procedure-body contains the executable part.
The AS keyword is used instead of the IS keyword for creating a standalone procedure.

 A procedure has two parts , specification and body.


• Specification consists of the name of the procedure and parameter declaration. Parameter
declaration should be unconstrained.
• The body of a procedure consists of local declarations ,the executable part and the exception
handling part.

S.V.BAHALE 41
Concept Explanation-Procedure
Example :
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN dbms_output.put_line('Hello World!');
END;
/

Executing a Standalone Procedure :


A standalone procedure can be called in two ways −
•Using the EXECUTE keyword

EXECUTE[EXEC] greetings;

• The procedure can also be called from another PL/SQL block −


BEGIN
greetings;
END; /

Deleting a Standalone Procedure :

A standalone procedure is deleted with the DROP PROCEDURE statement.


Syntax :
DROP PROCEDURE procedure-name;
Example :
DROP PROCEDURE greetings;

S.V.BAHALE 42
Concept Explanation-Procedure

Example:
1)
Create or replace procedure p1(id IN emp.eid%TYPE)
IS
BEGIN
Update emp
Set sal=sal+1000
Where eid=id;
END p1;

2)
Create or replace procedure p1(id IN emp.eid%TYPE, name OUT emp.ename%TYPE, sal1 INOUT emp.sal%TYPE)
IS
BEGIN
Select ename, sal into name, sal1 from emp
Where eid=id and sal1>5000;
END p1;

S.V.BAHALE 44
Concept Explanation-Procedure
 This program finds the minimum of two values.

DECLARE a number; b number; c number;


PROCEDURE findMin(x IN number, y IN number, z OUT number)
IS
BEGIN
IF x < y
THEN z:= x;
ELSE z:= y;
END IF;
END;

BEGIN
a:= 23;
b:= 45;
findMin(a, b, c);
dbms_output.put_line(' Minimum of (23, 45) : ' || c);
END;
/

S.V.BAHALE 45
Concept Explanation-Procedure
 This procedure computes the square of value of a passed value.

DECLARE
a number;
PROCEDURE squareNum(x IN OUT number)
IS
BEGIN x := x * x;
END;

BEGIN
a:= 23;
squareNum(a);
dbms_output.put_line(' Square of (23): ' || a);
END;
/

S.V.BAHALE 46
Concept Explanation-Function
Creating a Function :
A standalone function is created using the CREATE FUNCTION statement. T

Syntax :
CREATE [OR REPLACE] FUNCTION function_name [(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 the modification of an existing function.
• The optional parameter list contains name, mode and types of the parameters.
• IN represents the value that will be passed from outside and OUT represents the parameter that will be
used to return a value outside of the procedure.
• The function must contain a return statement.
• The RETURN clause specifies the data type you are going to return from the function.
• function-body contains the executable part.
• The AS keyword is used instead of the IS keyword for creating a standalone function.

S.V.BAHALE 47
Concept Explanation-Function
 A function has two parts , specification and body.
• Specification consists of the name of the function, parameter declaration and return data type.
• The body of a function consists of local declarations ,the executable part which contains PL/SQL
executable statements and one or more return statements with an expression.
• The expression should return value mentioned in the return data type.
• The exception handling part is used for writing exceptions.

 Advantages:
• Maintainability: stored at one location so updates becomes easier.
• Testing: Functions can tested independently of any other application.
• Security : Limits direct access to tables. It is secure since the code stays inside the database thus
hiding internal database details from the application(user). The user only makes a call to the
PL/SQL functions. Hence security and data hiding is ensured.
• Improves Performance : 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.
• Greater readability :We can divide the overall work into small modules which becomes quite
manageable also enhancing the readability of the code.
• It promotes reusability.

S.V.BAHALE 48
Concept Explanation-Function
Example :
CREATE OR REPLACE FUNCTION totalemployees
RETURN number IS
total number(2) := 0;
BEGIN
SELECT count(*) into total FROM emp;
RETURN total;
END;
/
Calling a Function:
• When a program calls a function, the program control is transferred to the called function.
• A called function performs the defined task and when its return statement is executed or when the last end
statement is reached, it returns the program control back to the main program.
• A function can be executed as a part of a SELECT statement :SELECT totalemployees FROM dual;
• In a PL/SQL Statements like, : dbms_output.put_line(totalemployees);

DECLARE c number(2);
BEGIN c := totalemployees ();
dbms_output.put_line('Total no. of Customers: ' || c);
END;
/
Dropping a Function:
The DROP FUNCTION statement drops a standalone function from the database.

DROP FUNCTION totalemployees ;

S.V.BAHALE 49
Concept Explanation-Function
Example:
create FUNCTION findMax(x IN number, y IN number)
RETURN number
IS z number;
BEGIN
IF x > y
THEN
z:= x;
ELSE
z:= y;
END IF;
RETURN z;
END;
-
DECLARE
a number;
b number;
c number;
BEGIN
a:= 23;
b:= 45;
c := findMax(a, b);
dbms_output.put_line(' Maximum of (23,45): ' || c);
END;
/

S.V.BAHALE 51
Concept Explanation-Function
 PL/SQL Recursive Functions

DECLARE
num number;
factorial number;

FUNCTION fact(x number)


RETURN number
IS
f number;
BEGIN
IF x=0 THEN
f := 1;
ELSE
f := x * fact(x-1);
END IF;
RETURN f;
END;

BEGIN
num:= 6;
factorial := fact(num);
dbms_output.put_line(' Factorial '|| num || ' is ' ||
factorial);
END;
/

S.V.BAHALE 52
Concept Explanation-Function

Example:
create or replace function getsal (no IN number)
return number
is sal number(5);
begin
select salary into sal from emp where id=no;
return sal;
end;
/

S.V.BAHALE 53
Concept Explanation-Function

Procedures VS Functions:
Function Procedure

A function MUST return a value A procedure cannot return a value

Functions can be called from SQL procedure cannot

Functions are considered expressions procedure are not

S.V.BAHALE 54
Concept Explanation-Trigger
• Triggers are stored programs, which are automatically executed or fired when some event occurs..
DML triggers run when a user tries to modify data through a data manipulation language (DML) event.
• DML events are INSERT, UPDATE, or DELETE statements on a table or view.
• DDL statements (CREATE or ALTER primarily) issued either by a particular schema/user or by any
schema/user in the database
• Database events, such as logon/logoff, errors, or startup/shutdown, also issued either by a particular
schema/user or by any schema/user in the database

A trigger has three basic parts:


• A triggering event or statement
• A trigger restriction
• A trigger action
Trigger Restriction
• A trigger restriction specifies a Boolean expression that must be true for the trigger to fire.
• The trigger action is not run if the trigger restriction evaluates to false or unknown.
Trigger Action
• A trigger action is the procedure (PL/SQL block, Java program, or C callout) that contains the SQL
statements and code to be run when the following events occur:
• A triggering statement is issued.
• The trigger restriction evaluates to true.
Like stored procedures, a trigger action can:
• Contain SQL, PL/SQL, or Java statements
• Define PL/SQL language constructs such as variables, constants, cursors, exceptions
• Define Java language constructs
• Call stored procedures

S.V.BAHALE 55
Concept Explanation-Trigger
Types of Triggers :
1. Row Level Triggers
2. Statement Level Triggers
3. Before Triggers
4. After Triggers

 Row Level Triggers :


Row level triggers execute once for each row in a transaction.
If the triggering statement affects no rows, the trigger is not executed at all.
Row level triggers are created using the FOR EACH ROW clause in the CREATE TRIGGER command.

 Statement Level Triggers :


Statement level triggers are triggered only once for each transaction.
For example when an UPDATE command update 15 rows, the commands contained in the trigger are
executed only once, and not with every processed row.
Statement level trigger are the default types of trigger created via the CREATE TRIGGER command.

 Before Trigger :
Since triggers are executed by events, they may be set to occur immediately before or after those
events.
BEFORE trigger execute the trigger action before the triggering statement.

 After Trigger :
AFTER trigger executes the trigger action after the triggering statement is executed.
AFTER triggers are used when you want the triggering statement to complete before executing the
trigger action.
S.V.BAHALE 56
Concept Explanation-Trigger
Four types of row and statement triggers:

 BEFORE statement trigger


Before executing the triggering statement, the trigger action is run.

 BEFORE row trigger


Before modifying each row affected by the triggering statement and before checking appropriate integrity
constraints, the trigger action is run, if the trigger restriction was not violated.

 AFTER statement trigger


After executing the triggering statement and applying any deferred integrity constraints, the trigger
action is run.

 AFTER row trigger


After modifying each row affected by the triggering statement and possibly applying appropriate integrity
constraints, the trigger action is run for the current row provided the trigger restriction was not violated.
Unlike BEFORE row triggers, AFTER row triggers lock rows.

S.V.BAHALE 57
Concept Explanation-Trigger
Advantages of Triggers :
• Trigger generates some derived column values automatically.
• Enforces referential integrity.
• Event logging and storing information on table access.
• Auditing
• Synchronous replication of tables.
• Imposing security authorizations.
• Preventing invalid transactions.

S.V.BAHALE 58
Concept Explanation-Trigger
Creating Triggers :
syntax :
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE} [OF col_name] ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE Declaration-statements
BEGIN Executable-statements
EXCEPTION Exception-handling-statements
END;

• CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing trigger with
the trigger_name.
• {BEFORE | AFTER | INSTEAD OF- − This specifies when the trigger will be executed. The INSTEAD OF
clause is used for creating trigger on a view.
• ,INSERT *OR+ | UPDATE *OR+ | DELETE- − This specifies the DML operation.
• [OF col_name+ − This specifies the column name that will be updated.
• [ON table_name+ − This specifies the name of the table associated with the trigger.
• *REFERENCING OLD AS o NEW AS n+ − This allows you to refer new and old values for various DML
statements, such as INSERT, UPDATE, and DELETE.
• *FOR EACH ROW+ − This specifies a row-level trigger, i.e., the trigger will be executed for each row being
affected. Otherwise the trigger will execute just once when the SQL statement is executed, which is called
a table level trigger.
• WHEN (condition) − This provides a condition for rows for which the trigger would fire. This clause is valid
only for row-level triggers.
S.V.BAHALE 59
Concept Explanation-Trigger
Example:
Create or replace Trigger np before insert on account for each row
Begin
IF :NEW.bal < 0 THEN
DBMS_OUTPUT.PUT_LINE('BALANCE IS NAGATIVE..');
END IF;
End;
/

S.V.BAHALE 60
Concept Explanation-Trigger
Example:
CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON employees
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;
/
OR
create or replace trigger tr1
before insert or update or delete on emp for each row
begin
:new.sal:=:new.sal-:old.sal;
raise_application_error(-20015,'sal='||:new.sal);
end;

S.V.BAHALE 61
Concept Explanation-Trigger
Triggering a Trigger:
Let us perform some DML operations on the Employee table.
1)The INSERT statement will insert a new record in the table −

INSERT INTO employees(ID,NAME,AGE,ADDRESS,SALARY) VALUES (7, 'Kriti', 22, 'HP', 7500.00 );

When a record is created in the Employee s table, the trigger, display_salary_changes will be fired.
Result :
Old salary:
New salary: 7500
Salary difference:

2)The UPDATE statement will update an existing record in the table −

UPDATE employees
SET salary = salary + 500
WHERE id = 2;
Result :
Old salary: 1500
New salary: 2000
Salary difference: 500

S.V.BAHALE 62
Concept Explanation-Trigger
Dropping Triggers :
Triggers may be dropped via the drop trigger command.

Syntax:
DROP TRIGGER trigger_name;

S.V.BAHALE 63

You might also like