03 PL SQL
03 PL SQL
PL/SQL
Introduction to PL/SQL
• What is PL/SQL?
• Executable Commands
– It’s enclosed between keywords BEGIN and END.
– It’s a mandatory section.
– It consists of executable PL/SQL statements of the program.
• Exception Handling
– This section starts with the keyword EXCEPTION.
– This section is also an optional section.
– It contains exceptions that handle errors in the program.
Simple PL/SQL program
Print natural numbers from 1 to 5.
declare
i number;
begin
i:=1;
loop
dbms_output.put_line(i);
i:=i+1;
exit when i > 5;
end loop;
end;
Procedures
• It’s a named block of statement.
• It may or may not return a value.
SYNTAX:
declare cursor c1
is
select deptName as Department,avg(fees) as Average_Fees from student
natural join department group by deptName;
rec1 c1%rowtype;
begin
for rec1 in c1 loop
dbms_output.put_line(rec1.Department ||' '||rec1.Average_Fees);
end loop;
end;
Explicit Cursor : Example 2
Show the department wise student details.
declare cursor c1
is
select distinct deptName from department;
cursor c2(dept varchar)
is
select name,marks from student natural join department where deptName=dept ;
rec1 c1%rowtype;
rec2 c2%rowtype;
begin
for rec1 in c1 loop
dbms_output.put_line(rec1.deptName);
for rec2 in c2(rec1.deptname) loop
dbms_output.put_line(rec2.name||' '||rec2.marks);
end loop;
dbms_output.put_line('');
end loop;
end;
Procedure with cursor
• Statement: Write a procedure which will display details of all students from a
given department:
To Execute:
begin
listStudents('production');
end;
PL/SQL Functions
• A PL/SQL function is same as a procedure except
that it always returns a value.
• General Syntax:
– CREATE [OR REPLACE] FUNCTION function_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype {IS | AS}
BEGIN
< function_body >
END [function_name];
Functions: Example 1
• Write a function which will return the total fees
collected for a given department.
create or replace function totalFees(dept varchar)
return int
is
total int;
begin
select sum(fees) into total from student natural join department
where deptName=dept;
return total;
end;
• Thank you!
• For any queries, ask me on my profile
• http://bbarters.com/user/ksjoshi88
or
• http://bbarters.com/user/prath257
• http://bbarters.com/user/ritesh