You are on page 1of 25

Unit 4 – PL/SQL Programming

Q. What are the various datatypes of PL/SQL? 4 Marks


(Any 4 data types -1Mark each)
Ans:
The default data types that can be declared in Pl/SQL are :
1) number (size)– for storing numeric data
eg. a number(2);
2) char/ varchar(size) – for character data
eg: mynamevarchar(20);
3) date – for date and time data
eg : dob date;
4) Boolean – for storing true, false or null
eg: status Boolean;
5) %Type - to declare a variable or constant to have a same data type as that of a
previously defined variable or a column in a table.
e.g. enoemp.empno%type

Q. Describe Exception handling. Explain with example. 4 Marks

Exception Handling: Exception is nothing but an error. Exception can be raise when DBMS
encounters errors or it can be raised explicitly. When the system throws a warning or has an
error it can lead to an exception. Such exception needs to be handled and can be defined
internally or user defined. Exception handling is nothing but a code block in memory that will
attempt to resolve current error condition.
Syntax:
DECLARE
; Declaration section
…executable statement;
EXCEPTION
WHEN ex_name1 THEN

:Error handling statements/user defined action to be


carried out;

END; DECLARE
s_rollNostudents.rollNo%type :=
10; s_namestudents.name%type;
s_addressstudents.address%type;
BEGIN
SELECT rollNo, name, address FROM students WHERE rollNo =
s_rollNo; dbms_output.put_line(s_rollNo || ' ' || s_name || ' ' ||
s_address);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such
student!'); WHEN others THEN
dbms_output.put_line('Error!');
END;

Q. Write a PL/SQL program to print numbers from 50 to 60 using for loop. 4 Marks
(Note: Any other Logic also considered)
DECLARE
x number
:=50; BEGIN
LOOP
dbms_output.
put_line(x); x
:= x +1;
IF x >60 THEN
exit; END
IF; END
LOOP;
END;

Q. Explain implicit and explicit cursor. 4 Marks


Implicit Cursor:
Implicit cursors are automatically created by Oracle whenever an SQL statement is
executed, when there is no explicit cursor for the statement. Whenever a DML statement
(INSERT, UPDATE and DELETE) is issued, an implicit cursor is associated with this
statement. For INSERT operations, the cursor holds the data that needs to be inserted. For
UPDATE and DELETE operations, the cursor identifies the rows that would be affected.
In PL/SQL, implicit cursor as has the attributes like %FOUND, %ISOPEN, %NOTFOUND,
and
%ROWCOUNT.

Example of implicit cursor:


Begin
Update emp set salary= salary +500 where empno
=&empno; If SQL%FOUND then
Dbms_out.put_line(―Emp table modified‖);
Else
Dbms_out.put_line(―Emp table modified‖);
End
if;
End;
Explicit cursor:
Explicit cursors are programmer defined cursors for gaining more control over the context
area. An explicit cursor should be defined in the declaration section of the PL/SQL Block. It is
created on a SELECT Statement which returns more than one row.
Working with an explicit cursor involves four
steps: Declaring the cursor for initializing in the
memory Cursor cursor_name IS select_statement;
Opening the cursor for allocating memory
Open cursorname;
Fetching the cursor for retrieving data
Fetch cursorname INTO variable1,variable2…
Closing the cursor to release allocated memory
Close cursorname;

Example of explicit cursor:


Declare
Cursor c1 is select empno, salary from emp Where deptno=10;
ecode emp.empno%Type;
sal emp.salary%Type;
Begin
Open c1;
If c1%ISOPEN then
Loop
Fetch c1 into ecode,sal;
If c1% NOTFOUND then Exit;
End if;
Update emp set salary = salary+500;
End Loop;
Close c1;
Else dbms_out.put_line(―unable to open‖);
End if;
End;

Q. Explain the concept of trigger. 4 Marks


A trigger is a PL/SQL block structure which is fired when DML statements like Insert, Delete,
Update is executed on a database table.
A trigger is triggered automatically when an associated DML statement is executed.
Syntax for Creating a Trigger:
CREATE OR REPLACE TRIGGER trigger_name
[BEFORE/AFTER]
[INSERT/UPDATE/DELETE]
ON Table_name [FOR EACH STATEMENT/FOR EACH ROW]
[WHEN CONDITION]
PL/SQL block

Example:
CREATE OR REPLACE TRIGGER trg1
BEFORE INSERT ON EMP
FOR EACH ROW
BEGIN
IF :new.sal<=0 THEN
Rasie_application_error(„Salary should be greater than 0‟);
END IF;
END;

Q. Define following term with example. 4 Marks


(i) Procedure
(ii) Function
(i) Procedure:
Definition: A procedure is named PL/SQL block which perform one or more specifies task.
Example
The following example creates a simple procedure that displays the string 'Hello World!' on the
screen when executed.
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;
(ii) Function:
Definition: Function is a logically grouped set of SQL and Pl/SQL statements that perform a
specific task.
Example:
This function returns the total number of CUSTOMERS in the customers table.
CREATE OR REPLACE FUNCTION totalCustomers
RETURN number IS
total number(2):=0;
BEGIN
SELECT count(*)into total
FROM customers;
RETURN total;
END;
/

Q. Explain GOTO statement with example. 4 Marks


The GOTO statement transfers control to a labelled block or statement.
It is an unconditional branching statement.
It does not use any condition for transferring the control to other part of code.
It transfers the control to the part of code which contains same label mentioned in goto
statement.
Syntax :
GOTO label;
..
..
<< label >>
statement;

Example :
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;
Q.Explain PL/SQL block structure. 4 Marks
Block structure of PL/SQL:
Declare
Declaration of memory variables
BEGIN (Mandatory)
SQL executable statements
Exception Handling
errors END;
(Mandatory)

A block begins with a declarative section where variables are declared. This is followed by a
section containing the procedural statements surrounded by BEGIN and END keywords. Each
block must have Begin and End statements and may optionally include an exception section to
handle errors. End section marks the end of PLSQL block.

Q.Give any four advantages of using PL/SQL. 4 Marks


(Any four advantages - 1 mark each)
Advantages of PL/SQL:
1. PL/SQL is portable and high transaction processing language.
2. PL/SQL is in fact procedural language but it also supports object oriented programming.
3. PL/SQL is that development tool which not only supports SQL data manipulations but also
provides facilities of conditional checking and looping.
4. It allows user to write as well as access the functions and procedures from outside the programs.
5. It has got built in libraries of packages.
6. PL/SQL is highly productive as it works with the oracle forms to develop the application software
i.e. it works with the front ends to develop the complete commercial applications.
7. The performance of PL/SQL is better, as in single line query entire block of statements can be
processed.
8. Some special features of PL/SQL include the different data types that are capable of handling
different types of data required in real life applications.
9. The most important features like triggers, cursors, locks etc have made PL/SQL a very versatile
language.
10. Security can be ensured with the help of PL/SQL, while developing a commercial database
system.
11. PL/SQL is a user friendly language and very simple to use.
Q. What are Predefined exceptions and User defined exceptions? 4 Marks
(Predefined exception - 2 marks; User Defined exception - 2 marks)

1) Predefined Exception/system defined exception/named exception:


Are always automatically raised whenever related error occurs. The most common errors that can
occurs during the execution of PL/SQL. Not declared explicitly. I.e. cursor already open, invalid
cursor, no data found, zero divide and too many rows etc. Programs are handled by system defined
Exceptions.
2) User defined exception:

It must be declare by the user in the declaration part of the block where the exception is used. It is
raised explicitly in sequence of statements using: Raise_application_error (error_no,
error_name);

Q. Write a PL/SQL program to find the square of a number given by user


usingWHILE….LOOP.(accept the number from user dynamically) 4 Marks
(Correct Program - 4 marks) [**NOTE: any relevant program logic shall be considered**]

SET SERVEROUTPUT ON;


DECLARE n number:= &n;
sqr number:= 0;
n_cntr number:=0; BEGIN
DBMS_OUTPUT.PUT_LINE(n);
WHILE n_cntr < n LOOP
sqr:= sqr + n;
n_cntr := n_cntr + 1;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Square of ' || n || ' is ' || sqr);
END;

Q. Write a PL/SQL program using while loop to display n even numbers. 4 Marks
(Correct logic - 2 marks; correct syntax - 2 marks) [** Note: Any relevant logic can be
considered**]
SET SERVEROUTPUT ON;
DECLARE n number:= &n;
i number:= 0;
cnt number:=0;
BEGIN
WHILE (cnt< n) LOOP
if( mod (i,2)=0) then
Dbms_output.put_line(i);
cnt:=cnt+1;
End if;
i:=i+1;
END LOOP;
END;

Q. List out any four statements of PL/SQL. 4 Marks


(Any four statement list/syntax - 1 mark each)

1. Declare
2. Begin
3. End
4. Exception
5. dbms_output.put_line();
6. If condition then
Statements Else Statements End if;
7. LOOP

<loop_body> END LOOP;


8. LOOP

<loop_body>
EXIT WHEN (condition); END LOOP;
9. WHILE <condition> LOOP

<loop body> END LOOP;


10. GOTO <<label_name>>;
11. FOR COUNTER IN [reverse] LOWER_BOUND..UPPER_BOUND LOOP

<loop body> END LOOP;


12. CASE [expression]

WHEN condition_1 THEN


result_1
WHEN condition_2 THEN
result_2 …..
WHEN condition_n THEN
result_N
ELSE
RESULT
END CASE;
Q. What is database trigger? Compare database triggers and procedures and explain the use
of database trigger.
(Definition - 1 mark; Comparison - 2 marks; Uses - 1 mark) [**Note: Any relevant comparison
can be considered**]

Database Trigger: Database trigger are ‗event-condition-action model„ which are fixed on certain
event. Trigger represents action to be taken if some event happens. In case of DBMS, triggers are
automatically fired when tables are modified with insert, update and delete etc.

Use of database trigger:


• Triggers can be used to prevent invalid transaction and to apply complex security authorization.
• It can be used to implement complicated integrity constraints.
• It can be used to maintain duplicate table and to check the data modifications.

Comparison:
Database Trigger Procedures
1. Triggers are fired when particular SQL 1. Procedures are executed when they are
commands (DML) are executed Called
2. Triggers have events and related actions 2. Procedure do not have events and related
Actions
3. Triggers are called implicitly 3. Procedure are called explicitly

Q. Explain PL/SQL block structure. 4 Marks


(Correct Explanation - 4 marks)

A PL/SQL Block consists of four sections:

1. The Declaration section : Declaration of memory variables used later in begin section.
2. The Begin..End section : SQL executable statements for manipulating table data should be in
BEGIN....END block.
3. The Exception section : SQL and/or PL-SQL code to handle errors that may crop up during
execution of the above code block.
Q. List types of cursor and explain each with example. 4 Marks
(Description - 1 mark; example - 1 mark for each type; 1 mark shall be awarded if only list is
given) [**Note: any other examples showing use of implicit and explicit cursor can be
considered**]
Types of Cursor
Implicit cursor
Explicit cursor

Implicit cursor: If database engine opens a cursor for internal processing, it is called as implicit
cursor. Example of implicit cursor:
Declare
Begin
Update emp set salary= salary +500 where empno =&empno;
If SQL%FOUND then
Dbms_out.put_line(―Emp table modified‖);
Else Dbms_out.put_line(―Emp table modified‖);
End if;
End;

Explicit cursor: A user can open a cursor for processing data as required. Such user defined cursors
are known as explicit cursors.
Example of explicit cursor:
Declare
Cursor c1 is select empno, salary from emp Where deptno=10;
Ecode emp.empno%Type;
Sal emp.salary%Type;
Begin
Open c1;
If c1%ISOPEN then
Loop
Fetch c1 into ecode,sal;
If c1% NOTFOUND then
Exit;
End if;
Update emp set salary = salary+500;
End Loop;
Close c1;
Else
Dbms_out.put_line(―unable to open‖);
End if;
End;
WINTER 2016

Q. Define cursor? List the two types of cursor. 2 Marks


Cursor: A cursor is a temporary work area created in the system memory when a SQL
statement is executed.
Types of Cursor: 1.Implicit Cursor 2.Explicit Cursor

Q. Explain the exception handling with its two type. 4 Marks


Exception Handling: Exception is nothing but an error. Exception can be raise when
DBMS encounters errors or it can be raised explicitly. When the system throws a
warning or has an error it can lead to an exception. Such exception needs to be handled
and can be defined internally or user defined. Exception handling is nothing but a code
block in memory that will attempt to resolve current error condition.

Syntax:
DECLARE
; Declaration section
…executable statement;
EXCEPTION
WHEN ex_name1 THEN
; Error handling statements/user defined action to be carried out;
END;

Types of Exception:
1) Predefined Exception/system defined exception/named exception:
Are always automatically raised whenever related error occurs. The most common
errors that can occur during the execution of PL/SQL. Not declared explicitly i.e.
cursor already open, invalid cursor, no data found, zero divide and too many rows
etc. Programs are handled by system defined Exceptions.

2) User defined exception:


It must be declare by the user in the declaration part of the block where the
exception is used.
It is raised explicitly in sequence of statements using:
Raise_application_error(Exception_Number,Error_Message);

Q. Write a PL/SQL program to print even or odd number from given range (Accept
number range from user). 4 Marks
{**NOTE: any relevant program logic shall be considered**}
DECLARE
A NUMBER :=&A;
B NUMBER :=&B;
C NUMBER :=&C;
BEGIN
IF(C=1) THEN
FOR I IN A..B LOOP
IF(MOD(I,2)=0) THEN
DBMS_OUTPUT.PUT_LINE(I);
END IF;
END LOOP;
ELSE
FOR I IN A..B LOOP
IF(MOD(I,2)=1) THEN
DBMS_OUTPUT.PUT_LINE(I);
END IF;
END LOOP;
END IF;
END;

OR
-- PL/SQL code to display even numbers
DECLARE
A NUMBER :=&A;
B NUMBER :=&B;
BEGIN
FOR I IN A..B LOOP
IF(MOD(I,2)=0) THEN
DBMS_OUTPUT.PUT_LINE(I);
END IF;
END LOOP;
END;

-- PL/SQL code to display odd numbers


DECLARE
A NUMBER :=&A;
B NUMBER :=&B;
BEGIN
FOR I IN A..B LOOP
IF(MOD(I,2)=1) THEN
DBMS_OUTPUT.PUT_LINE(I);
END IF;
END LOOP;
END;

Q. Explain function in PL/SQL with suitable example 4 Marks


A function (also called a user function or user-defined function) is a set of PL/SQL
statements that is called by name. A function returns a value to the environment in
which it is called.
Syntax:
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;
Example :
CREATE OR REPLACE FUNCTION employer_details_func
RETURN VARCHAR(20);
IS
ename VARCHAR(20);
BEGIN
SELECT fname INTO ename
FROM emp WHERE empID = '100';
RETURN ename;
END;
Q. Explain loop control structure used in PL/SQL. 4 Marks
LOOP: PL/SQL LOOP statement is an iterative control statement that allows to execute
a sequence of statements repeatedly like WHILE and FOR loop.
Syntax:
LOOP
sequence_of_statements;
END LOOP;
Example:
i number :=1;
Loop
dbms_out.put_line(„Good Morning‟);
i :=i+1;
Exit when i=10
End Loop

WHILE: If it is not known in advance how many times a sequence of statements needs
to execute. In such cases, one should use PL/SQL WHILE LOOP statement.
Syntax:
WHILE condition LOOP
sequence_of_statements;
END LOOP;
Example:
i number := 1;
while (i<=10) Loop
dbms_output.put_line(i);
i :=i+1;
End Loop;

3) FOR: FOR loop is an iterative statement that execute a sequence of statements a


fixed number of times.
Syntax:
FOR loop_counter IN [REVERSE] lower_bound .. higher_bound
LOOP
sequence_of_statements;
END LOOP;
Example:
For i in 1..10 loop
dbms_output.put_line(i);
end loop;
SUMMER-2015
Q. How to create trigger? State any two advantages of trigger.
(Trigger Syntax or example -2Marks, Any 2 advantages- 2 Marks)
[Note: Any relevant example can be considered]
The Syntax for creating a trigger is:
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
ON table_name
[FOR EACH ROW/For Each statement]
WHEN (condition)
BEGIN
--- sql statements
END;
(OR)
Example
CREATE or REPLACE TRIGGER After_Update_Row_product
AFTER
insert On product
FOR EACH ROW
BEGIN
INSERT INTO product_check Values('After update, Row level',sysdate);
END;

Advantages of triggers:
1. Triggers provide an alternative way to check the integrity of data.
2. Can catch errors in business logic in the database layer.
3. SQL triggers provide an alternative way to run scheduled tasks.
4. Triggers are very useful to audit the changes of data in tables.

Q. Write a PL/SQL program which handles divide by zero exception.


(Correct Program - 4 Marks)
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 Exception
dbms_output.put_line(„ Result ‟ || C); -- Result will not be displayed
EXCEPTION
WHEN ZERO_DIVIDE THEN
dbms_output.put_line(„ Trying to Divide by zero :: Error ‟);
END;
/

Q. What are the various datatypes of PL/SQL?


(Any 4 data types -1Mark each)

The default data types that can be declared in Pl/SQL are :


1) number (size)– for storing numeric data
eg. a number(2);
2) char/ varchar(size) – for character data
eg: mynamevarchar(20);
3) date – for date and time data
eg : dob date;
4) Boolean – for storing true, false or null
eg: status Boolean;
5) %Type - to declare a variable or constant to have a same data type as that of a
previously defined variable or a column in a table.
e.g. enoemp.empno%type

Q. Write PL/SQL procedure to calculate factorial of a give number.


(Correct program – 4Marks)
[Note: Any other relevant logic shall be considered]
SQL> create or replace procedure Factorial(n in number)
is
v number :=1;
begin
for i in 1..n
loop
v :=v * i; end loop;
dbms_output.put_line(v);
end;
Procedure created
SQL> Begin
Factorial(5);
End;

Q. Differentiate between function and procedure.


(Any four point – 1Mark each)

Q. What are the various control structure statements used in PL/SQL?


(Any four control structures - 1 Mark each)
Conditional Control:
1. If then Else End If statement:
• The „If then Else End if is used to check the conditions.
• If the condition in if part is true then the statement in the if block gets execute.
• If the condition in if part is false then the statement given in the else part gets
execute.
• To give more number of conditions we can use „if the elseif‟ which provides more
number of conditions.
• The general syntax of „if‟ is as follows:
If condition then
Statements
Else
Statements
End if;

2. Nested If:
• In this, any number of ELSIF clauses can be used with one IF statement.
• Either set of actions of the result of the first IF statement of ELSE statement can
contain further IF statements before specific actions are performed.
• Each nested IF statement must terminate with a corresponding END IF.
• Syntax:
If condition then
Statements
If condition then
Statements
Else
If condition then
Statements
Else condition then
Statements
End if;
End if;
End if;

3. Case
• Evaluates a list of conditions and returns one of multiple possible result
expressions.
• CASE can be used in any statement or clause that allows a valid expression. For
example, you can use CASE in statements such as SELECT, UPDATE, DELETE
and SET, and in clauses such as select_list, IN, WHERE, ORDER BY, and
HAVING.
• Synatx:
CASE [ expression ]
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
...
WHEN condition_n THEN result_n
ELSE result
END

Iterative Control:
1. Simple Loop
2. While Loop
3. For Loop

1. Simple Loop
LOOP statements let you execute a sequence of statement multiple times.
Place the keyword LOOP before the first statement in the sequence and the
keyword END LOOP after the last statement in the sequence.
Syntax:
Endless loop
LOOP
<loop_body>
END LOOP;
Conditional loop
LOOP
<loop_body>
EXIT WHEN (Condition);
END LOOP;
The EXIT WHEN statement lets you complete a loop if further processing is impossible
or undesirable.
When the EXIT statement encountered, the condition in the WHEN clause is evaluated.
If the condition is true, the loop completes and control passes to the next statement.

2. While Loop
The WHILE LOOP statement associates a condition with a sequence of statements.
Before each iteration of loop, the condition is evaluated.
If the condition is true, the sequence of statement is executed, then control resumes at the
top of the loop.
If the condition is false or null, the loop is bypassed and control passes to the next
statement.
Syntax:
WHILE <Condition> LOOP
<loop body>
END LOOP;

3. For Loop :
The FOR LOOP statement specifies a range of integers, then execute a sequence of
statements once for each integer in the range.
To reverse the range , “REVERSE” keyword is used.
The syntax is :
FOR i IN 1..N LOOP
<loop_body>
END LOOP;

4. Sequential Control:
Label can be used to give a label or name to the piece of code. And once the name is
given to it, user can call that piece of code with that label whenever and wherever
required in the program .
Syntax for label is as follows:
<<label_name>>
Statements;
The Goto statement is used to transfer the control or to change the sequence of the
instructions.
Syntax for goto statement is as follows:
Goto<<label_name>>

WINTER 2015
Q. What statement is used in PL/SQL to display the output?
(Correct statement – 2 Marks)
dbms_output.put_line( var/msg);
OR
set serveroutput on;
dbms_output.put_line( var/msg);

Q. What is Cursor?
(Cursor Description – 2 Marks)
Oracle creates a memory area, known as context area, for processing an SQL
statement, which
contains all information needed for processing the statement, for example, number of
rows processed, etc.

Q. Write PL/SQL program to print even or odd numbers from given range. (Accept
number
from user.)
(Correct logic - 2 Marks, correct syntax – 2 Marks)
[** Note: Any relevant logic can be considered]
Logic 1 :
Declare
n1 number := &n1;
n2 number :=&n2;
i number ;
begin
dbms_output.put_line(‘Even numbers are :’);
for i in n1..n2
loop
if mod(i,2)=0 then
dbms_output.put_line(i);
end if;
end loop;
dbms_output.put_line(‘Odd numbers are :’);
for i in n1..n2
loop
if mod(i,2)!=0 then
dbms_output.put_line(i);
end if;
end loop;
end;

Logic 2 :
Declare
n1 number := &n1;
n2 number :=&n2;
i number ;
begin
for i in n1..n2
loop
if mod(i,2)=0 then
dbms_output.put_line(‘Even :’ || i);
else
dbms_output.put_line(‘Odd :’ || i);
end if; end
loop; end;

Q . Explain conditional control structure in PL/SQL.


(Explanation of each structure - 1 Mark, syntax of each - 1 Mark)
Conditional control statements in PL/SQL:
1. If then Else End if statement:PL/SQL provide ‘if’ statement to check conditions in
program. If the given condition is true, then the part after If statement gets executed,
otherwise, part below else gets executed.
Syntax:
If <condition> then
<action>
Else
<action>
End if;

2. Case
Evaluates a list of conditions and returns one of multiple possible result expressions.
CASE can be used in any statement or clause that allows a valid expression
Syntax:
CASE [ expression ]
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
...
WHEN condition_n THEN result_n
ELSE result
END CASE;
Q. Write PL/SQL program to display factorial of any number.
(Correct logic – 2 Marks, correct syntax – 2 Marks)
[**Note: Any other relevant logic can be considered]
declare
f number :=1;
n number := &n;
begin
for i in 1..n
loop
f := f * i; end loop;
dbms_output.put_line(f);
end;
/

Q. Explain implicit and explicit cursors.


(Implicit cursor – 2 Marks, Explicit cursor – 2 Marks)
Implicit Cursor:
Implicit cursors are automatically created by Oracle whenever an SQL statement is
executed, when
there is no explicit cursor for the statement.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit
cursor is
associated with this statement. For INSERT operations, the cursor holds the data that
needs to be
inserted. For UPDATE and DELETE operations, the cursor identifies the rows that
would be
affected.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which
always has the
attributes like %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. The following
table
provides the description of the most used attributes

Explicit cursor:
Explicit cursors are programmer defined cursors for gaining more control over the
context area. An
explicit cursor should be defined in the declaration section of the PL/SQL Block. It is
created on a
SELECT Statement which returns more than one row.
Working with an explicit cursor involves four steps:
Declaring the cursor for initializing in the memory
Cursor cursor_name IS select_statement;
Opening the cursor for allocating memory
Open cursorname;
Fetching the cursor for retrieving data
Fetch cursorname INTO variable1,variable2…
Closing the cursor to release allocated memory
Close cursorname;

Q. Explain parameterized cursor with example.


(Explanation - 2 Marks, Any relevant Example - 2 Marks)
PL/SQL Parameterized cursor pass the parameters into a cursor and use them in to
query.
PL/SQL Parameterized cursor define only datatype of parameter and not need to define
it's length.
Default values is assigned to the Cursor parameters and scope of the parameters
are locally.
Parameterized cursors are also saying static cursors that can passed parameter
value when cursor
are opened.

Syntax to declare parameterized cursor:


CURSOR CursorName(VariableName Datatype)IS<SELECT statement…>
Opening A parameterized Cursor And Passing Values to the Cursor
OPEN CursorName(Value / Variable / Expression);

Example
Cursor display employee information from emp_information table whose emp_no is
four
(4).
DECLAR
E
cursor c(no number) is select * from
emp_information where emp_no = no;
tmp
emp_information%rowtype;
BEGIN
OPEN c(4);
FOR tmp IN c(4) LOOP
dbms_output.put_line('EMP_No: '||tmp.emp_no);
dbms_output.put_line('EMP_Name:
I|tmp.emp_name); dbms_output.put_line('EMP_Dept:
'||tmp.emp_dept);
dbms_output.put_line('EMP_Salary:'||tmp.emp_salar);
END Loop;
CLOSE ;
END;
/

You might also like