Lab 11 - Functions
Lab 11 - Functions
Functions
• Unlike procedures, functions can return a
value to the caller.
Creating Functions in SQL Example
CREATE OR REPLACE FUNCTION age(dob IN
DATE ) RETURN NUMBER
IS
cal_age NUMBER;
BEGIN
cal_age := (SYSDATE - dob)/365.25;
RETURN cal_age;
END;
/
Creating Functions in SQL Example
CREATE OR REPLACE FUNCTION
Student_Age(Current_S_ID IN NUMBER)
RETURN NUMBER
IS
Current_Date DATE;
Student_DOB DATE;
BEGIN
SELECT s_dob INTO Student_DOB
FROM student
WHERE s_id = Current_S_ID;
Current_Age := (SYSDATE– Student_DOB)/365.25;
RETURN Current_Age;
END;
/
Calling the user-defined function (1)
• SELECT NAME, Student_Age(S_ID)
FROM STUDENT
declare
STUDENT_AGE number;
begin
STUDENT_AGE := Student_Age(101);
end;
HINTS TO DISPLAY CODE
SET LONG 1000
• %NOTFOUND
– No more records can be fetched from the cursor
• %ISOPEN
– The cursor has been opened
• %ROWCOUNT
– The number of rows fetched from the cursor so far
FOR Loops
declare
pi constant NUMBER(9,7) := 3.1415926;
radius INTEGER(5);
area NUMBER(14,2);
begin
for radius in 1..7 loop
area := pi*power(radius,2);
insert into AREAS values (radius, area);
end loop;
end;
/
Cursor FOR Loops
declare
pi constant NUMBER(9,7) := 3.1415926;
area NUMBER(14,2);
cursor rad_cursor is
select * from RADIUS_VALS;
begin
for rad_val in rad_cursor loop
area := pi*power(rad_val.radius,2);
insert into AREAS values (rad_val.radius, area);
end loop;
end;
/
WHILE Loops
declare
pi constant NUMBER(9,7) := 3.1415926;
radius INTEGER(5);
area NUMBER(14,2);
begin
radius := 3;
while radius<=7 loop
area := pi*power(radius,2);
insert into AREAS values (radius, area);
radius := radius+1;
end loop;
end;
/
Conditional Logic
if <some condition>
then <some command>
elsif <some condition>
then <some command>
else <some command>
end if;
Conditional Logic
declare
pi constant NUMBER(9,7) := 3.1415926;
area NUMBER(14,2);
cursor rad_cursor is
select * from RADIUS_VALS;
rad_val rad_cursor%ROWTYPE;
Begin
open rad_cursor;
fetch rad_cursor into rad_val;
area := pi*power(rad_val.radius,2);
if area >30
then
insert into AREAS values (rad_val.radius, area);
end if;
close rad_cursor;
end;
/