0% found this document useful (0 votes)
139 views

Dbms Unit 5 Final

The document discusses PL/SQL, including its structure, datatypes, cursors, procedures, and functions. PL/SQL combines SQL and procedural elements and allows grouping of SQL statements to execute as a single unit. It has a declare, begin, and exception section. Common datatypes include number, date, varchar, and cursor. Cursors allow iterating through recordsets returned from a query. Procedures and functions are reusable code blocks that can optionally return values. Packages allow grouping related procedures and functions into a single unit.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
139 views

Dbms Unit 5 Final

The document discusses PL/SQL, including its structure, datatypes, cursors, procedures, and functions. PL/SQL combines SQL and procedural elements and allows grouping of SQL statements to execute as a single unit. It has a declare, begin, and exception section. Common datatypes include number, date, varchar, and cursor. Cursors allow iterating through recordsets returned from a query. Procedures and functions are reusable code blocks that can optionally return values. Packages allow grouping related procedures and functions into a single unit.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

III BSc, DBMS

UNIT 5
PL/SQL
1Q. DEFINE PL/SQL. EXPLAIN ABOUT STRUCTURE OF PL/SQL PROGRAM.
WRITE STEPS TO EXECUTE A PLSQL PROGRAM.
ANS: PL/SQL INTRODUCTION: PL/SQL stands for procedural language/structure
query language.
 PL/SQL is not a 4GL or a high level language (3GL). But it acts as an interface
or platform to work with set of SQL commands to execute a task.
 PL/SQL contains SQL commands along with block of statements like control
statements, functions, procedures and so on.
Advantages of PL/SQL:
1. We can group no.of SQL commands and execute them as one task.
2. We can also do decision control logics and looping programs on SQL commands
using PL/SQL.
Structure of PL/SQL Block:

declare
variable declaration;
begin
SQL Statements;
exception
SQL code to handle errors;
end;

 Here , “Declare section” is used to declare variables used in a plsql program.


 “Begin Section” is used to write all executable stattements.
 “Exception Section” is used to write statements to handle errors.
 Every PL/SQL statement must end with a semi-colon(“;”);
 Every PL/SQL program must end with keyword “end”.
 PL/SQL is not case-sensitive.
 Single line comment in PL/SQL is “- -“(double hyphen).
 Multiple line comment in PL/SQL is “/*…. */”.

1
III BSc, DBMS

Example PL/SQL PROGRAM for addition of two numbers.


declare
x number;
y number;
z number;
begin
x:=10;
y:=20;
z=x+y;
dbms_output.put_line(‘sum is ‘ || z);
end;
Steps to Execute a PL/SQL Program:
1. Open notepad and type PLSQL program
2. Save file in plsql folder ie., e:\plsql\file1.sql . We must save file with “.SQL”
extention
3. Open SQL prompt. Give user-name and password
4. At SQL prompt give the following command to execute program:
SQL> set serveroutput on
SQL> @ e:\plsql\file1
Output : Sum is 30
PL/SQL procedure successfully completed
 Here “set serveroutput on “ is used to display plsql editor output on sql screen.
“@” symbol is used to execute PLSQL program

2
III BSc, DBMS

2Q. EXPLAIN DATATYPES IN PL/SQL.


Ans: Datatypes in PL/SQL: A datatype represents type of data we store in a variable
and range of data. Oracle supports the following data types in PL/SQL.
%TYPE: %type is used to define field structure to a variable in pl/sql. It is a dynamic
datatype in plsql.
Ex: s emp.sal%type;
%ROWTYPE: %rowtype is used to define record structure to a variable in pl/sql. It is a
dynamic datatype in plsql.
Ex: r emp%rowtype;
Number : This datatypes is used to store numbers i.e., whole number or decimal number
etc., Maximum size of this datatype is 2bytes.
Ex: marks number(3) can store 55,77,88……
Ex: sal number(7,2) can store 5123.00,8000.50,…..
Char : Char is a datatype used to store fixed length text. Maximum size of char is 0 to 255
characters. Ex: pancardno char(10);
Varchar: varchar is a datatype used to store variable length text. Maximum size of
varchar is upto 2000 characters. Ex: address varchar(30);
Varchar2 : varchar2() is a datatype used to store variable length text. Maximum size
of varchar2 is 2GB. Ex: bookdesc varchar2(200);
Date & Time : This datatype is used to store date&time. Maximum size of this data type
is 8 bytes. Format for date is ‘dd-mon-yy’. Example: dob date;
Raw : Raw is a binary datatype. It is used to store images, videos, audios etc.,.
Maximum size of raw datatype is 2Bytes.
LOB: LOB means Large Objects. LOB is a binary datatype. It is used to store images,
videos, audios etc.,.Maximum size of LOB datatype is 4 Bytes.
CLOB: CLOB means Character Large Objects. CLOB is a binary datatype. It is used to
store character or text data. It is used to store pdf’s, textbooks etc., Maximum size of
CLOB datatype is 4 Bytes.

3
III BSc, DBMS

3Q. EXPLAIN ABOUT CURSORS IN PL/SQL.


ANS: CURSOR: Cursor is a temporary workarea created in system memory by oracle
engine. A cursor is created when “SQL command” is executed in plsql program.
 Output of SQL command may contain one or more records.Records in this
workarea are known as “Active Data Set(ADS)”.
Types of Cursors: 1. Implicit Cursors. 2.Explicit Cursors
Implicit Cursors: Implicit cursors are created and executed automatically by “Oracle
Engine”. Implicit cursors contains only one record in cursor workarea.
Explicit Cursors: Explicit Cursors are created by “User”. Hence these are known as
“User-defined” Cursors. Explicit Cursors contains more than one record in cursor
workarea.
Cursor Attributes: Different types of attributes for a cursor are:
1. %isopen: Used to check if cursor is open or not. It “returns true” if cursor is
successfully created, otherwise it returns false.
2. %found: Returns “true” if workarea contains any records, otherwise it returns
“false”.
3. %notfound: It is opposit of “%found”. It returns “False” if workarea contains
any records, otherwise it returns “True”.
4. %rowcount : It returns no.of records present in cursor workarea.
Steps to work with cursors:
Step1 : Create cursor
Ex: cursor c1 is select * from emp where deptno=10;
Where c1 is cursor name.
Step 2: Open Cursor
Ex: open c1;
Step 3: Fetch records into variable. (i.e., copy records into variable)
Ex: fetch c1 into r;
Here, “r” is a %rowtype variable.
Step 4: Close cursor.
Ex: close c1;

4
III BSc, DBMS

Example Cursor program to print details of employees working in deptno 10.


declare
cursor c1 is select * from emp where deptno=10;
r emp%rowtype;
begin
open c1;
loop
fetch c1 into r
dbms_output.put_line(r.empno);
dbms_output.put_line(r.ename);
exit when c1%notfound;
end loop;
close c1;
end;

5
Aditya Degree College, Kakinada III BSc, DBMS

4Q. EXPLAIN ABOUT PROCEDURES IN PL/SQL.


ANS: Procedures: Procedures are self-contained block of statements to perform a
specific-task.
 Procedures are also known as “Stored Procedures”.
 A Procedure doesn’t return any value to the main program or called program.
 Procedures are database objects.
 The advantage of procedures is “Reusability of code”.
Syntax for Procedure:

create or replace procedure <procedure name> (variable datatype) as


variable declaration;
begin
statements;
end;

Example for Procedure:

create or replace procedure addition(x number,y number) as


z number(3);
begin
z:=x+y;
dbms_output.put_line(z);
end;

Steps to Execute a Procedure:


1. Save the procedure program with .sql extentions like “pro1.sql”
2. Execute the file like,
SQL> @ e:\plsql\pro1
3. Execute procedure using “ exec” command like
SQL> exec addition(30,40)
Output: 70
6 G.VijayaLakshmi, ADCKKD
III BSc, DBMS

5Q. EXPLAIN ABOUT FUNCTIONS IN PL/SQL.


ANS: Functions: Functions are self-contained block of statements to perform a
specific-task.
 A Function returns a value to the main program or called program.
 Functions are database objects.
 The advantage of Functions is “Reusability of code”.
Syntax for Function:

create or replace function<function name> (variable datatype) return datatype is


variable declaration;
begin
statements;
return(variable);
end;

Example for Function:

create or replace function addition(x number,y number) return number is


z number(3);
begin
z:=x+y;
return(z);
end;

Steps to Execute a Function:


1. Save the Function program with .sql extentions like “fun1.sql”
2. Execute the file like,
SQL> @ e:\plsql\fun1
3. Execute Function using “ select” command like
SQL> select addition(30,40) from dual;
Output: 70

7
III BSc, DBMS

6Q. EXPLAIN ABOUT PACKAGES IN PL/SQL.


Ans: Packages: A package is a collection of sub-programs like procedures,
functions and cursors. Each procedure or function or cursor is a sub-program.
 Packages are database objects. We can create packages using “Create” command.
 Advantages of packages is “we can group all functions and procedures of an
application into one unit”. It helps in “reusability and better understanding “ of
program.
Structure of Package: Every package may contain two parts. They are:
1) package specification 2) package body or definition
Package Specification: A package specification program consists of declaration of all
procedures, functions and cursors. Without package specification we cannot write
package body.
Syntax for Package Specification:

create or replace package<package name> is/as


function1;
function2;
.........
procedure1;
procedure2;
....................
end packagename;

Example for Package Specification:

create or replace package p1 is


procedure addition(x1 number,y1 number);
procedure subtraction(x2 number, y2 number);
end p1;

8
III BSc, DBMS

Package body or definition: The package body contain various methods declared in
the package specification. Package body name and package specification name must be
same.
Example for Package Body:

create or replace package body p1 is


procedure addition(x1 number,y1 number) is z1 number;
begin
z1:=x1+y1;
dbms_output.put_line(z1);
end addition;
procedure subtraction(x2 number, y2 number) is z2 number;
begin
z2:=x2+y2;
dbms_output.put_line(z2);
end p1;

Steps to execute a package: The procedures or functions can be accessed with the
help of package name. i.e., Packagename.procedurename(args);
Ex: SQL> exec p1.addition(30,40);
70
In this example, p1 represents packagename, addition represents procedure name.

9
III BSc, DBMS

7Q. EXPLAIN ABOUT EXCEPTION HANDLING IN PL/SQL.


ANS: Exception Handling: Exception means “runtime errors”. Exception handling is
a programming technique to handle runtime errors.
 A program can have no.of exceptions.
 All exception in plsql are handled in “Exception block”.
 When an runtime error occurs in program, normal execution stops and the
control transfers to exception block.
There are two types of exception :
1. Pre-defined Exceptions
2. User-defined Exceptions.
1. Predefined Exception: Pre-defined exceptions are system defined or built-in
exceptions. Different types of Pre-defined exception:
zero_divide: This exception occurs when “number is divide by zero”.
value_error: This exception occurs when “ datatype mismatch occur”.
no_data_found: This exception occurs when “select command in plsql returns zero
records”.
too_many_rows: This exception occurs when “select comman in plsql returns more
than one record”.
Example Program on Predefined Exceptions:

declare
x number(3);
y number(3);
begin
x:=10;
y:=x/0;
dbms_output.put_line(y);
exception
when zero_divide then
dbms_output.put_line(‘ division by zero error’);
end;

10
III BSc, DBMS

User-defined Exceptions: Exceptions defined by user are known as user-defined


exceptions. Here user can give their own conditions as exceptions.
 We can create no.of. user-defined exceptions for a plsql program.
 The following statements are used to define user-defined exceptions:
 Create an exception in “declaration section”.
 Raising an exception using “raise” command
 Handling an exception in “exception block”.

Example Program on User-defined Exceptions:

declare
age_error exception;
age number(3):=&age;
begin
if age>18 then
dbms_output.put_line(‘eligible for voting’);
else
raise age_error;
end if;
exception
when age_error then
dbms_output.put_line(‘not eligible for voting’);
end;

In the above program user-defined exception name is “age_error”.

11
III BSc, DBMS

8Q. EXPLAIN ABOUT TRIGGERS IN PL/SQL.


ANS: TRIGGERS: A Trigger is a database object. It is executed automatically when
we perform DML commands i.e., insert,delete,update on database table.
Trigger programming is also known as “Event Handling”, where events are nothing
but DML commands we perform on table.
Types of trigges: There are two types of triggers
 Row level Trigger
 Database Trigger
Row level Trigger : Trigger written by users on tables are known as row-level
triggers. These triggers are executed for each record(row) in a table.
Syntax for Row-level Trigger:

create or replace trigger <triggername> before/after/insteadof insert/delete/update


on tablename for each row
begin
statements;
end;
Example for Row-level Trigger:

create or replace trigger t1 after insert on smarks for each row


begin
update smarks set smarks.tot = smarks.m1+ smarks.m2+smarks.m3;
end;

Database Trigger : Database triggers are written by DBA i.e., Database


Administrator. Database triggers will be executed when the user log on to database.
Example for database trigger to stop all DML commands on “emp table”:

create or replace trigger mytrig before insert or delete or update on emp


begin
raise_application_error(‘operations not allowed on emp table’);
end;

Detete a Trigger: Drop command is used to delete a trigger from the database.
Syntax: SQL> Drop trigger <triggername>;
Example: SQl> Drop trigger t1;

12
III BSc, DBMS

9Q. EXPLAIN CONTROL STRUCTURES IN PL/SQL WITH EXAMPLES.


ANS: PL/SQL INTRODUCTION: PL/SQL stands for procedural language/structure
query language.
 PL/SQL is not a 4GL or a high level language (3GL). But it acts as an interface
or platform to work with set of SQL commands to execute a task.
 PL/SQL contains SQL commands along with block of statements like control
statements, functions, procedures and so on.
Control Structures in PL/SQL: There are two types of control structures in pl/sql.
They are 1. Decision making statements 2. Looping statements.
Decision Making Statements: Decision making statements are executed only one-
time based on a “condition”.They are divided into following types:
1. simple if 2. if – else 3. elsif ladder 4.case statement
1. simple –if:
Syntax: Example:
if condition then if n>0 then
statements; dbms_output.put_line(‘positive number’);
end if; end if;

2. if - else:
Syntax: Example:
if condition then if n>0 then
statements; dbms_output.put_line(‘positive number’);
else else
statements; dbms_output.put_line(‘negative number’);
end if; end if;

3. if – elsif (elsif ladder):

Syntax: Example:
if condition then if day==1 then
statements; dbms_output.put_line(‘Monday’);
elsif condition then elsif day==2 then
statements; dbms_output.put_line(‘Tuesday’);
elsif condition then elsif day==3 then
statements; dbms_output.put_line(‘Wednesday’);
....................... end if;
end if;

13
III BSc, DBMS

4. Case statement :
Example:
Syntax: case day
case variable when 1 then
when value1 then dbms_output.put_line('Monday');
statements; when 2 then
when value2 then dbms_output.put_line(‘Tuesday’);
statements; when 3 then
………………………. dbms_output.put_line('Wednesday');
else else dbms_output.put_line(‘Invalid Choice’);
statements; end case;
end case;
Looping Statements: In looping statements, a block of code is executed no.of
times ,until condition is true. When condition is false then it exit the loop. Different
types of looping statements are:
1. Simple loop 2. While loop 3. For loop
simple –loop: It is called “exit control loop”. In this loop condition is given at end
of loop.
Syntax: Example:
loop i:=1;
statements; loop
exit when <condition> dbms_output.put_line(i);
end loop; i:=i+1;
exit when i>=5;
end loop;

while –loop: It is called “entry control loop”. In this loop condition is given at
begining of loop.

Syntax: Example:
while <condition> then i:=1;
statements; while i<=5 then
end loop; dbms_output.put_line(i);
i:=i+1;
end loop;

for –loop: It is called “entry control loop”. In this loop condition is given at
begining of loop.

14
III BSc, DBMS

Syntax: Example1:
for variable in[reverse] val1..val2 for i in 1..5
loop dbms_output.put_line(i);
statements; end loop;
end loop;

10Q. EXPLAIN OPERATORS AND PRECEDENCE OF OPERATORS IN PL/SQL.


ANS: Operators in pl/sql: Operators are symbols which are used to perform
arithmetic or logical operations. Operators are used along with variables to perform
various operation in pl/sql.
Different Operators in pl/sql are:
1. Assignment Operator
2. Arithmetic Operators
3. Relational Operators
4. Logical Operators
5. Comparision Operators
1. Assignment operator : It is used to assign the value to variable.
Ex: a: =10;
b: =20;
c: =a + b;
2. Arithmetic operators: These operators are used to perform arithmetic operations.
It returns a number values as output.
Example:
Operator Meaning Example
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ dividend a/b
3. Relational operators: These operators are used to check conditions. It can returns
either true or false.
Example:
Operator Meaning Example
= Equals a=b
!= Not Equals a!=b
< Less than a<b
<= Less than or equals a<=b
> Greater than a>b
>= Greater than or a>=b
equals

15
III BSc, DBMS

4. Logical operators: These are used to check two or more logical conditions. It returns

either true or false. For example, they are:


 And : it returns true, if all the conditions returns true.
 Or: It returns true, if any one of the conditions returns true.
 Not: It displays opposite status of given condition. i.e. , if the condition is false
then “logical not” returns “true”.
5. Comparison operators: These operators are used to display output based on user

requirement. Different comparison operators are


Like: It is used to compare character data in a table i.e. , ename like ‘S%’;
In: It is used instead of “multiple or conditions” i.e. , deptno in(10,20,30);
Between: It is used to display data between a range i.e., sal between 5000 and
15000;
Operator Precedence: BODMAS rule (Bracket Division Multiplication Addition
Substraction) rule is applied as operator precedence for evaluating arithmetic
calculations. Example: x=(10+5)/3
X=15/3 = 5

16

You might also like