0% found this document useful (0 votes)
1 views44 pages

Dbms Unit-5

The document provides an overview of PL/SQL, a procedural language extension to SQL developed by Oracle, detailing its structure, including the declaration, execution, and exception handling sections. It discusses the advantages and disadvantages of PL/SQL, such as support for SQL, better performance, and modularity, as well as the shortcomings of SQL. Additionally, it covers control structures in PL/SQL, including conditional constructs, iterative control, and sequential control statements.

Uploaded by

Arun
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)
1 views44 pages

Dbms Unit-5

The document provides an overview of PL/SQL, a procedural language extension to SQL developed by Oracle, detailing its structure, including the declaration, execution, and exception handling sections. It discusses the advantages and disadvantages of PL/SQL, such as support for SQL, better performance, and modularity, as well as the shortcomings of SQL. Additionally, it covers control structures in PL/SQL, including conditional constructs, iterative control, and sequential control statements.

Uploaded by

Arun
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/ 44

BSC-DBMS

UNIT-5
STRUCTURE OF PL / SQL
1) Explain about the structure of PL / SQL program?
PL / SQL:
 PL /SQL stands for procedural language extension to structured query language.
 PL/ SQL is a combination of sql along with the procedural features of programming
language.
 It was developed by oracle corporation in early 1990’s to enhance the capabilities of
SQL.
 PL/SQL incorporates many of the advanced features of programming languages that
was designed during 1970 and 1980’s.
 It is not a case sensitive language.
 PL/SQL is the super set of SQL.
 It fully supports SQL commands and datatypes.
 It allows the data manipulation and query statements of SQL to be included in
PL/SQL block structure.
 Oracle uses PL/SQL engine to processes the pl/sql statements.

PL/SQL BLOCK STRUCTURE:-

PL/SQL is a block structured language. It is a procedural approach to sql in which a


direct instruction is given to the pl/SQL engine to perform actions like
storing/fetching/processing data.

 The instructions are grouped together to from a block.


 In pl/sql the programs can divided into logical blocks.
 It consists of three sections (or) blocks. They are
1. Declaration section
2. Execution selection
3. Exception handling section

K.UMADEVI-AWDCKKD 1
BSC-DBMS

PL/SQL BLOCK STRUCTURE

DECLARE(optional)
Declaration statements;
BEGIN(Mandatory)
Execution statements;
EXCEPTION(optional)
Exception handling statements;
END;

1) DECLARATION SECTION;-

 This section starts with the keyword DECLARE.


 It is an optional section.
 It defines all variables, constants, cursors, subprograms and other elements to be used in
the program.
 It can be skipped if no declaration is needed.
 This section should be always followed by execution section.
2) EXECUTION SECTION;-
 This section is enclosed between the keywords BEGIN and END.
 It is the main and mandatory selection.
 It consists of the executable pl/sql statements of the programs.
 It contains both pl/sql code and sql code.
 It starts with the keyword BEGIN and ends with the keyword END.

3)EXCEPTION HANDLING SECTION:-

 This section starts with the keyword EXCEPTION.


 Any errors in the program can be handled in this section.
 It is an optional section.
 It handles runtime errors.
 It should be always followed by the key word END.

K.UMADEVI-AWDCKKD 2
BSC-DBMS

RULES:

 Place a semicolon(;) at the end of each statement.


 The keyword BEGIN, DECLARE, EXCEPTION are not followed by semicolons.
 When the block is executed successfully without errors, then the message output
should be as follows.
SQL> PL/SQL PROCEDURE SUCCESSFULLY COMPLETED

Example: /*largest of 2 numbers*/


declare
a number;
b number;
begin
a:=&a;
b:=&b;
if(a>b) then
dbms_output.put_line(a||‘is big’);
else
dbms_output.put_line(b|| ‘is big’);
end if;
end;
OUTPUT: 3is big
PL/SQL procedure successfully completed.

2) Write about the advantages of PL/SQL?

PL/SQL:- refer pl/sql definition in previous question.

ADVANTAGES OF PL/SQL:

i. SUPPORT FOR SQL:


 PL/SQL allows the use of all sql commands as well as all the SQL functions,
operators and datatypes.

K.UMADEVI-AWDCKKD 3
BSC-DBMS

ii. BLOCK STRUCTURE:


 PL/SQL is a block structured language.
 Each program written in PL/SQL is written as a block.
 Blocks can also be nested.
 Each block is meant for a particular task.
iii. BETTER PERFORMANCE:
 Without PL/SQL, oracle serves processing SQL statements one at a time.
 With PL/SQL, an entire block can be processed at a time.
 So, it improves the performance.
iv. MODULARITY:
 Modularity means divides an application into well defined modules.
 PL/SQL allows process to be divided into different modules such a
procedures and functions, called subprograms.
v. CONTROL STRUCTURES:
 PL/SQL allows control structure like if statements, for loop, while loop can
be used in the block.
vi. PORTABLILITY:
 Applications written in PL/SQL are portable to any platform on which oracle
runs.
vii. ERROR HANDLLING:
 PL/SQL handles errors (or) exceptions effectively during the execution of
PL/SQL program.
viii. INTEGRATION:
 PL/SQL is the product of oracle corporation.
 So, it integrates well with SQL.
 Plus and other application developments products of oracle.
DISADVANTAGES:
The disadvantages of PL/SQL
1. Poor I/O features
2.Insufficent memory 3. Proprietary to oracle

K.UMADEVI-AWDCKKD 4
BSC-DBMS

3) Write about disadvantages (or) short coming in SQL?


SQL: Structured query language can be defined as a domain specific language used to
manage the relational databases and performs different operations on data stored in them.

ADVANTAGES: Some of the advantages in SQL are

a) NO CODING NEEDED:
It is very easy to manage the database system without any need to write the large
amount of code by using the standard SQL.
b) WELL DEFINED STANDARD:
It has well defined standard like ISO & ANSI.
c) PORTABILITY:
SQL can be used in the program like pcs, servers laptops and even some of the
mobile phones.
d) INTERACTIVE LANGUAGE:
The domain languages can be used for communicating with the database and
receive answer to the complex question in seconds.
e) MULTIPLE DATA VIEWS:
With the help of SQL language the users can make different views of database
structure and database for the different users.

DISADVANTAGES OF SQL: The SQL also has some certain disadvantages

a) DIFFICULT INTERFACES:
SQL has a complex interface that makes it difficult for some users to access it.
b) PARTIAL CONTROL: The programmer who use SQL does not have a full
control over the database because of hidden business rules.
c) IMPLEMENTATION:
Some of the database go to the popritery extension to standard SQL for
ensuring the vendor location.
d) COST:
The operating cost of some SQL versions makes it difficult for some
programmers to access it.
Different symbols in pl/sql

K.UMADEVI-AWDCKKD 5
BSC-DBMS

Symbol Meaning

+ addition operator

% attribute indicator

' character string delimiter

. component selector

/ division operator

( expression or list delimiter

) expression or list delimiter

: host variable indicator

, item separator

* multiplication operator

" quoted identifier delimiter

= relational operator

< relational operator

> relational operator

@ remote access indicator

; statement terminator

- subtraction/negation operator

:= assignment operator

=> association operator

|| concatenation operator

** exponentiation operator

<< label delimiter (begin)

>> label delimiter (end)

/* multi-line comment delimiter (begin)

K.UMADEVI-AWDCKKD 6
BSC-DBMS

Symbol Meaning

*/ multi-line comment delimiter (end)

.. range operator

<> relational operator

!= relational operator

~= relational operator

^= relational operator

<= relational operator

>= relational operator

-- single-line comment indicator

4)Explain about control structures in PL/SQL?


CONTROL STRUCTURE:
 PL/SQL offers a range of constructs that allows to control the flow of processing.
 We can change the logical flow of statements with in the PL/SQL block with a number
of control structure
 There are four types of PL/SQL control structures
They are
1. Conditional constructs with if statement (conditional)
2. Case expression (conditional)
3. Loop control structures (iterative)
4. Sequential control
a) IF STATEMENT:
 They structure of PL/SQL if statement is similar to the structure of if
statement in other procedural language.
 It allows to perform action based on condition
 There are three forms of if statements
i) IF-THEN-END IF
ii) IF-THEN-ELSE-END IF

K.UMADEVI-AWDCKKD 7
BSC-DBMS

iii) IF-THEN-ELSE IF-ENDIF


i) IF-THEN-ENDIF:
The general syntax is:
If condition then
Statements;
End if;

ii) IF-THEN-ELSE-ENDIF;
The general syntax is;
If condition then
Statements;
else
Statements;
End if;

iii) IF-THEN-ELSEIF-ENDIF:
The general syntax is
If condition then
Statements;
elseif condition then
Statements;
else
Statements;
end if;

Example: /*largest of 3 numbers using IF-ELSEIF*/

declare
A number;
B number;
C number;
Begin
A:=10;

K.UMADEVI-AWDCKKD 8
BSC-DBMS

B:=20;
C:=30;
if(a>=b) and (a>=c) then
dbms_output.put_line(A||‘is big’);
elsif(b>a) and (b>=c) then
dbms_output.put_line(B|| ‘is big’);
else
dbms_output.put_line(C|| ‘is big’);
end if;
end;
OUTPUT: 30 is big

PL/SQL procedure successfully completed.

B) CASE EXPRESSION:

 The PL/SQL case statement allows to execute a sequence of statements based on a


selected.
 A selector can be anything such as variable, function (or) expression.
 It compares the expression that is specified in one (or) more when conditions
 it has two forms they are
i) simple case statement
ii) searched case statement

i)SIMPLE CASE STATEMENTS:

Syntax: case selector

When value-1 then


Statements;
When value-2 then
Statements;
..…………..……..
.…………………..

else

K.UMADEVI-AWDCKKD 9
BSC-DBMS

Statements;
end case;

iii) SEARCHED CASE STATEMENTS:


Syntax:
Case
…………………………….
…………………………….
……………………………..
else
Statements;
end case;

Example: /*case expression*/


declare
A number:=&a;
begin
case a
when 1 then
dbms_output.put_line(‘value=1’);
when 2 then
dbms_output.put_line(‘value=2’);
else
dbms_output.put_line(‘invalid value’);
end case;
end;

OUTPUT: Enter value for a: 2


old 2: A number:=&a;
new 2: A number:=2;
value=2
PL/SQL procedure successfully completed.

K.UMADEVI-AWDCKKD 10
BSC-DBMS

5. Explain about iterative control in PL/SQL?

ITERATIVE CONTROL STRUCTURES:


These are also called as looping control structures these are used to repeated the
execution of one (or) more statements for a specified no.of times.
PL/SQL provides the following types of loops:
a) Basic / simple loop
b) While loop
c) For loop
a) SIMPLE LOOP:
 It is the simplest form of loop statement.
 It encloses a sequence of statements between the keywords ‘LOOP’ and
‘END LOOP’.
 It allows the execution of the statements at least once, even if the condition
is false.
 Without the exit statement, the loop would be in finite (or) endless.

EXIT STATEMENTS:

 it is used to terminate a loop.


 The exit statement must be placed inside the loop.
 When clause is used to define a condition in this statements
 When the exit statement is encountered the condition in the when clause is
evaluated
Syntax:loop
Statements;
……………….
……………….
exit (when condition);
end loop

Example: declare
i number;
begin

K.UMADEVI-AWDCKKD 11
BSC-DBMS

i :=100;
loop
dbms_output.put_line(i);
i:=i+1;
exit when i>110;
end loop;
end;

b) WHILE LOOP:
 This loop is used to repeat a sequence of statements until the condition is
false.
 The condition is evaluated at the start of each iteration.
 The loop terminates when the condition is false

Syntax: while condition loop

Statements;

…………………..

End loop;

Example: /*while loop*/

declare
i number;
begin
i:=20;
while i<=30 loop
dbms_output.put_line(i);
i:=i+1;
end loop;
Output: 20 21 22 23 24 25 26 27 28 29 30
PL/SQL procedure successful completed

C) FOR LOOP:

 This loop is used to repeat a sequence of statement until the condition is false.
 The condition is evaluated at the start of each iteration.

K.UMADEVI-AWDCKKD 12
BSC-DBMS

Syntax: for counter in [reverse]<lowerbound>..<upper bound>

statements;
……………….
end loop;
Counter: It is an implicitly declared integer variable whose value automatically increase
(or)decreases.
REVERSE: It is used to decrement the iteration in for loop.
LOWER BOUND: it specifies a minimum value in a given range.
UPPER BOUND: It specific a maximum value in a given range.
Example: /*for loop*/
Declare
i number;
begin
for i in 1..10 loop
dbms_output.put_line(i);
end loop;
end;
Output: 1 2 3 4 5 6 7 8 9 10
PL/SQL procedure successfully completed.
6.Write about sequential control statements in PL/SQL?
Sequential control statements constructors:
These are also called as unconditional control statements. By default all PL/SQL blocks are
executed in a top down sequential process.
The process begins with a begin statement and ends with a END statements so to
change the sequence conditional statements.
1) Go to
2) Null
1) GOTO STATEMENT:
The GOTO statements immediately transfers program control to the label name
unconditionally.
The statements (or) label name must be unique in the block.

K.UMADEVI-AWDCKKD 13
BSC-DBMS

Syntax:
Goto<<label name>>;
Example: /*goto*/
begin
dbms_output.put_line(‘HI’);
goto abc;
dbms_output.put_line(‘HELLO’);
<<abc>>
dbms_output.put_line(‘BYE’);
end;
2)NULL STATEMENTS:
The NULL statements does nothing other than pass control to the next
statements.
In some cases, if you want to tell PL/SQL to don nothing then in such cases the null
statements to be used.
SYNTAX: null;
Example: /*program for null statements*/
Declare
a number;
begin
a:=&a;
if a mod 2!=0 then
dbms_output.put_line(‘number is odd’);
else
null;
end if;
end;
output: Enter value for a: 1
old 4: a:=&a;
new 4: a:=1;
number is odd PL/SQL procedure successfully completed.

K.UMADEVI-AWDCKKD 14
BSC-DBMS

7.Write about datatypes in PL/SQL?


PL/SQL: refer introduction part in 1st question
PL/SQL: refer SQL datatype replace PL/SQL in place of SQL
8.Write about the operator precedence in PL/SQL?
OPERATOR PROCEDURE:
 Operator precedence determines the grouping of terms in an expression.
 Certain operators have higher precedence than others, for example: the
multiplication operator has higher precedence than the addition operator.
 The operator within an expression are done in a particular order depending on
their priority.
For example: x=7+3x2
Here, if the operator ‘x’ has higher precedence then ‘+’ then it can be evaluated as follows.
X=7+3x2
X=7+6
X=13
The following tables shows the default order of operations form higher priority to lower
priority.

Operator Operation

+, - identity, negation

*, / multiplication, division

+, -, || addition, subtraction,
concatenation

=, !=, <, >, <=, >=, <>, ^=, IS NULL, LIKE, comparison
BETWEEN, IN

NOT exponentiation, logical negation

AND conjunction

OR disjunction

** Exponentiation

K.UMADEVI-AWDCKKD 15
BSC-DBMS

Example: consider the following expression.


X=(5+12)/4
X=17/4
X=4.25

9.Write about type and % type in PL/SQL?


%Type:
 To avoid type and size conflict between a variable and a column of a table ,the
attribute % type is used.
 The % type attribute is used to declare a constant, variables etc.
 Item declared with % type is called as referencing item and the previously declared
item is called as referenced item.
 The referencing item inherits the following from the referenced item.
1) Datatype and size
2) Constraints
 The referencing item does not inherit the initial value of the referenced item.

Example: r circle radius %type


Here r referencing item
Circle table name
Radius column name (referenced item)

Example: /*example for % type*/


declare
eno emp.empno%type;
name emp.ename%type;
dno emp.deptno%type;
salary emp.sal%type;
begin
Select empno,ename,deptno,sal into eno,name,dno,salary from emp where
emp.empno=7369;

K.UMADEVI-AWDCKKD 16
BSC-DBMS

dbms_output.put_line(‘employee no’||eno);
dbms_output.put_line(‘employee name’ ||name);
dbms_output.put_line(‘employee salary’ ||salary);
end;
Output: employee no7369
employee nameSMITH
employee salary800
PL/SQL procedure successfully completed.

% ROW TYPE:

 The row type attribute provides a record type that represents a row in a
database table.
 The record can store an entire row of data selected from the table (or) fetched
from a cursor (or) cursor variable.
 Example: x emp % row type;
Here the variable ‘x’ can store all the columns data of emp table.

/*program for % row type*/

declare
e emp%rowtype;
begin
select * into e from emp where empno=7369;
dbms_output.put_line(‘employee no’ ||e.empno);
dbms_output.put_line(‘employee name’ ||e.ename);
dbms_output.put_line(‘employee deptno’ ||e.deptno);
dbms_output.put_line(‘employee salary’ ||e.sal);
end;
output: employee no7369
employee nameSMITH
employee deptno20
employee salary800

PL/SQL procedure successfully completed.

K.UMADEVI-AWDCKKD 17
BSC-DBMS

10.Write about exception handling in PL/SQL?


EXCEPTION IN PL/SQL:
 Error occurs during the program execution is called exception in PL/SQL.
 Runtime errors (or) exceptions arise from design faults, coding mistakes,
hardware failures and many other sources.

EXCEPTION HANDLING:

 Exception block in PL/SQL program takes an appropriate action against the error
condition.
 when an error occurs, an exception is raised i.e the normal execution stops and the
control transfers to the exception handling path of the PL/SQL block.

ADVANTAGES:

Errors are handled conveniently without need to check the code.


* It improves readability
* It improves reliability
TYPES OF EXCEPTIONS: There are two types of exceptions in pl/sql.They are

1) pre-defined exception

2)user-defined exceptions

1) pre-defined exceptions:
 These are internally defined by runtime system.
 There are many pre-defined exceptions in PL/SQL which are executed when
any database rule is violated by the programers.
 The exception handling part is used when the exception occurs.

Syntax: exception

When <exception identifier1> then

Statements;

When <exception identifier 2> then

Statements;

K.UMADEVI-AWDCKKD 18
BSC-DBMS

Some of the pre-defined exception are

EXCEPTION NAME ERROR DISCRIPTION


1. CURSOR_ALREADY_OPEN It is raised when cursor is already opened
2. DUP_VAL_ON_INDEX Unique constraint vollated.
3. INVALID_CURSOR It is raised when attempts to open (or) close invalid
cursor
4. INVALID_NUMBER It is raised when the conversion does not exist

5. NO_DATA_FOUND It is raised when a select into statement returns no


values
6. TOO_MANY_ROWS It is raised when a select into statement returns
more then one row
7. ZERO_DIVIDE It is raised when divisor is equal to zero
8. VALUE_ERROR Numeric (or) value error
9. STORAGE_ERROR Out of storage
10. LOGIN_DENIED Login is failed
11. NOT_LOGGED_ON Connection failed
Example: /*exception handling*/

Declare
n number;
begin
n:=10/0;
exception
when ZERO_DIVIDE then
dbms_output.put_line(‘division by zero error’);
end;
Output: division by zero error
PL/SQL procedure successfully completed.

K.UMADEVI-AWDCKKD 19
BSC-DBMS

2.USER-DEFINED EXCEPTION:

 We can also define our own exceptions. These are declared and defined by user.
 These are declared in the declaration selection of PL/SQL blocks with their type as
exception.
 They must be raised explicitly using the raise statement.

The following statements are used to define user defined exceptions:

i. Declaring an exception in declaration selection.


ii. Raising an exception using raise command
iii. Handling an exception

RAISING AN EXCEPTION:

A user defined exception is raised explicitly by issuing the raise statement within the begin block.

Syntax: declare

<exception identifiers > exception;

begin

………………………………………

raise <exception identifiers>;

exception

when < exception identifiers> then

statements;

ends;

K.UMADEVI-AWDCKKD 20
BSC-DBMS

11.Explain about procedures in PL/SQL?


PROCEDURE:
 PL/SQL procedure is also called as stored procedure.
 It is a block in PL/SQL which is used to perform one (or) more specific tasks.
 It is just like procedure in other programming language.
 The procedure contains
 1.HEADER 2. BODY

HEADER: The header contains the name of the procedure and the parameter (or) the variable
passed to the procedure.

BODY: The body contains the declaration section, execution section, and exception section to
a general PL/SQL blocks.

CREATING A PROCEDURE:

 We can create a new procedure with the create procedure statement, which may
declare a list of parameter.
 The procedure must define the actions to be performed by the standard PL/SQL blocks.

PASSING PARAMETERS: we can pass parameters to procedure in three ways these are called as
modes .They are

i. IN PARAMETERS
ii. OUT PARAMETERS
iii. IN OUT PARAMETES

A procedure may (or) may not return any value

1) IN PARAMETER:
 These types of parameters are used to pass values to stored procedures.
 It is read only parameter.
2) OUT PARAMETER:
 These types of parameters are used to send output to stored procedure.
 It is similar to a return type in functions
 It is write only parameter.

K.UMADEVI-AWDCKKD 21
BSC-DBMS

3) IN OUT PARAMETER:
 It is Read-Write parameter.
 The syntax of creating procedure is

Create [ or replace] procedure procedurename [(parameter1 IN/OUT/IN OUT datatype


1; parameter 2 IN/OUT/IN OUT datatype 2…………………………….)]

Is/as

[declaration section]

begin

<procedure body>

exception

exception section

end[procedure name];

In the above syntax

 Create is a clause used to create to the procedure.


 Or replace option allows the modification of an existing procedure.
 Procedure is a keyword.
 Procedure name is the name of the procedure.
 The parameters list is optional.
 IN represents the value that will be passed from outside.
 OUT represent the parameters that will be used to return a value outside value
of the procedure.
 The default mode is IN.
 IS/AS specifies the beginning of the body of the procedure.

Example: /*procedure program*/

Create or replace procedure P(x number, y number) is


Z number;
begin

K.UMADEVI-AWDCKKD 22
BSC-DBMS

Z:=x+y;
dbms_output.put_line(‘sum is’ ||Z);
end P;
Output: Procedure created

EXECUTING A STAND ALONE PROCEDURE:

A stand alone procedure can be called in two ways

1) Using the execute keyword


2) Calling the name of the procedure from a pl/sql block.

1) EXECUTE:
The procedure can be executed by passing execute keyword.
Ex: sql> execute p(10,20);
2) CALLING A PROCEDURE:
A procedure can be called from any PL/SQL program by giving it names followed by
parameters.
Example:
To call the procedure ‘p’ the following statement will be written in a PL/SQL program.
/*calling procedure*/
Begin
p(10,20);
end;

output: sum is30

PL/SQL procedure successfully completed.

DROPING A PROCDURE: To drop a procedure, drop procedure statement is used

SYNTAX: drop procedure <procedure name>;

K.UMADEVI-AWDCKKD 23
BSC-DBMS

12.Explain about functions in PL/SQL (OR) subprogram?


FUNCTIONS:
 PL/SQL function is also called as stored functions
 it is a block in PL/SQL which is used to perform one (or) more specific tasks.
 it is similar to procedures.
 the main difference between procedure and a function is a function must
always a return value and procedure may (or) may not return a value.
 The function contains
1) HEADER 2) BODY

1) HEADER:
The header contains name of the functions and parameters passed to the function
and return clause is used to specify the return datatype.
2) BODY:
The body contains declaration, execution and exception section similar to general
PL/SQL block.

CREATING A FUNCTION:

 We can create a new function with the create function statements which
may declare a list of parameters.

 The function must contains a return statement. The function must define
the action to be performed by Standard PL/SQL block.

PASSING PARAMETER: We can pass parameter to functions in 3 ways

These are also called as modes they are

1) IN PARAMETER
2) OUT PARAMETER
3) IN/OUT PARAMETER

1)IN PARAMETER:

 These types of parameter are used to pass values to stored function

K.UMADEVI-AWDCKKD 24
BSC-DBMS

 it is a read only parameter

3) OUT PARAMETER:
These type of parameter are used to send output from stored functions.
It is a write only parameters.
4) IN/OUT PARAMETERS:
These type of parameter are used to pass values and send output to from function
Syntax:
The syntax of creating functions
Create or replace function function_name (parameter [IN/OUT/IN OUT] datatype)
return type
Is/as
<declaration section>
Begin
<function section>
Exception
<exception section>
End function_name;

In the above syntax


 Create clause is used to create & function [(or) replace] option allows
modifying an existing function.
 Function is a keyword.
 Function name is a name of the function (user defined).
 IN and OUT represents the values that are used to pass (or) send of in
functions.
 The parameters list is optional
 The default mode is IN.
 Return clause specifies that datatype that are going to return from the
function.
 IS/AS specifies the begin of the body.

K.UMADEVI-AWDCKKD 25
BSC-DBMS

/*function program*/

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


Z number;
begin
Z:=x+y;
return Z;
end;
Output:Function created
CALLING FUNCTION:

 A function can be called from any PL/SQL program by giving its name followed by
parameters.

 A function may accepts one (or) more parameters but returns a single value.

/*calling function*/

Declare
S number;
begin
S:=F(11,12);
dbms_output.put_line(‘sum is’ ||S);
end;
Output: sum is23
PL/SQL procedure successfully completed.
DROPPING A FUNCTION: To drop a function drop function statement is used.

SYNTAX: drop function <funcition_name>;

13.Explain the steps to write PL/SQL program?


PL/SQL:refer pl/sql program for introduction in 3 points (20/9)
STEPS TO PL/SQL PROGRAM:
STEP 1: open the sql window
Start programs oracle for window NT SQL plus 8.0
Any command in sql are to be given at sql prompt (SQL>)

K.UMADEVI-AWDCKKD 26
BSC-DBMS

STEP 2: to write a PL/SQL program


SQL> Ed programname.SQL;
SQL>Ed addition.SQL;
STEP 3: The notepad opens, type the PL/SQL program

/*addition of two numbers*/


Declare
a number;
b number;
c number;
begin
a:=2;
b:=8;
c:=a+b;
Dbms_output.put_line(‘sum is’ ||c);
End;
STEP 4: After typing the program, go to file menu and save the program by clicking save
option.
STEP 5: Exit the notepad.
STEP 6: To view the output of any PL/SQL program
SQL>set serveroutput on;
STEP7: before viewing the output execute the pl/sql program using ‘@’
SQL>@programname;

Example: SQL>@addition;
10/
Sum is 10
Pl/sql procedure successfully completed
After execution it displays errors if any (or) the below statement appears.
PL/SQL procedure successfully completed

K.UMADEVI-AWDCKKD 27
BSC-DBMS

RULES:
1) The programname should not have space.
2) Any message should be tybe between ‘________’ (single quotes)
3) Every line in the program ends with semicolon (;).
4) The output statement is Dbms_output.put_line

14.Explain about cursors in PL/SQL?


CURSORS:
 When an SQL statement is processed oracle creates a memory area know as
context area.
 A cursor is a pointer for context area. It contains all the information needed for
processing the statement.
 Cursor is a temporary working area created in a system memory that is used to
execute SQL statement and store information. In PL/SQL, the context area is
controlled by cursor.
 A cursor can hold more than one row but can process only row at a time.
 The set of rows that the cursor holds is called as active set.

TYPES OF CURSORS: There are two types of cursors inPL/SQL.

They are 1) IMPLICIT CURSORS 2)EXPLICIT CURSORS

1.IMPLICT CURSORS
 The implicit cursors are automatically generated by oracle while an SQL
statement is executed.
 These are created by default when DML statements like insert, update, delete
etc………. are executed.

IMPLICIT CURSOR ATTRIBUTES: Oracle provides some attributes know as implicit cursor attributes
to check the status of DML operations.These are used with SQL keyword. Some of them are

a) % FOUND
b) %NOTFOUND

K.UMADEVI-AWDCKKD 28
BSC-DBMS

c) %ROWCOUNT
d) %ISOPEN

A ATTRIBUTE DISCRIPTION EXAMPLE


%FOUND If returns true, if the DML statement SQL % FOUND
Like insert, delete and update affect at least one
row other wise
%NOTFOUND It returns true, if DML statements like insert, SQL %NOTFOUND
delete, update and select into statement do not
affect any row otherwise it returns false.
%ROWCOUNT It returns the number of rows affected by DML SQL %ROWCOUNT
operation (or) select into statement.
%ISOPEN It always returns false for implicit cursors because SQL %ISOPEN
the SQL cursor is automatically closed after
executing to SQL statements

2.EXPLICIT CURSORS:
 These are defined by the programmers to gain more control over the context
area.
 These cursors should be defined in the declaration section of PL/SQL.
 It is created on a select statements which returns more than one row.

Steps to create explicit cursor:The following steps used to create explicit cursors.

Step 1: declare the cursor to initialized in the memory.

Syntax: cursor <cursor_name> is <select_statement>;

Here cursor_name is defined by the user.

Cursor is a keyword.

Select statement is used for select query which returns multiple rows.

STEP 2: open the cursor to allocate memory.

Syntax: open <cursor_name>;

K.UMADEVI-AWDCKKD 29
BSC-DBMS

STEP 3: Fetch the cursor to retrieve the data

Syntax: fetch<cursor_name>into<var_list>;

Step 4: close the cursor to release the memory.

Syntax: close<cursor_name>;

Explicit cursor attributes:

 Oracle provides some attributes known as explicit cursor attributes to control


the data processing while using cursors.

 These attributes are used to check the status of the explicit cursor.

These are used with cursor_name.

ATTRIBUTE EXAMPLE
1. %FOUND Cursor_name %found
2. %NOTFOUND Cursor_name %notfound
3. %ROWCOUNT Cursor_name %rowtype
4. %ISOPEN Cursor_name %isopen

/*explicit cursor*/

Declare
no emp.empno% type;
name emp.ename%type;
salary emp.sal%type;
cursor c1 is select empno, ename, sal from emp where sal>2000;
begin
open c1;
loop
fetch c1 into no, name, salary;
exit when c1%notfound;
dbms_output.put_line(no||’ ‘||name||’ ‘|| salary);
end loop;
close c1;
end;
ouput:7839 KING 5000
7698 BLAKE 2850
7782 CLARK 2450

K.UMADEVI-AWDCKKD 30
BSC-DBMS

7566 JONES 2975


7788 SCOTT 3000
7902 FORD 3000

PL/SQL procedure successfully completed.

15.Explain about package in PL/SQL?


PACKAGE:
A package is a database object that groups logically related PL/SQL objects such as
procedure, functions, variables cursors and type declaration into a single unit.
The entire package is loaded into the memory when a procedure (or) a function with
in the package is called for the first time.
PL/SQL package is stored in the oracle database and can be used by many applications.
Advantages:
 Modularity
 Easier application design
 Information hiding
 Added functionality
 Better performance
Components of package:
a package basically has two components
they are 1) PACKAGE SPECIFICATION 2)PACKAGE BODDY
1) PACKAGE SPECIFICATION:
 It consists of a declaration of all the public variables, cursors, procedures,
functions and exception.
 To create a package, use the ‘create package’ statement.

Syntax:
Create [or replace] package package_name
{is/as}
<procedure_specification>;

K.UMADEVI-AWDCKKD 31
BSC-DBMS

<function_specification>;
<variable_declaration>;
<cursor_declaration>;
<exception_declaration>;
end [package_name];

Here
 package is keyword.
 package_name is defined by the user.
The elements which are all declare in the specification can be accessed form
outside of the package. Such elements are known as public elements.

Example:
/*package specification*/
create or replace package pack as procedure pro (no emp.empno%type);
function fun (x number, y number) return number;
End pack;
Output: Package created

2) PACKAGE BODY:
 It consists of definition of all the elements that are present in the package
specification.
 It fully defines cursors, procedures and functions declared in the package
specification.
 It can also have private elements that are not declared in package specification.
To create package body, use the ‘create package body statement.

Syntax:
Create [or replace] package body package_name
{is/as}
<global declaration part>;

K.UMADEVI-AWDCKKD 32
BSC-DBMS

<private element definition>;


<procedure definition>;
<function definition>;
…………………………………….
Begin executable statements;
Exception
Exception statements
End;
End[package_name];
Referencing package elements:
All the public element of the package can be referred by calling the package name
followed by the element name separated by period(.)
Syntax:<package_name>.<element_name>;
Example: SQL>execute pack.pro(2);

16.Explain about triggers in PL/SQL?


TRIGGER:
Trigger is invoked by oracle engine automatically whenever a specified event occurs.
Trigger is stored into database and invoked repeatedly when specific condition match.
Triggers are written to be executed in response to any of the following event occurs.
1) A database manipulation (DML) statements (delete, insert (or) update)
2) A database definition (DDL) statements (create, alter (or) drop)
3) A database operations (server error, logon, logoff etc)
4) Trigger would be defined on tables, views etc…,

Advantages:

a) Enforces referential integrity.


b) Event logging and storing information on table access.
c) Auditing
d) Synchronous replication of tables
e) Preventing invalid transactions
f) Trigger generates some derived column values automatically

K.UMADEVI-AWDCKKD 33
BSC-DBMS

g) Imposing security authorizations.

Creating a trigger:

The trigger can be created as follows.

Syntax:Create [or replace] trigger triggername

Before [after/instead of]


[insert (or) /update (or)/delete]
[of col_name]
On table_name
[referencing old as a new as n]
[for each row]
When <condition>
Declare
Declaration_statement
Begin
Executable_statement
Exception
Exception_statements
End;
In the above syntax

Create (or) replace: It creates or replaces an existing trigger with the trigger_name.
Before/ater/instead of:This specifies when the trigger would be executed trigger on a
view.
Insert (or) /update(or)/delete:it specifies the DML operations.
Of col_name:This specifies the column name that would be updated
On table_name:This specifies the name of the table associated with the trigger.
Referencing old as a new as n:It refers to the old and new values for various DML
statements.
: old and :new are used to refer the columns.
Example: :old.col_name
:new.col_name

K.UMADEVI-AWDCKKD 34
BSC-DBMS

For each row:it specifies a row level trigger i.e the trigger would be executed for each row
being effected
when <condition>:it refers to the condition for rows for which the trigger would fire.
Types of triggers:depending upon the execution of a trigger it may be classified as
statement_level trigger(table)
 Row_level trigger
 Before trigger
 After trigger
 Instead of trigger
1) Statement_level trigger:
The trigger would be executed when delete (or) insert (or) update are applied on the
table.
2) Row_level trigger:
This trigger is fired when for each row statement is executed
3) Before trigger:
This trigger is fired before the certain action is performed
4) After trigger:
This trigger is fired after the certain action is performed
5) Instead of trigger:
This trigger is fired instead of performing the particular action
/*before trigger*/
Create or replace trigger t1
Before insert on emp
For each row
Begin
:new.ename:=upper(:new.ename);
End;
Output: Trigger created

K.UMADEVI-AWDCKKD 35
BSC-DBMS

16.Write about composite datatype in PL/SQL?


COMPOSITE DATATYPE:
A composite datatype stores values that have internal components. We can pass entire
composite variable to subprogram as parameters. These are know as
Collections:
Which represents a collection of components that can be manipulated individually.
Example: records, tables. Etc…………….
PL/SQL RECORDS:
 Records are composite datatype which means it is a combination of different
scalar datatypes like a char, varchar number etc……..
 Each scalar datatypes in the record holds a values.
 A record can be visualized as a row of data.
 it can contain all the context of a row.
 PL/SQL records provides a way to deal with separate but related variable as a
unit.
 PL/SQL records is a variable that may contain a collection of separate values
each individually addressable.

Defining a record type:

The record type has to be defined before its record can be declared i.e to declare a
record you must first define the record type (a composite type ) then declare a record for
that type.

Syntax: Type record_type_name is record

(first_col_name column datatype, second_col_name column datatype,………………);

IN THE SYNTAX:

 ‘Record_type_name’ it is the name of the record type you want to define.


 First_col_name, second_col_name………………….name of the field columns within the
record.
 Column_datatype_define the scalar datatype of the fields/columns.

K.UMADEVI-AWDCKKD 36
BSC-DBMS

Declaring a record:
Syntax to declare a record of a user defined record type is

Record_namerecord_type_name;
Declare
Type pks is record
{
Snoemp.eno%tyhpe;
Name emp.ename%tyhpe;
Salary emp.sal%type;
};
p, pks
begin
select eno, ename, sal into p, form emp where eno=1;
dbms_output.put_line(‘employe_no’||’ ‘||name:’||p.name||’ ‘||sal: ||p.salary);
end;
17.Explain about fundamental |(or) language element of PL/SQL?
FUNDAMENTAL OF PL/SQL:
Like every other programming language PL/SQL has a set of elements. These elements are
used to represent real world objects and operation.
They are
1) Character set
2) Reserved words
3) Delimiters
4) Identifiers
5) Literals
6) Lexical units
1) Character set:
PL/SQL programs are written as lines of text using a specific set of characters.
The PL/SQL character set includes
A-Z (or) a-x letters/ alphabets

K.UMADEVI-AWDCKKD 37
BSC-DBMS

0-9 numbers
Specific symbuls( ), +, -, /, <>……….

2) Reserved words: (KEY WORDS)


Reserved words have special syntactic meaning to PL/SQL and so it cannot be
redefined
Example: begin, end, exception, package etc…

3) DELIMETERS:
Delimiters are simple (or) compound symbols that have special meaning to PL/SQL.

SYMBOL MEANING
< > Not equal to
+, -, /, * Arithmetic operation
@ Remote access indicator
-- Single line comment
|*………….*| Multi line comment
:= Assignment operator

4) Identifiers:
Identifiers refers to the programs items and units, which include constants, variable,
exception, cursors, subprograms, packages etc……
Identifiers can contain upto 30 characters, but they must start with an alphabetic
characters.

5) Literals:
Literals are the explicit numeric character string (or) Boolean values which are not
represented by an identifiers. TRUE, NULL etc… are all the literals of the type
Boolean.
The different types of literals are:

K.UMADEVI-AWDCKKD 38
BSC-DBMS

Numeric literals – 23, 45….


Character literals – ‘A’, ‘%’, ‘9’
String literals- “uma”
Boolean literals – true, false, etc
Data and time literals – 20-oct-2017

6) Lexical units:
A line of PL/SQL contains group of characters known as lexical unit, which can be
classified as follows
 Delimiters
 Identifiers
 Literals
 Comments

18.Write about variable and constant in PL/SQL?


VARIABLE:
A variable is a name used to store data temporarily during the execution of code.
Each variable has a specific datatype, which determines specific range and value.
Variable can be used for the following
1) Temporary storage of data
2) Manipulation of stored values
3) Reusability

Syntax:

Variable_name datatype [notnull:=value];

In the above syntax

a) Not null is an optional specification on the variable


b) Value is also optional

Example: declare

Salary number(6);

K.UMADEVI-AWDCKKD 39
BSC-DBMS

Rules to declare variable:

1) A variable should not exceed 30 characters


2) It allows underscore and dollar signs
3) It needs to declare in the declaration section of a PL/SQL block.
4) Variable name are not case sensitive.
5) The keyword cannot be used as a variable name
6) The name must begin with letter
Initializing variable:
The variable which are initialized with other variables or values is called as
initialization. It can be done using assignment operator(:=)

Example:salnumber(3):=10000;
(or)
Sal:=&sal;
Example: write any PL/SQL program for essay
CONSTANT:
1) A constant is a value used I PL/SQL block that remains unchanged throughout
the program.
2) It is a user-defined literal value
3) It is also used with constant keyword
Syntax:var_name constant datatype:=value:
Example: p: constant float:=3.14;
EXAMPLE: WRITE RECORD PROGRAM FOR ESSAY

K.UMADEVI-AWDCKKD 40
BSC-DBMS

DBMS-V(A) IMPORTANT
QUESTIONS ESSAYS
1. Explain about File based System and its drawbacks?
2. Explain about architecture of DBMS
3. Explain about various Data Models?
4. Explain about EER Model?
5. Explain about the basic building blocks of ER-Model?
6. Explain about CODD Rules?
7. Explain about Relational Algebra and its operations?
8. Explain about DML & DDl commands?
9. Explain about Relational Set operators?
10.Explain about joins in sql?
11.Explain about Cursors in pl/sql?
12.Explain about procedures in pl/sql?
13.Explain about triggers in pl/sql?
14.Explain about Exception handling?

SHORTS
1. Write about the components of database?
2. List out the advantages of DBMS?
3. Write about the classification entity sets?
4. Write about the classification of attributes?
5. Write about the classification of relationships?
6. Generalization and Specialization?
7. Write about different types of keys?
8. Write about QBE?
9. Selection and projection operation?
10. Datatypes in sql?
11. Aggregate functions in sql
12. Constraints?
13. Structure of pl/sql
14. Advantages/features of pl/sql
15. Functions in pl/sql?
16. Constraints on Specialization and Generalization?

K.UMADEVI-AWDCKKD 41
BSC-DBMS

B.Sc(Computer Science)
Paper – DBMS
Previous Paper -1
Time:3 Hours Maximum marks:75
SECTION-A

I.Answer any five questions.


1.Briefly explain various objectives of DBMS.

2.Write about DBMS vendors and their products.

3.Explain about Building Blocks of Entity Relationship.

4.Write about set operations in SQL.

5.Explain about packages in PL/SQL.

6.Explain the evolution of DBMS.

7.Write about relational Integrity.

8.Write about the History of SQL.

SECTION – B

II.Answer All the questions.


9.a) Explain the Evaluation of Database Management system.

(OR)

b) Explain about Data Models.

10.b) Explain about classification of entity sets and Attribute classification.

(OR)

b) Discuss about generalization and specialization. What are the constraints on specialization and
generalization.

11.a) Explain about Codd’s relational database rules.

(OR)

b) Explain in detail about relational calculus.

12.a) Explain selection and projection operations with example.

(OR)

b) What is Constraint? Explain different types of constraints in SQL queries.

13.a) What are Cursor? Explain Various types of cursors in detail.

(OR)

b) Explain Exception handling mechanism in PL/SQL.

K.UMADEVI-AWDCKKD 42
BSC-DBMS

B.Sc(Computer Science)
Paper – DBMS
Previous Paper- 2
Time:3 Hours Maximum marks:75
SECTION-A

I.Answer any five questions.


1.What are the objectives of DBMS?

2.What the Building blocks of an entity relationship.

3.Advantages of Relational algebra.

4.What are the datatypes available in SQL?

5.Explain various control structures in PL/SQL.

6.Explain the components of Database Management System.

7.Aggregation and composition.

8.QBE.

SECTION – B

II.Answer All the questions.


9.a) Explain briefly about Database Management system.

(OR)

b) Explain the classification of DBMS.

10.a) What are the drawbacks of File based system?

(OR)

b) What are the advantages of Database Management System.

11.a) Discuss about Relationship degree and relationship classification.

(OR)

b) Briefly explain about Relational Data Model.

12.a) Write about selection and projection operations with example.

(OR)

b) Discuss in detail about DDL and DML commands with example.

13.a) Explain various control structures in PL/SQL.

(OR)

b) What is a Trigger? Explain different types of triggers in PL/SQL.

K.UMADEVI-AWDCKKD 43
BSC-DBMS

B.Sc(Computer Science)
Paper – DBMS
Previous Paper- 3
Time:3 Hours Maximum marks:75
SECTION-A

I.Answer any five questions.


1.Write about the drawbacks in File based System.

2.Write about entity clusters.

3.Write about CODD rules.

4.Write a brief note on aggregate functions.

5.Write about data types in PL/SQL.

6.Write about generalization.

7.What is a view? Write the procedure to create a view.

8. Write about sub query.

SECTION – B

II.Answer All the questions.


9.a) Explain in detail about advantages and disadvantages of DBMS.

(OR)

b) Explain in detail about database architecture.

10.a) What are the basic building blocks of ERM.

(OR)

b) What is relationship? Explain classification and degrees of Relationship.

11.a) Explain the advantages and disadvantages of relational algebra.

(OR)

b) Explain the concept of relational calculus.

12.a) Explain in detail about DDL, DML and DCL commands.

(OR)

b) Explain join and set operation with example.

13.a) Explain the structure of PL/SQL program

(OR)

b) what is trigger? Explain operations on triggers.

K.UMADEVI-AWDCKKD 44

You might also like