Session 7
Session 7
function myfunc(
param1 IN number)
return number
is
grade number;
begin
grade:=param1 ;
return (grade);
end;
begin
DBMS_OUTPUT.PUT_LINE('The function returned: ' || myfunc(10));
end;
/
• Exercise : WRITE THE CODE FOR CALLING THE PROCEDURE
Use the select statement in PL/SQL
(only if the select returns one single row as result )
declare
name varchar2(100);
id number;
begin
select sid, fname
into id,name
from students
where sid = 1111;
end;
/
Cursors
• When the result of a select statement
consists of more than one row the “select
into” statement can not be used.
• A PL/SQL cursor allows a program to fetch
and process information one row at a time
• Declaration:
cursor <sname> is <select statement>;
Cursor example
DECLARE
CURSOR c1 IS
select sid,fname
from students;
c1_rec c1%rowtype;
BEGIN
if not c1%isopen then
open c1;
end if;
close c1;
END;
/
How to work with cursors
• declare the cursor
• declare a variable rec_name of type cursor
%rowtype
• “open c_name”
• fetch row by row “fetch c_name into rec_name”
• “close cursor”
– c_name%found – returns true if there are still
records , false otherwise
– c_name%isopen - returns true if the cursor is open,
false otherwise
Cursor “for” example
DECLARE
CURSOR c1 IS
select sid,fname
from students;
BEGIN
for c1_rec in c1 loop
dbms_output.put_line('Row Number ' || c1%rowcount || '> ' ||
c1_rec.sid || ' ' || c1_rec.fname);
end loop;
END;
/
• When using “for loops” the cursor does not have to be explicitly opened and
fetched from.
Stored Procedures
• Syntax
create [or replace] procedure <proc_name>
[(<parameter_list>)] as
<declarations>
begin
--executable section
[exception <exception-section>]
end
why needed ?
• most of the time the stored procedures
contain the entire application logic
• Ex: create a report with all the courses on
all the years, average grade of the curse,
students enrolled in the course, their
grades on all the components of the
courses and their final grade.
Exceptions
• when an error occurs during the execution
of a PL/SQL program a exception is raised
• program control is transferred to the
exception section
Common exception
• NO_DATA_FOUND -- select into failed
because the it resulted in no row
• TOO_MANY_ROWS -- select into failed
because the it resulted more than one row
• INVALID_NUMBER -- to_number(string)
has invalid input parameter
• ZERO_DEVIDE -- a division by 0 occured
Views
• A view is a named query , virtual table
• Views are created, dropped or granted
access to, identical to a table.
How do views differ from tables?
From : http://www.cdoug.org/docs/views-1099.pdf
Syntax
create view <view_name> as
<select statement>;
drop view <view_name> ;
ex.
create view vCourses as
select catalog.ctitle, courses.term, courses.lineno from
catalog, courses
where catalog.cno=courses.cno;