Unit-4 Dbmsupdated
Unit-4 Dbmsupdated
INTRODUCTION TO PL/SQL
Though SQL is the natural language of the DBA, it
suffers from various inherent disadvantages, when used as
a conventional programming language.
1. SQL does not have any procedural capabilities i.e.
SQL does not provide the programming techniques of
condition checking, looping and branching that is vital
for data testing before its permanent storage.
2. SQL statements are passed to the Oracle Engine one
at a time. Each time an SQL statement is executed, a
call is made to the engine's resources. This adds to the
traffic on the network, thereby decreasing the speed of
data processing, especially in a multi-user
environment.
3. While processing an SQL sentence if an error occurs,
the Oracle engine displays its own error messages.
SQL has no facility for programmed handling of errors
that arise during the manipulation of data.
As the name suggests, PL/SQL is a superset of SQL.
PL/SQL is a block-structured language that enables
developers to combine the power of SQL with procedural
statements. PL/SQL bridges the gap between database
technology and procedural programming languages.
ADVANTAGES OF PL/SQL:
1. PL/SQL is development tool that not only supports
SQL data manipulation but also provides facilities of
conditional checking, branching and looping.
2. PL/SQL sends an entire block of SQL statements to
the Oracle engine all in one go. Communication
between the program block and the Oracle engine
reduces considerably, reducing network traffic. Since
the Oracle engine got the SQL statements as a single
block, it processes this code much faster than if it got
the code one sentence at a time. There is a definite
improvement in the performance time of the Oracle
engine. As an entire block of SQL code is passed to the
Oracle engine at one time for execution, all changes
made to the data in the table are done or undone, in
one go.
3. PL/SQL also permits dealing with errors as required,
and facilitates displaying user-friendly messages, when
errors are encountered.
1
Unit 4 DBMS II BCA
2
Unit 4 DBMS II BCA
Exception Section:
This section deals with handling of errors that arise
during execution of the data manipulation statements,
which make up the PL/SQL code block. Errors can arise
due to syntax, logic and/or validation rule violation.
3
Unit 4 DBMS II BCA
PLlSQL
The Character Set:
The basic character set includes the following:
Literals:
A literal is a numeric value or a character string used
to represent itself.
Numeric Literal:
These can be either integers or floats. If a float is being
represented, then the integer part must be separated from
the float part by a period.
String Literal:
These are represented by one or more legal characters
and must be enclosed within single quotes. The single quote
character can be represented, by writing it twice in a string
literal. This is definitely not the same as a double quote.
Character Literal:
These are string literals consisting of single characters.
4
Unit 4 DBMS II BCA
5
Unit 4 DBMS II BCA
Logical Comparisons:
PL/SQL supports the comparison between variables
and constants in SQL and PL/SQL statements. These
comparisons, often called Boolean expressions, generally
consist of simple expressions separated by relational
operators (<, >, =, <>, >=, <=) that can be connected by
logical operators (AND, OR, NOT). A Boolean expression will
always evaluate to TRUE, FALSE or NULL.
6
Unit 4 DBMS II BCA
CONTROL STRUCTURE:
The flow of control statements can be classified into the
following categories:
Conditional Control
Iterative Control
Sequential Control
Conditional Control:
PL/SQL allows the use of an IF statement to control the
execution of a block of code. In PL/SQL, the IF - THEN -
ELSIF - ELSE - END IF construct in code blocks allow
specifying certain conditions under which a specific block of
code should be executed.
Example:
PL\SQL program to check the given number is odd or
even.
declare
num number(2);
begin
num:=&EnterNumber;
if num mod 2 =0 then
dbms_output.put_line(‘ Given number is even’);
else
dbms_output.put_line(‘Given number is odd’);
end if;
end;
7
Unit 4 DBMS II BCA
output:
SQL>/
EnterNumber:4
Given number is even
Procedure successfully complted.
Iterative Control:
Iterative control indicates the ability to repeat or skip
sections of a code block. A loop marks a sequence of
statements that has to be repeated. The keyword loop has to
be placed before the first statement in the sequence of
statements to be repeated, while the keyword end loop is
placed immediately after the last statement in the sequence.
Once a loop begins to execute, it will go on forever. Hence a
conditional statement that controls the number of times a
loop is executed always accompanies loops. PL/SQL
supports the following structures for iterative control:
Simple Loop:
In simple loop, the key word loop should be placed before
the first statement in the sequence and the keyword end
loop should be written at the end of the sequence to end the
loop.
loop
exit when i>num;
dbms_output.put_line(i);
i:=i+1;
end loop;
end;
Output:
8
Unit 4 DBMS II BCA
SQL>/
EnterNumber:5
1
2
3
4
5
Procedure successfully completed.
9
Unit 4 DBMS II BCA
Example1:
PL/SQL program to display the first N natural numbers
using for loop.
declare
num number(2);
i number(2);
begin
num:=&EnterNumber;
for i in 1..num
loop
dbms_output.put_line(i);
end loop;
end;
Output:
SQL>/
EnterNumber:5
1
2
3
4
5
10
Unit 4 DBMS II BCA
Output:
SQL>/
EnterNumber:5
5
4
3
3
1
Sequential Control
The GOTO Statement:
The GOTO statement changes the flow of control
within a PL/SQL block. This statement allows execution of a
section of code, which is not in the normal flow of control.
The entry point into such a block of code is marked using
the tags <<user-defined name>>. The GOTO statement can
then make use of this user-defined name to jump into that
block of code for execution.
Example:
Declare
PL/SQL TRANSACTIONS
ORACLE TRANSACTIONS:
A series of one or more SQL statements that are
logically related or a series of operations performed on
Oracle table data is termed as a Transaction. Oracle treats
this logical unit as a single entity. Oracle treats changes to
table data as a two-step process.
A COMMIT statement given at the SQL prompt can be
used to make the changes permanent.
A ROLLBACK statement given at the SQL prompt can
be used to undo a part of or the entire transaction.
A transaction is a group of events that occur between any of
the following events:
o Connecting to Oracle
o Disconnecting from Oracle
o Committing changes to the database table
o Rollback
11
Unit 4 DBMS II BCA
Closing Transactions:
A transaction can be closed by using either a commit
or a rollback statement. By using these statements, table
data can be changed or all the changes made to the table
data undone.
Using COMMIT:
A COMMIT ends the current transaction and makes
permanent any changes made during the transaction. All
transactional locks acquired on tables are released.
Using ROLLBACK:
A ROLLBACK does exactly the opposite of COMMIT. It
ends the transaction but undoes any changes made during
the transaction. All transactional locks acquired on tables
are released.
Creating A SAVEPOINT:
SAVEPOINT marks and saves the current point in the
processing of a transaction. When a SAVEPOINT is used
with a ROLLBACK statement, parts of a transaction can be
undone. An active SAVEPOINT is one that is specified since
the last COMMIT or ROLLBACK.
12
Unit 4 DBMS II BCA
WHAT IS A CURSOR?
The Oracle Engine uses a work area for its internal
processing in order to execute an SQL statement. This
work area is private to SQL's operations and is called a
Cursor. The data that is stored in the cursor is called the
Active Data Set. Conceptually, the size of the cursor in
memory is the size required to hold the number of rows in
the Active Data Set.
13
Unit 4 DBMS II BCA
Types of Cursors:
Cursors are classified depending on the circumstances
under which they are opened.
1. If the Oracle engine opened a cursor for its internal
processing it is known as an Implicit Cursor.
2. A cursor can also be opened for processing data
through a PL/SQL block, on demand. Such a user-
defined cursor is known as an Explicit Cursor.
Implicit Cursor:
The Oracle engine implicitly opens a cursor on the
Server to process each SQL statement. Since the implicit
cursor is opened and managed by the Oracle engine
internally, the function of reserving an area in memory,
populating this area with appropriate data, processing the
data in the memory area, releasing the memory area when
the processing is complete is taken care of by the Oracle
engine. The resultant data is then passed to the client
machine via the network. A cursor is then opened in
memory on the client machine to hold the rows returned by
the Oracle engine. The number of rows held in the cursor on
the client is managed by the client's operating system and
it's swap area.
14
Unit 4 DBMS II BCA
Example4:
The bank manager has decided to transfer employees across branches. Write
a PL/SQL block to accept anemployee number and the branch number
followed by updating the branch number of that employee towhich he belongs
appropriately. Display an appropriate message using SQL%FOUND based on
theexistence of the record in the EMP_MSTR table. Display an appropriate
message usingSQL%NOTFOUND based on the non-existence of the record
in the EMP_MSTR table.
BEGIN
UPDATE EMP MSTR SET BRANCH NO = &BRANCH _NO WHERE
EMP_N0&EMP NO;
IF SQL%FOUND THEN
dbms_output.put_line(Employee Successfully Transferred);
END IF;
IF SQL%NOTFOUND THEN
dbms_output.put_line('Employee Number does not Exist);
END IF;
END;
Output:
Enter value for branch no: 'B4'
old 2: UPDATE EMP_MSTR SET BRANCH_NO= &BRANCH NO
new 2: UPDATE EMP MSTR SET BRANCH NO = 'B4'
Enter value for emp no: 'E1'
old 3 WHERE EMP NO = &EMP NO;
new 3: WHERE EMP NO = 'E1';
Employee Successfully Trans ferred
PL/SQL procedure successfully completed.
15
Unit 4 DBMS II BCA
Example 5:
For SQL%ROWCOUNT
The bank manager of Darya Ganj branch decides to activate all those
accounts, which were previously
marked as inactive for performing no transactions in last 365 days. Write a
PL/sQL block to update the
status of accounts. Display an appropriate message based on the number of
rows affected by the update
fired.
DECLARRE
Rows_Affected char(4);
BĘGIN
UPDATE ACCT_MSTR SET STATUS = 'A' WHERE STATUS = 'S' AND
BRANCH NO IN(SELECT BRANCH_NO FROM BRANCH_MSTR
WHERE NAME = "Darya Ganj);
Rows_Afected To_CHAR(SQL%ROWCOUNT);
IF SQL%ROWCOUNT> 0 THEN
dbms_output-put_line(Rows Afected || Account(s) Activated
Successfully);
ELSE
dbms_output.put_line('Currently there exist no Inactive Accounts in the
Darya Ganj Branch');
END IF;
END;
Output:
2 Account (s) Activated Successfully
PL/SQL procedure successfully completed.
Explicit Cursor:
When individual records in a table have to be
processed inside it PL/SQL code block a cursor is used.
This cursor will be declared and mapped to an SQL query in
the Declare Section of the PL/SQL block and used within its
Executable Section. A cursor thus created and used is
known as an Explicit Cursor.
16
Unit 4 DBMS II BCA
Cursor Declaration:
A cursor is defined in the declarative part of a PL/SQL
block. This is done by naming the cursor and mapping it to
a query. When a cursor is declared, the Oracle engine is
informed that a cursor of the said name needs to be opened.
The declaration is only intimation. There is no memory
allocation at this point in time. The three commands used to
control the cursor subsequently are open, fetch and close.
17
Unit 4 DBMS II BCA
The close statement disables the cursor and the active set
becomes undefined. This will release the memory occupied
by the cursor and its Data Set both on the Client and on the
Server.
18
Unit 4 DBMS II BCA
19
Unit 4 DBMS II BCA
20
Unit 4 DBMS II BCA
21
Unit 4 DBMS II BCA
22
Unit 4 DBMS II BCA
The sequence of statements inside the loop is executed once for every row
that is fetched, i.e. check ifany data is retrieved
Update the STATUS field of the ACCT_MSTR table to reflect the inactivity
Automatically repeat the above steps until the data retrieval process is
complete.
The cursor closes automatically when all the records in the cursor have been
processed. This isbecause there are no more rows left to load into
NoTrans_Rec. This situation is sensed by the FORverb which, causes the
23
Unit 4 DBMS II BCA
loop to exit.
Finally a COMMIT is fired to make the changes permanent
PARAMETERIZED CURSORS:
Commercial applications require that the query, which,
defines the cursor, be generic and the data that is retrieved
from the table be allowed to change according to need.
Oracle recognizes this and permits the creation of
parameterized cursors for use. The contents of a
parameterized cursor will constantly change depending
upon the value passed to its parameter. Since the cursor
accepts user-defined values into its parameters, thus
changing the Result set extracted, it is called as
Parameterized Cursor.
Declaring A Parameterized Cursor:
Example:
Empno Ename Dept DOJ Basic
1001 Arun Research 12-jun- 45000
1984
1002 Bhuvan Administration 01-Mar- 40000
1985
1003 Kavya Research 01-jan- 35000
1990
1004 Bharath Administration 01-jan- 35000
1990
declare
cursor e_cur(eno number) is
select basic from employee
where empno=eno;
en employee.empno%type;
bas employee.basic%type;
24
Unit 4 DBMS II BCA
begin
en:=&ENTEREMPLOYEENUMBER;
open e_cur(en);
loop
fetch e_cur into bas;
exit when e_cur%notfound;
bas:=bas+bas*0.1;
update employee
set basic=bas
where empno=en;
end loop;
close e_cur;
end;
SQL>/
ENTEREMPLOYEENUMBER:1001
Procedure successfully executed
SQL>
Select * from employee;
Empno Ename Dept DOJ Basic
1001 Arun Research 12-jun- 49500
1984
1002 Bhuvan Administration 01-Mar- 40000
1985
1003 Kavya Research 01-jan- 35000
1990
1004 Bharath Administration 01-jan- 35000
1990
25
Unit 4 DBMS II BCA
26
Unit 4 DBMS II BCA
27
Unit 4 DBMS II BCA
28
Unit 4 DBMS II BCA
Example:
29
Unit 4 DBMS II BCA
Example:
Using A Function
Example 1:
Consider the tables TRANS_MSTR and ACCT_MSTR. Both
the tables belong to the banking system.The TRANS_ MSTR
table is used to register the deposits or withdrawals, as
performed. As a batch processthe initial opening balance
value must be written to the TRANS_MSTR table whenever
an account isopened with the bank.
30
Unit 4 DBMS II BCA
BEGIN
SELECT DISTINCT ACCT_NO INTO dummyAcctNo FROM
TRANS_MSTR
WHERE ACCT_NO= vACCT_NO;
/*If the SELECT Statement retrieves data, return value is
set to1*/
RETURN 1;
EXCEPTION
/*If the SELECT statement does not retrieve data, return
value 1s
to 0 */
31
Unit 4 DBMS II BCA
DECLARE
mACCT_NO ACCT_MSTR.ACCT_N0%type;
mTYPE ACCT_MSTR.TYPE%type;
valexists NUMBER(1);
BEGIN
OPEN SCANTABLE;
LOOP
valexists :=F_CHKACCTNO(MACCT_NO);
32
Unit 4 DBMS II BCA
IF valexists = 0 THEN
IF mTYPE = 'SB' THEN
INSERT INTO TRANS_MSTR (TRANS_NO, ACCT NO,
DT, TYPE, PARTICULAR, DR_CR, AMT, BALANCE)
VALUES(SELECT T||
TO_CHAR(MAX(TO_NUMBER(SUBSTR( TRANS N
2))) + 1) FROM TRANS_MSTR), mACCT NO, SYSDATE, 'C’,
‘initial’,Payment, ‘D', 500, 500);
ELSE
INSERT INTO TRANS MSTR (TRANS_NO, ACCT_NO, DT, TYPE,
PARTICULAD
ELSE AR,DR_CR, AMT, BALANCE)
VALUES(SELECT T || TO_CHAR(MAX(TO_NUMBER(SUBSTR( TRANS No
2)) + 1) FROM TRANS_MSTR), mACCT_NO, SYSDATE, 'C', InitialPayment',
‘D', 2000, 2000);
END IF;
END IF;
END LOOP;
CLOSE SCANTABLE;
COMMIT;
END;
Output:
PL/SQL procedure success fully completed.
If the select retrieves no record (i.e. the ACCT_NO is not present in the
TRANS_MSTR table), a newrecord is inserted into the TRANS_MSTR
table.
The above process continues till all the records in the cursor,
SCANTABLE are processed. When all therecords have been processed
33
Unit 4 DBMS II BCA
the PL/SQL block exits the loop and the all the transactions
arecompletedwith the COMMIT statement.
UsingA Procedure
Example 2:
The current example deals with the Fixed Deposit Maturity system.
The tables involved with thisprocessing are FD_DTLS, TRANS _MSTR
and ACCT_MSTR.
Whenever a fixed deposit is due for payment and if there are
instructions given to the bank for crediting thefixed deposit amount
on maturity to their account held in the bank, an entry is. passed in
theTRANS MSTR table for deposit of the fixed deposit amount as well
as the ACCT_MSTR table is updatedto reflect the increase of the
current balance. Finally the status of that fixed deposits is updated as
M i.e.Matured in the FD_DTLS table.
mCurBal number;
BEGIN
34
Unit 4 DBMS II BCA
VALUES((SELECT 'T'||
TO_CHAR(MAX(TO_NUMBER(SUBSTR(TRANS_NO, 2)))+ 1)
FROM TRANS _MSTR), vACCT_NO, SYSDATE, 'C’,
'FixedDepositPayment', 'D', vAMT, (mCurBal + vAMT));
Output:
Procedure created.
Calling The Procedure In A PL/SQL Code Block:
DECLARE
/* Cursor CRSR_FDCHK retrieves all the records of table FD DTLS
which are active and due for payment */
CURSOR CRSR_FDCHK IS
SELECT FD_NO, PAYTO_ACCTNO, DUEAMT FROM FD_DTLS
WHERETO_CHAR(DUEDT,DD-MM-YY') = TO_CHAR(SYSDATE,
'DD-MM-YY)AND STATUS = 'A' AND PAYTO_ACCTNO IS NOT NULL;
mFD_NO VARCHAR2(10);
mPAYTO_ACCTNO VARCHAR2(10);
mAMT NUMBER(8,2);
mState NUMBER := 0;
BEGIN
/* Opening the cursor */
OPEN CRSR_FDCHK;
LOOP
FETCH CRSR_FDCHK INTO mFD_NO, mPAYTO_ACCTNO, MAMT;
/*Updating the state to i 1.e. there are fds due for payment */
mState: =1;
35
Unit 4 DBMS II BCA
END LOOP;
/ Display a message lr no FDS are due for pa yment based on the mState
variable */
IF mState = 0 THEN
DBMS_OUTPUT.PUT_LINE(‘Currently there are no fixed deposits due for
payment: );
END IF;
CLOSE CRSR_FDCHK;
COMMIT;
Output:
Currently there are no fixed deposits due for payment.
PL/SQL procedure successfully completed.
The status of the fixed deposit is set to M i.e. the fixed deposit is now matured
In case no records are fetched by the cursor CRSR_FDCHK a message stating
"Currently there are no fixed deposits due for payment"
36
Unit 4 DBMS II BCA
DROP PROCEDURE<ProcedureName>;
Example 3:
DROP PROCEDURE PROC_INSUPD;
Output:
Ptocedure dropped.
Syntax:
DROP FUNCTION «FunctionName
Example 4:
DROP FUNCTION F_CHKACCTNO;
Output:
Function dropped.
ORACLE PACKAGES
A package is an Oracle object, which holds other objects within it. Objects
commonly held within apackage are procedures, functions, variables,
constants, cursors and exceptions. The tool used to create apackage is SQL*
Plus. It is a way of creating generic, encapsulated, re-useable code.
Packages can contain PUSQĽ blocks of code, which have been written to
perform some přocess entirely on their own. These PL/ SQL blocks of code do
not require any kind of input from other PLSQL blocks ofcode. These are the
package's standalone subprograms.
Subprograms held within a package can be called from other stored programs,
like triggers, precompilers,or any other Interactive Oracle program like SQL*
Plus.
Note
Unlike the stored programs, the package itself cannot be called, passed
parameters to, or nested.
A package's body fully defines cursors, functions, and procedures and thus
37
Unit 4 DBMS II BCA
Package Specification
The package specification contains:
1.Name of the package
2.Names of the data types of any arguments
3.This declaration is local to the database and global to the package
Example 5:
The following is an example of package creation specification. In this example,
the specification declares a function and a procedure:
Example 6:
Sometimes a specification only declares variables, constants, and exceptions,
and therefore a package body is not necessary. The following example is a
package specification for a package that does not have a package body:
38
Unit 4 DBMS II BCA
39
Unit 4 DBMS II BCA
40
Unit 4 DBMS II BCA
41
Unit 4 DBMS II BCA
42
Unit 4 DBMS II BCA
43
Unit 4 DBMS II BCA
44
Unit 4 DBMS II BCA
Handler.
An Exception Handler is nothing but a code block in
memory that will attempt to resolve the current
exception condition. The Oracle engine can recognize every
exception conditi that occurs in memory. To
handle very common and repetitive exception conditions the
Oracle engine uses Named Exception
Handlers. The Oracle engine has about fifteen to twenty
named exception handlers. In addition to this the
Oracle engine uses more than twenty thousand numbered
exception handlers. These exception handles
are identified not by names but by four integers preceded by
a hyphen (i.e. -1414). These exception handler
names are actually a set of negative signed integers. Each
Exception Handler, irrespective of how it is
identified, (i.e. by Name or Number) has code attached that
will attempt to resolve an exception condition.
This is how Oracle's, Default Exception-Handling strategy
works.
Oracle's default exception handling code can be overridden.
When this is done Oracle's default exception
handling code is not executed but the code block that takes
care of the exception condition, in the exception
section, of the PL/ SQL block is executed. This is an
example of a programmer giving explicit exception
handling instructions to an Oracle exception handler.
This means that the Oracle engine's Exception Handler
must establish whether to execute its own exception
handling code or whether it has to execute user-defined
exception handling code.
As soon as the Oracle engine invokes an exception handler
the exception handler goes back to the PL/ SQL
block from which the exception condition was raised. The
exception handler scans the PL/ SQL block for
the existence of an Exception section within the PL/ SQL
block. If an exception section within the PL
SQL block exists the exception handler scans the first word,
after the action word When, within this
exception section.
If the first word after the action word When, is the exception
handler's name then the exception handler
executes the code contained in the Then section of the
45
Unit 4 DBMS II BCA
construct as follows:
EXCEPTION
WHEN<<ExceptionName>THEN
<<User Defined Action To Be Carried OuT>>
The first word that follows the action word When must be a
String. Hence this technique will work well forthe fifteen to
twenty named exception handlers. In addition to these the
Oracle engine has twenty
thousand, numbered exception handlers, which are raised
automatically and appropriately when the Oracleengine
recognizes exception condition. User defined exception
handling code must be permitted even forthese (numbered)
exception handlers.
Example:
PL/SQL Program using the named exception
NO_DATA_FOUND
Practical list Part B 5tH Program.
USER-Named Exception Handlers:
The technique that is used is to bind a numbered
exception handler to a name using Pragma
46
Unit 4 DBMS II BCA
Example:
User Defined Exception Handling (For Business Rule
Validations)
47
Unit 4 DBMS II BCA
Example:
Write a PL/SQL program to make a bank transaction.
Update the bank table, whenever a withdrawal operation
carried out. Display an error massage when no sufficient
balance for withdrawal. The bank table consists of following
fields: acno, name, atype, bal. Assume that account number
A0001 initially had balance amount 650.
declare
except1 exception;
ano varchar2(6);
amt number(5);
begin
ano:=’&ACCOUNTNUMBER’;
amt:=&AMOUNT;
48
Unit 4 DBMS II BCA
49