UNIT 3 Ch1 PLSQL BSC
UNIT 3 Ch1 PLSQL BSC
UNIT 3 Ch1 PLSQL BSC
CHAPTER 9
Introduction to PL/SQL
Introduction:
SQL suffers from inherent disadvantages. They are
It does not have procedural capabilities
SQL statements are passed to the oracle engine one at a time. This decreases the processing
speed in a multi-user environment
SQL has no facility of programmed handling of error messages
Q)LIST ANY TWO ADVANTAGES OF PLLSQL?2M or 5m
9.1 Advantages of PL/SQL:
PL/SQL is a development tool that not only supports SQL data manipulation but also
provides facilities for condition checking, branching and looping
PL/SQL sends the entire block of SQL code to oracle engine. As the entire block of
SQL code is passed to Oracle engine at one time for execution, all the changes made to
the data in the table are done or undone in one go.
PL/SQL facilitates the displaying of user-friendly messages when errors are encountered
PL/SQL allows declaration and use of variables in blocks of code. The variables are used to
store intermediate results of a query for later processing
PL/SQL all sorts of calculations can be done efficiently and quickly
Applications written in PL/SQL are portable to any computer hardware system and
operating system
Example:
DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END;
/
Output:
Hello, World!
Variables:
A variable in PL/SQL is a named variable. A variable name must begin with a character and
can be followed by a maximum of 29 characters. Reserved words cannot be used as variable
names unless enclosed within double quotes. A blank space cannot be embedded in a variable
name. variable names are not case sensitive. Variables are separated from each other by a comma.
Values can be assigned to variables in two ways:
1. Using the assignment operator :=
2. Selecting or fetching table data values into variables
Logical Comparisons:
Comparisons in PL/SQL can be made using Boolean expressions. A Boolean expression
consists of variables separated by relational operators{<,>,<=,>=,<>}. A logical expression is a
combination of two or more Boolean expressions separated by logical operators{AND,OR, NOT}.
A boolean expression always evaluates to TRUE, FALSE or NULL
Comments:
A comment in PL/SQL can be written in two ways:
1. It can begin with a double hyphen(--). Here, the entire line can be treated as a comment.
2. A group of lines can be enclosed between /* and */. All the lines will be ignored for
processing
Example:
a. --Single line comment
b. /* This is
a comment*/
Radius: 9.5
Circumference: 59.69
Area: 283.53
2) IF condition THEN
statement 1;
ELSE
statement 2;
END IF;
3)IF condition 1 THEN
statement 1;
statement 2;
ELSIF condtion2 THEN
statement 3;
ELSE
statement 4;
END IF;
Example:
SQL> ed samif.sql
set serveroutput on
declare
x number(2);
y number(2);
begin x:=&x;
y:=&y;
if x>y then
dbms_output.put_line (x || 'is bigger');
else
dbms_output.put_line (y || 'is bigger');
end if;
end;
Output:
Enter value for x: 35
old 5: x:=&x;
new 5: x:=35; Enter
value for y: 25 old 6:
y:=&y;
new 6: y:=25;
35is bigger
PL/SQL procedure successfully completed.
Simple Loop:
A Simple Loop is used when a set of statements is to be executed at least once before the loop
terminates. An EXIT condition must be specified in the loop, otherwise the loop will get into an
infinite number of iterations. When the EXIT condition is satisfied the process exits from the loop.
Syntax of Simple Loop:
LOOP
statements;
[EXIT WHEN condition;]
END LOOP;
These are the important steps to be followed while using Simple Loop.
1. Initialize a variable before the loop body.
2. Increment the variable in the loop.
3. Use a EXIT WHEN statement to exit from the Loop. If you use a EXIT statement without
WHEN condition, the statements in the loop is executed only once
Example:
set server
output on declare
i number:=0;
begin
dbms_output.put_line('Even numbers from 1 to 10 are:');
loop
i:= i+2;
dbms_output.put_line (i);
exit when i>=10;
end loop;
end;
Output:
Even numbers from 1 to 10 are: 2
4 6 8 10
PL/SQL procedure successfully completed.
While loop:
A WHILE LOOP is used when a set of statements has to be executed as long as a condition
is true. The condition is evaluated at the beginning of each iteration. The iteration continues until
the condition becomes false.
WHILE <condition>
LOOP
statements;
End loop;
Example:
set serveroutput on
declare
pi constant number(5,2):=3.14; r
number(2);
c number(5,2);
begin
r:=3; while
r<=7 loop
c:=2*pi*r;
insert into circle values(r,c);
r:=r+1;
end loop;
end;
Output:
SQL> @samwhile.sql;
PL/SQL procedure successfully completed.
RADIUS CIRCUM
---------- ----------
3 18.84
4 25.12
5 31.4
6 37.68
7 43.96
FOR Loop
A FOR LOOP is used to execute a set of statements for a predetermined number of times.
Iteration occurs between the start and end integer values given. The counter is always incremented
by 1. The loop exits when the counter reachs the value of the end integer.
Example:
set serveroutput on
declare
i number; n
number;
f number:=1;
begin
n:=&n;
for i in 1..n
loop f:=f*i;
end loop; dbms_output.put_line('Factorial
is '|| f);
end;
Output:
Enter value for n: 5
old 6: n:=&n; new 6:
n:=5; Factorial is 120
SAVEPOINT – It marks and saves the current point in the processing of a transaction. When a
savepoint is used with a rollback statement, parts of the transaction can be undone. An active
savepoint is one that is specified since the last COMMIT or ROLLBACK.
Syntax:
savepoint <savepointname>;
ROLLBACK – A rollback does exactly the opposite of COMMIT. It ends the transaction but
undoes any changes made during the transaction. Rollback can be fired at the SQL prompt with or
without savepoint clause.
Syntax:
rollback [work] [to [savepoint]<savepointname>];
DECLARE
a number(2) := 10;
BEGIN
<<loopstart>>
-- while loop execution
WHILE a < 20 LOOP
dbms_output.put_line ('value of a: ' || a);
a := a + 1;
IF a = 15 THEN
a := a + 1;
GOTO loopstart;
END IF;
END LOOP;
END;
/
CURSORS
10.1 Introduction:
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 operations and is called a Cursor. The data
that is stored in the cursor is called the Active Data Set. The size of the cursor in the memory is the
size required to hold the number of rows in the active data set. Oracle has a predefined area in the
main memory set aside, within which cursors are opened. . A cursor contains information on a
select statement and the rows of data accessed by it. A cursor can hold more than one row, but can
process only one row at a time
Cursors are classified depending on the circumstances under which they are opened.
Both implicit and explicit cursors have the same functionality, but they differ in the way they
are accessed
q)what is implicit cursor?
10.2 Implicit cursors
If the oracle engine opened a cursor for its internal processing, it is known as implicit
cursor. 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.
Implicit Cursor Attributes:
Attributes Return Value Example
%FOUND The return value is TRUE, if the DMLSQL%FOUND
statements like INSERT, DELETE and
UPDATE affect at least one row and if
SELECT ….INTO statement return at least one
row.
The return value is FALSE, if DML statements
like INSERT, DELETE and UPDATE do not
affect row and if SELECT….INTO statement
do not return a row.
%NOTFOUND The return value is FALSE, if DML statements SQL%NOTFOUND
like INSERT, DELETE and UPDATE at least
one row and if SELECT ….INTO statement
return at least one row.
The return value is TRUE, if a DML statement
like INSERT, DELETE and UPDATE do not
affect even one row and if SELECT ….INTO
statement does not return a row.
%ROWCOUNT Return the number of rows affected by the SQL%ROWCOUNT
DML operations INSERT, DELETE, UPDATE,
SELECT
Example: Consider the PL/SQL Block that uses implicit cursor attributes as shown below:
/*increase the salary of all employees by 1000*/
DECLARE
var_rows number(5);
BEGIN
UPDATE employ
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;
Output:
Salaries for 7employees are updated PL/SQL
procedure successfully completed.
Q)Write the functionality of OPEN,FETCH AND CLOSE Command in explicit cursor with
syntax(5m)
Functionality of Open, Fetch and Close commands:
Declaring a cursor – A cursor is declared in the declare section of the PL/SQL block. This is done
to create an active data set. The cursor name is used to reference the active data set that is held
within the cursor
Syntax:
CURSOR cursor-name IS SELECT statement;
Example:
DECLARE
CURSOR emp_cur IS
SELECT *
FROM employ
WHERE salary > 5000;
In the above example we are creating a cursor ‘emp_cur’ on a query which returns the
records of all the employees with salary greater than 5000.
Opening a cursor – Opening a cursor executes a query and creates an active data set that contains
all rows which meet the search criteria of the query. An open statement retrieves the records from
the table and places the records in the cursor
Syntax:
OPEN cursor_name;
Fetching records from the cursor – The fetch statement retrieves the rows from the active data set
into the memory variables declared in the PL/SQL block one row at a time. Each time a fetch
statement is executed, the cursor pointer is advances to the next row in the active data set.
Syntax:
FETCH cursor-name INTO variable list;
Closing a cursor – The close statement disables the cursor and the active data set becomes
undefined. This will release the memory occupied by the cursor and the active data set.
Syntax:
CLOSE cursor-name;
Example:
/*Display employee name and salary whose salary is more than 6000*/
SET SERVEROUTPUT ON
DECLARE
emp_rec employ%rowtype;
CURSOR emp_cur IS
SELECT * FROM employ
WHERE sal > 6000;
BEGIN
OPEN emp_cur;
FETCH emp_cur INTO emp_rec;
dbms_output.put_line (emp_rec.ename || ' ' || emp_rec.sal);
CLOSE emp_cur;
END;
/
Output:
SQL> @EXPCUR.SQL
Gita 7000
PL/SQL procedure successfully completed.
Example:
/*To display all employees whose salary is greater than 9000*/
SET SERVEROUTPUT ON
DECLARE
CURSOR emp_cur IS
SELECT *
FROM employ
WHERE sal > 9000;
BEGIN
for emp_rec in emp_cur
loop
dbms_output.put_line (emp_rec.ename || ' ' || emp_rec.sal);
end loop;
END;
/
Output:
Rani 10000
Ranbir 11000
PL/SQL procedure successfully completed.
5MARKS QUESTIONS
1. Explain PUSQL program structure with example.
2. What is a cursor ? Explain attributes of implicit and explicit cursor.
3. Explain any two looping statements in PUSQL with syntax and example.
4. Explain the following cursor attributes. i) %FouND ii) %NoT FoUND iii) %rsoPEN iv)
%ROWCOUNT
5. Explain the following cursor statements with syntax and example. i) Open statement ii)
Fetch statement.
6. Explain any two iterative control statemnets with example.
7. Explain with syntax and example,how to create a cursor and read the records from the
cursor.
8. Explain various forms of IF…..ENDIF statement with syntax and example.