—
NB.Sc, COMPUTER
———eerer
Introduction, Structure of PL/SQL |
@ PL/SQL Language Elements, Data types.
Operators precedence, Control Structure. |
# Create a PL/SQL Program, Iterative Control.
@ Procedure, Function Database Triggers.
SHORT ANSWER TYPE QUESTIONS |
What is PL/SQL? |
PL/SQL stands for Procedural Language/Structured Query naan Is |
provided by Oracle asa procedural extension to SQL. SQL isa declarative language,
In SQL, the statements have no control to the program and can be executed in any
order. PL/SQL, on the other hand, is a procedural language that makes up for all the -
missing elements in SQL. PL/SQL arose from the desire of programmers to have a
language structure that wes more familiar than SQL's purely deciarative nature,
Write about Advantages of PL/SQL? WV?
1. Procedural language support : PL/SQL is a development tools not only for
data manipulation futures but also provide the conditional checking, looping or
branching operations same as like other programming language.
2. Error handling : PL/SQL is dealing with error handling, it's permits the smart |
way handling the errors and giving user friendly error messages, when the errors
are encountered
3. Declare variable : PL/SQL gives you control to declare variables and access
them within the block. The declared variables can be used at the time of query
processing. |
4. Intermediate Calculation : Calculations in PL/SQL done quickly and efficiently
without using Oracle engines. This improves the transaction performance. |
5. Portable application : Applications are written in PL/SQL are portable ii any
Operating system. PL/SQL applications are independence program to run any
computer.
Write about short comings in SQL?
SQL isa powerful tool for accessing the database but it suffers from some deficiencies |
as follows
a) SQL statements can be executed only one at a time. Every time to execute a
SQL statement, a call s made to Oracle engine, thus it results in an increase in
database overheads.y
(je GOMPUTER SCIENCE. seit
i
SS
: ee ee
hile processing an § SS
b) While Provessing an SQL statement If an error accurs, oracle generates ts
his some times ants
other meaningful ery orn
own erTor Message, whic}
to display some
for that.
difficult to under stand. [fa user wv
nessage, SQL dows not have provision
¢) SQL is not able to do the
Conditional ever means one cannot
use the control are staten vy on RDBMS, this
nents in SQL statements,
‘eedence in PL/SQL?
The operations within an ex)
their precedence (priority),
from top to bottom. Operato,
Write about operator pre;
Pression are done in a particular order depending on
Table below lists the operator's level of precedence
ts listed in the same row have equal precedence
Operators with higher precedence are applied first, but if parentheses are used,
expression within innermost Parenthesis is evaluated first
Order of Operations
od operation
** NOT Ce 4
‘ponentiation, logical negation
|
identity, negation
multiplication, division
addition, subtraction, concatenation
comparison
LIKE, BETWEEN, IN
AND conjunction -|
OR disjunction
What is Procedure in PL/SQL? Write advantages of procedures and functions.
A procedure is a subprogram that performs some specific task, and stored in the
data dictionary. A procedure must have a name so that it can be invoked or called by
any PL/SQL program that appears within an application, Procedures can take |
Parameters from the calling program and perform the specific task. Before the
procedure or function is stored, the Oracle engine parses and compiles the procedure
or function. |
Benefits of Procedures and Functions : Stored procedures and functions have
Many benefits in addition to modularizing application development. |
- Itmodifies one routine to affect multiple applications,
Itmodifies one routine to eliminate duplicate testing.
Itensures that related actions are performed together. Or not at all, by doing the
activity through a single path.
Ttavoids PL/SQL parsing at runtime by parsing at compile time
Itreduces the number of calls to the database and database network traffic by
bundling the commands.
—I1B.Sc, COMPUTER SCIENCE - SEM3
102 $a |
6., What is the diff
A
aon)
rence between procedure and function
Function
Procedure =
subprogram that | A function is a subprogram that can
accept parameters, compute a value and
1. A procedure ts
can accept parameters, perform
an action and return parameters return that value to caller
A procedure may return no value } 2. A function must return only one value
_ A function can return a value as direct
output of the function call
4, Generally we use a function to compute
3. A procedure cannot return a
value as direct output
4. Generally we use a procedure to
perform an action a value |
What are Packages? Write advantages of packages?
‘an be defined as a collection of related pro:
sociated cursors and variables together as a unit in the
package is a group of related procedures and functions
as well as local procedures and
A package ci gram objects such as
procedures, functions, and a:
database. In simpler term, a
stored together and sharing common variables,
functions.
Advantages of packages :
_ You can create package to store all related functions and procedures are grouped |
together into single unit called packages.
_ Package are reliable to granting a privileges.
All function and procedure within a package can share variable among them.
. Package are support overloading to overload functions and procedures.
. Package are improve the performance to loading the multiple object into memory
at once, therefore, subsequent calls to related program doesn't required to calling |
physically I/O.
6. Package are reduce the traffic because all block execute all at once.
er aes _
LONG ANSWER TYPE QUESTIONS
Explain about Basic Structure of PL/SQL program?
Structure of PL/SQL: PL/SQL is a 4GL (fourth generation) programming language.
Itoffers all features of advanced programming language such as portability, security,
data encapsulation, information hiding, etc.
PL/SQL isa block structured language. This means a PL/SQL program ts made
up of blocks, where block is a smallest piece of PL/SQL code having logically
related statements and declarations. A block consists of three sections namely :
Declare, Begin, and Exception followed by an End statement. We will see the
different sections of PL/SQL block.gq, COMPUTER SCIEN —
ee SCIENCE - SEM3
DECLARE
Declarations of variables, constant:
Ss
elc., 10 be use in PL/SQL
BEGIN f
PL/SQL and SQL Executable
statements
EXCEPTION
PL/SQL code to handle errors
during execution period.
END;
. Declare Section :
1 tion : Declare section declares the variables, constants, Processes,
functions, etc., to be used in the other parts of program. It is an optional section.
| 2, Begin Section : It is the executable section. It consists of a set of SQL and PL’
SQL statements, which is executed when PL/SQL block runs It is a compulsory
section.
| 3. Exception Section : This section handles the errors. which occurs during
| execution of the PL/SQL block. This section allows the user to define his/her own
error messages. This section executes only when an error occurs. It is an optional
section,
4. End Section : This section indicates the end of PL/SQL block.
Every PL/SQL program must consist of at least one block, which may consist of
| any number of nested sub-blocks.
E.g.
‘om the user.
PL/SQL code to print sum cof two numbers taken fr
| SQL > SET SERVEROUTPUT ON:
SQL > DECLARE
~- taking input for variable a
ainteger : = & a:
--taking input for variable b
b integer := &b:
c integer :
BEGIN
c:zatb;
dbms_output. put_line ('Sum of a |'and | biis=‘e):A
[WB.se. compuTER SCIENCE - SEM a |[104]|
2
9 ]
Briefly explain abottt Lexical units in PL/SQL |
characte |
Lexical Units: A tine of PL/SQL program contains groups oF eharacters knoys, |
as lexteal units, which can be classified as follows
1. Delimiters, 2. Identifiers, 3, Literals, 4, Comments
1. Detimiters A delimiter isa simple or compound symbol pea Special
Meaning to PL/SQL. Simple symbol consists of one character, while compoung
symbol consists of more than one character. PL/SQL supports following simple
symbol delimite
t—#1=> <5 %' (@i"
Compound symbol delimiters legal in PL/SQL are as follows :
>! a
=
>
2. Identifiers : Identifiers are used in the PL/SQL programs to name the PL SQi
Program items as constants, variables, cursors, cursor variables. subprograms, ete
PL/SQL Identifiers follow the following rules :
1. Identifiers can consists of alphabets, numerals, dollar signs, underscores and
number signs only.
An identifier must begin with an alphabetic letter optionally followed by one or
more characters (permissible in identifier).
- An identifier cannot contain more than 30 characters.
4. An identifier cannot be reserved word.
Some of the valid identifiers are as follows :
A, Al and so on
3. Literals : A literal is an explicity defined character, string, numeric, or Boolean
value, which is not represented by an identifier.
i) Numeric Literals ; A numeric literal is an integer or a real value. An inte
literal may be a positive, negative, or urisigned whole number without a decimal
point. Some examples of integer numeric literals are as follows :
100 006 -10 0 +10
Areal lieral is a positive, negative, or unsigned whole or fractional number with |
a decimal point. Some examples of real integer literals are as follows
0.0 -19.0 3.56219 +43.99 © 7 456
Numeric literals can also contain exponential numbers. Some examples of |
exponential numeric literals are as follows : |
7E3 2.0E-3 3.141591 -2E33 -8.3e-2 |
Where, E stands for "times ten to the power of”
ii) Character Literals + A character literal is an individual character enclosed bY
single quotes. Character literals include all the printable characters in the PL/SQL |
character set: letters, numerals, spaces, and special symbols. Some examples 0! |
character literals are as:follows |
aqp.Se. COMPUTER SCIENCE -SEM3 |[t05
(9S SEM IL 105 :
- Ae SG —
PI. SQL 1s case ser
sive within character literals
A string literal is enclos
clers, Some examples
‘Good Moming!' 'TATA INFOTI
iii) String Literals
of one or more char:
consist
ed within single quotes and may
of String literals are as follows
ECH LID!
All string literals are of character data type.
PL/SQL is case sensitive within str ing literals.
iv) Boolean Literals :
Boolean literals are the predefined values TRUF, FALSE.
| and NULL. Keep in mind Boolean literals are values, not strings. For example a
condition: 1f (x=10) is TRUE only for the value of x equal to 10. for any other value
of x it is FALSE and for no value of x it is NULL.
4. Comments : Comments are used in the PL/SQL program to improve the
readability and understandability of a program. A comment can appear anywhere 1n
the program code. The compiler ignores comments. A PL/SQL comment may be a
| single-line or multiline.
i Single-Line Comments
Single-line comments begin with a double hyphen (-) anywhere on a line and extend
to the end of the line
E.g. — start calculations
i) Multiline Comments
Multiline comments begin with a slash-asterisk (/*) and end with an asterisk-slash
(*/), and can span multiple lines.
E.
* Hello World! This is an example of multiline comments in PL/SQL *
:xplain about various datatypes using in PL/SQL? ~ MO ©
Every constant and variable has a datatype. A datatype specifies the space to be
reserved in the memory, type of operations that can be performed, and valid range
of values. PL/SQL supports all the built-in SQL datatypes. Apart from those
datatypes, PL/SQL provides some other datatypes. Some commonly used PL/SQI
| datatypes are as follows :
1. NUMBER : The NUMBER datatype to store fixed or floating point number of
Virtually any size. You can specify precision, which is the total number of digits, and
| scale, which determines where rounding occurs.
| Syntax : NUMBER [(precision, scale)]
| You cannot use constants or variables to specify precision and se
ale; you must use
an integer literals.
| 2. CHAR: You use the CHAR datatype to store fixed-length character d
| CHAR datatype takes an optional parameter that lets you specify
| up to 32767 bytes.
| Symray » CHAR[(maximum_length)]
ata. The
amaximum length[WB.Se. COMPUTER SCIENCE
A.
~*~
PUSaL
106
3. VARCHAR 2: You use the VARCHAR2 datatype to store variable-lengy
character data. The VARCHAR2 pe takes a required parameter that lets
You specify a maximum length up to 32767 bytes:
Syntax » VARCHAR2 (maximum _length) i
4. DATE: You use the DATE datatype to store fixed-length data values. The
DATE datatype takes no parameters. Valid dates for DATE variables include January
1.4712 BC to December 31, 4712 AD.
S. BOOLEAN : One of the mostly used datatype is BOOLEAN. A BOOLEAy, |
datatype is assigned to those variables, which are required for logical operations, 4
BOOLEAN datatype variable can store only logical values, i.e., TRUE, FALSE,
NULI
6. “Type: The %TYPE attribute provides the datatype of a variable or database |
column. In the following example, %TYPE provides the datatype of a variable
balance NUMBER(8,2):
minimum_balance balance% TYPE;
In the above example PL/SQL will treat the minimum_balance of the same datatype
as that of balance. i.e, NUMBER(8.2).
7. YRowtype : The YROWTYPE attribute provides a record type that represents
a row in a table (or view). The record can store an entire row of data selected
from the table.
E.g. emp_rec is declared as a record datatype of emp table. emp_rec can store a
row selected from the emp table.
emp_rec emp%ROWTYPE;
Briefly explain about Variables and constants in PL/SQL?
Variables and Constants : Variables and constants can be used within PL/SQL |
block, in procedural statements and in SQL statements. These are used to store the
values. As the program executes, the values of variables can change, but the values
of constants cannot.
Variables and constants are declared in the Declaration section of PL/SQL block.
These can be any of the SQL data type like CHAR, NUMBER, DATE, ete.
1. Variables Declaration : The syntax for declaring a variable is as follows
identifier datatype;
E.g. DECLARE
Name VARCHAR2(10),
Age NUMBER(2);
Joining date DATE;-
‘cg SONPUTER SCIENCE. SEM |[T07][ pusal_
nitializing the V; — :
wt 8 ariable : By default variables are antialized t@ NUE
rime fo declaration. If we want toin 7e + sy nlx
jyould be as follows; itl the yale y same ae
at the
dentifier datatype = value;
Or:
jgentitier datatype DEFAULT value;
Eg: Joining_date DA’
‘OLIULY-99§ (ar)
DEFAULT ‘01 JULY-99',
3, Declaring Constants : Declaration of constant is similar 10 declaration of
variable, except the key-word CONSTANT precedes the datatype and it must be
initialized by some value. The syntax for declaring a constant 18 aS follows:
identifier CONSTANT datatype := value;
Eg. Age_limit CONSTANT NUMBER
5, Explain about Conditional control statements in PL/SQL?
Joining_date DAI
4, Conditional Control : A conditional control structure tests a condition to find out
whether it is true or false and accordingly executes the different blocks of SQL
statements. Conditional control is generally performed by IF statement. There are
three forms of IF statements.
1. IF-THEN
2, IF-THEN-ELSE
3. IF-THEN-ELSIF
1. IF-THEN : Itis the simplest form of IF condition. The syntax for this statement
isas follows :
IF condition THEN
Sequence of statements
END IF;
E.g. DECLARE
AGE integer:
IF AGE
DBMS_OUTPUT. PUT_LINE (‘you are eligible to vote’);
END IF:
END;
1
2, [R-THEN-ELSE : The second form of IF statement adds the keyword E
followed by an alternative sequence of statements, as followsB.Sc. COMPUTER SCIENCE - SEM 3 ————
LWB.Se. COMPUTER SCIENCE -SEM3 |[108 ][____
| IF condition THEN
| sequence_of statements |
ELSE
sequence_of_statements2
END IF,
E.g. DECLARE
A integer;
B integer;
| BEGIN
B= &B:
IF A>B THEN
DBMS_OUTPUT.PUT_LINE (‘A is Big’):
ELSE
| DBMS_OUTPUT.PUT_LINE ('B is Big’);
END IF;
additional conditions, as follows :
IF condition] THEN
sequence_of_statements]
ELSIF condition? THEN
sequence_of_statements2
ELSE
sequence_of_statements3 i
END IF;
E.g. DECLARE
Qty integer;
| Pcode _ integer;
| amt real;
| BEGIN
| Qty = &Qty;
Pcode := &productcode;
| IF Peode = | THEN
amt := Qty * 17.50;
ELSIF Peode = 2 THEN
amt *= Qty * 2.75;
ELSIF Pcode = 3 THEN
LSIF : The third form of IF statement selects an action from several
mutually exclusive alternatives. It uses the keyword ELSIF (not ELSEIF) to introduceSe COMPUTER SCIENCE. SEM3 |[To9 a
|
amt = Qty *4.80;
ELSIF Peode = 4 THEN
amt: = Qty * 6.20;
ELSE
amt := Qty * 12.00;
END IF;
DBMS_OUTI
DBMS. PUT.PUT_LINE (‘Amount =" |j amt);
Explain about CASE statement in PL/SQL with examples?
onditions. CASE
PL/SQL CASE statement comparing one by one sequencing ©
WHEN
statement attempt to match expression that is specified in one or more
condition.
Syntax :
CASE selector
WHEN value-1
THEN statement-1;
WHEN value-2
THEN statement-2;
ELSE
statement-3;
END CASE
Example Code :
SQL>DECLARE
anumber := 7;
BEGIN
CASE a
WHEN | THEN
DBMS_OUTPUT.PUT_LINE(‘value ips
WHEN 2 THEN
DBMS_OUTPUT.PUT_LINE(‘value 2);
ELSE
DBMS_OUTPUT.PUT_LINE(no matching CASE found’);
END CASE;
END;
i
Example Result
no matching CASE foundCOMPUTER SCIENCE - SEM3
a)
END Loop
DECLARI
no NUMBER 0.
SNUMBER 0
BEGIN
WHILE no 10 LOOP
no not]
Sostno.
END Loop,
DBMS OUFPULPUT EINECSum 2" || s):
END.
Example Result
Sum: 45
3. FOR-LOOP : FOR loops iterate over a specified range of integers. The range
1S part of izerarion selieme, which 1s enclosed by the keywords FOR and LOOP. A
double dot(..) serves as the range operator.
Syntax : FOR counter IN [REVERSE] lower value ..upper_value LOOP
sequence_of_statements
END LOOP:
The range is evaluated when the FOR loop is first entered and is never re-evaluated.
The sequence of statements is executed once for each integer in the range. After
every iteration. the loop counter is incremented.
The REVERSE clause is used if starts from upper_value and decremented by 1
until it reaches the lower_value.
E.g. : DECLARE
no integer:
BEGIN
FOR no IN 1 .. 5 LOOP
DBMS_OUTPUT.PUT_LINE(‘Iteration :' || no);
END LOOP:
END
Example Result
Iteration :
ation
ay
8
Write about
Foie ee sat
nts in PL/SQ
Sequential con Sequen s
Heontrol state
a I Statements are control yeu!
iteration Loop.
i) goto statement
1) continue statement
i) goto Statement : The sequential control unconditionally passes the contra! (°
specified unique label; i ean be inthe forward direction or inthe backward direction
For sequential control GOTO statement is used, Overuse brGO FO statement may
merease the complexity, thus as far as possible avoid the use of GOO statement
The syntax is as follows
GOTO label;
<