DBMS - Lab Manual - RECORD
DBMS - Lab Manual - RECORD
DBMS - Lab Manual - RECORD
1) Creation, altering and droping of tables and inserting rows into a table (use constraints
while Creating tables) examples using SELECT command.
2) Queries (along with sub Queries) using ANY, ALL, IN, EXISTS, NOTEXISTS, UNION,
INTERSECT, Constraints.
Example:- Select the roll number and name of the student who secured fourth rank in the
class.
3) Queries using Aggregate functions (COUNT, SUM, AVG, MAX and MIN), GROUP BY,
HAVING and Creation and dropping of Views.
4) Queries using Conversion functions (to_char, to_number and to_date), string functions
(Concatenation, lpad, rpad, ltrim, rtrim, lower, upper, initcap, length, substr and instr), date
functions (Sysdate, next_day, add_months, last_day, months_between, least, greatest,
trunc, round, to_char, to_date)
5) i)Creation of simple PL/SQL program which includes declaration section, executable
section and exception –Handling section (Ex. Student marks can be selected from the table
and printed for those who secured first class and an exception can be raised if no records
were found)
ii)Insert data into student table and use COMMIT, ROLLBACK and SAVEPOINT in
PL/SQL block.
6) Develop a program that includes the features NESTED IF, CASE and CASE expression.
The program can be extended using the NULLIF and COALESCE functions.
7) Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops using
ERROR Handling, BUILT –IN Exceptions, USE defined Exceptions, RAISE-
APPLICATION ERROR.
8) Programs development using creation of procedures, passing parameters IN and OUT of
PROCEDURES.
9) Program development using creation of stored functions, invoke functions in SQL
Statements and write complex functions.
10) Program development using creation of package specification, package bodies, private
objects, package variables and cursors and calling stored packages.
11) Develop programs using features parameters in a CURSOR, FOR UPDATE CURSOR,
WHERE CURRENT of clause and CURSOR variables.
12) Develop Programs using BEFORE and AFTER Triggers, Row and Statement Triggers and
INSTEAD OF Triggers
1
EXP:1
AIM:
Creation, altering and droping of tables and inserting rows into a table (use constraints while
creating tables) examples using SELECT command.
ORACLE
Oracle was first developed by Relational Software in the year 1979 later came to be known as
oracle Corporation. This company produces the most widely used, server based, multi user
RDBMS named Oracle
DDL
• This part of SQL is a syntax for database tables to be created or deleted. We can also define
indexes, specify links between tables, and impose constraints between database tables
• The important DDL statements are
– CREATE Table
– ALTER Table
– DROP Table
– TRUNCATE Table
– RENAME Table
DML
• This part of SQL is a syntax for executing queries. But the SQL language also include a
syntax to update, insert and delete records.
• The important DML Statements are
– SELECT – Extracts data from a database table
– UPDATE – Updates data in a database table
– DELETE – Deletes data from a database table
– INSERT INTO – Inserts new data into a database Table.
TCL
DCL
• This part SQL is a syntax to control the flow of data among different users of the database
• The important DCL statements are
– GRANT – Grants permissions to users
– REVOKE – Revokes permissions to users
2
DDL STATEMENTS
CREATE
• Defines each column of the table Uniquley. Each column has minimum of three attributes.
– Name
– Datatype
– Size
• Rules for creating Tables
– A name can have upto 30 Characters
– Alphabets from A-Z,a-z and numbers from 0-9 are allowed.
– A name should begin with an alphabet.
– The use of special characters is allowed lile _ , $ , # .
– SQL reserved words are not allowed
• Syntax
– CREATE TABLE <Table Name> ( <Column name 1> <Datatype>(<size>),
<Column name 2> <Datatype>(<size>),……);
• Check List
– What are the attributes of the row to be stored.
– What are the datatypes of the attribues.
– Which column should be used to build primary key.
– Which column must allow or not allow null values.
– Which column must allow or not allow Duplicates.
Note
Table created
SQL>desc reserves;
ALTER
SQL>desc sailors;
Table altered
SQL>desc sailors;
DROP
TRUNCATING TABLE
• It empties the table completely . Leave the table structures. Such like Delete all rows from
the table.
• Truncate Drops the table and recreates its. It is faster than Deleting all Rows
• It is not transaction safe
• Deleted rows will not be returned
• Syntax
5
DML
INSERT
• Syntax
– INSERT INTO <TableName>(<ColumnName> ,<ColumnName>,…) VALUES
(<Expression>, <Expession>,…);
– While inserting there must (‘) for character data and date datatypes
• Rules
– If there are less values being described than there are columns in the table then it is
mandatory to indicate both the columns and there column values
– If there are exactly the same number of values as there are columns and the values
are sequenced in exactly in accordance with the data type of the table columns there
is no need to indicate the column names.
• Inserting Multiple Values
– INSERT INTO <TableName> VALUES (&ColumnName1, &ColumnName2,….);
1 row inserted
1 row inserted
1 row inserted
1 row inserted
------
6
UPDATE
• Syntax 1
– UPDATE <TableName> SET <ColumnName1>=<Expression1>,
<ColumnName2>=<Expression2>,….;
• Syntax 2
– UPDATE <TableName> SET <ColumnName1>=<Expression1>,
<ColumnName2>=<Expression2>,… WHERE Condition;
10 rows updated -- this command will update all sailors ages to 23.0
7
74 103 9-8-98
DELETE
• Syntax 1
– DELETE FROM <TableName>;
• Syntax 2
– DELETE FROM <TableName> WHERE Condition;
10 rows deleted
No rows selected
8
DATA CONSTRAINTS
• Oracle permits data constraints to be attached to table columns via SQL Syntax
• Once data constraints are part of table column construct, the Oracle database engine checks
the data being entered into a table column against the data constraints.
• If the data passes this check, it is stored in the table column else it is rejected.
• Both CREATE TABLE and ALTER TABLE SQL syntax are used to attach constraints
• Once these constraints are attached data must be carefully loaded into the database.
• Primary Key is one or more columns in a table used to uniquely identifies a row.
• A single column primary key is called Simple Key.
• A multi column primary key is called Composite Key.
• Primary key will not allow Duplicate values.
• Primary key will not allow Null values.
• It helps in relating tables with one another
• It cannot be LONG or RAW data type
• Only one primary key is allowed per tabel
• Unique index is created automatically if there is a Primary key
• One table can combine upto 16 columns in a composite Primary Key
Foreign Key
• Syntax
<columnName> <Datatype>(<size>) REFERENCES <TableName>
[(<ColumnName>)] [options];
• Syntax
Foreign key (<ColumnName> [,<ColumnName>]) REFERENCES <TableName>
[(<ColumnName> ,<ColumnName>)]
9
Unique
NULL
• A null value is not equal to zero we set null when the value is unknown
• Null value can be inserted into columns of any data type
• Syntax
– <ColumnName> <datatype>(<size>) NOT NULL;
– Example
– SQL>Create table student(s_no varchar2(10), s_name char(20) NOT NULL,year
date,branch char(3), subject char(10));
– IT does not allow NULL values to be inserted in s_name
CHECK
Syntax
– <ColumnName> <Datatype>(<size>) CHECK (<Logical Expression>);
–
It checks while the values are inserted into the table
Assigment:
SQL>drop sailors;
Table dropped
SQL>drop boats;
Table dropped
SQL>drop reserves;
Table dropped
10
SQL>create table sailors(sid number(3) PRIMARY KEY ,sname varchar2(10), rating number(1)
CHECK(rating>=1 and rating<=10),age number(3,1));
Table created
SQL>desc sailors;
Table created
SQL>desc boats;
NAME NULL? TYPE
BID NOT NULL NUMBER(3)
BNAM
VARCHAR2(10)
E
COLOR VARCHAR2(10)
Table created
SQL>desc reserves;
NAME NULL? TYPE
SID NOT NULL NUMBER(3)
BID NOT NULL NUMBER(3)
DAY DATE
RESERVES (Child)
SID BID DAY
FK FK
11
Composite PK
Insert data into Sailors, Boats and Reserves table in the same order
12
BID in Boats
SID,BID in reserves
The following restrictions are followed for fields which are declared as foreign key
To insert records into sailors and boats there is no restriction , but to insert record into reserves we
must have the particular record with sid and bid values in sailors and boats tables.
To update a record in sailors whose value is referenced in reserves will not be permited
To update a record in reserves we will have the restriction that only the updating are allowed up to
the values in sailors table
SQL>update reserves set sid=33 where sid=22;
Deletion in reserves has no restriction but to delete a record from sailors and boats the records
must not have references in child.
We can allow the updating and deleting in parent and child by using the following syntax
13
This syntax will carry updating and deleting in parent to child with out above restrictions.
SELECT
Syntax 1
– Select all Columns and rows
– SELECT * FROM <TableName>;
Syntax 2
– Selected Columns and rows
– SELECT <ColumnName1>,<ColumnName2>,… FROM <TableName>;
Syntax3
– Selected rows and all columns
– SELECT * FROM <TableName> WHERE condition;
Syntax 4
– Selected rows and Columns
– SELECT <ColumnName1>,<ColumnName2>,… FROM <TableName> WHERE
condition;
Syntax 5
– Selecting rows by eliminating duplicate rows
– SELECT DISTINCT <ColumnName1>,<ColumnName2>,… FROM
<TableName>;
Syntax 6
– Selecting data from table in sorted order
– SELECT * FROM <TableName> ORDER BY <ColumnName1>,<
ColumnName2>,.. [sortorder];
SNAME AGE
Dustin 45.0
Brutus 33.0
Lubber 55.5
Andy 25.5
Rusty 35.0
Horatio 35.0
Zobra 16.0
14
Art 25.5
Bob 63.5
9 rows selected
SQL> select sid, sname, rating, age from sailors where rating>7;
OR
5 rows selected
Q3) Find the names of sailors who have reserved boat number 103;?
SQL> select s.sname from sailors s, reserves r where s.sid=r.sid and r.bid=103;
SNAME
Dustin
Lubber
Horatio
Q4) Find the sids of sailors who have reserved a red boat?
SQL> select r.sid from boats b, reserves r where b.bid=r.bid and b.color=’red’;
SID
22
22
31
31
64
SQL> select distinct r.sid from boats b, reserves r where b.bid=r.bid and
b.color=’red’;
SID
22
31
64
Q5) Find the names of sailors who have reserved a red boat?
15
SQL> select distinct s.sname from sailors s, reserves r, boats b where s.sid=r.sid and
r.bid=b.bid and b.color=’red’;
SNAME
Dustin
Lubber
Horatio
SQL>select b.color from sailors s, reserves r, boats b where s.sid=r.sid and r.bid=b.bid
and s.sname=’lubber’;
COLOR
Red
Green
Red
7) Find the names of sailors who have reserved at least one boat?
16
EXP. 2
AIM: Queries (along with sub Queries) using ANY, ALL, IN, EXISTS, NOTEXISTS, UNION,
INTERSECT, Constraints.
NESTED QUERIES
Q1) Find the names of sailors who have reserved a red or a green boat?
SQL> Select s.sname from sailors s, reserves r, boats b where s.sid=r.sid and
r.bid=b.bid and (b.color = ‘red’ or b.color= ‘green’);
Or
SQL> Select s.sname from sailors s, reserves r, boats b where s.sid=r.sid and
r.bid=b.bid and b.color=’red’
UNION
Select s.sname from sailors s, reserves r, boats b where s.sid=r.sid and r.bid=b.bid and
b.color=’green’;
SNAME
Dustin
Lubber
Horatio
Q2) Find the names of sailors who have reserved a red and a green boat?
SQL> Select s.sname from sailors s, reserves r, boats b where s.sid=r.sid and
r.bid=b.bid and b.color=’red’
INTERSECT
Select s.sname from sailors s, reserves r, boats b where s.sid=r.sid and r.bid=b.bid and
b.color=’green’;
SNAME
Dustin
Lubber
Horatio
Q3) Find the names of sailors who have reserved a red boat but not green boat?
SQL> Select s.sname from sailors s, reserves r, boats b where s.sid=r.sid and
r.bid=b.bid and b.color=’red’
MINUS
Select s.sname from sailors s, reserves r, boats b where s.sid=r.sid and r.bid=b.bid and
b.color=’green’;
NO ROWS SELECTED
Q4) Find all sids of sailors who have a rating of 10 or reserved boat 104?
SID
22
31
58
71
Q5) Find the name of sailors who have reserved boat 103
SNAME
Dustin
Lubber
Horatio
Q6) Find the name of sailors who have reserved a red boat
SNAME
Dustin
Lubber
Horatio
Q7) Find the names of sailors who have not reserved a red boat.
SNAME
Brutus
Andy
Rusty
Horatio
Zobra
Art
Bob
Q8) Find the name of sailors who have reserved boat 103
18
Horatio
Q9) Find the name of sailors who have not reserved boat 103
SQL>Select s.sname from sailors s where
NOT EXISTS (select * from reserves r where r.bid=103 and r.sid = s.sid) ;
SNAME
Brutus
Andy
Rusty
Horatio
Zobra
Art
Bob
Q10) Find sailors whose rating is better than some sailor called Horation?
SID
31
32
58
71
74
Q11) Find sailors whose rating is better than every sailor called Horation?
SID
58
71
19
EXP. 3
AIM: Queries using Aggregate functions (COUNT, SUM, AVG, MAX and MIN), GROUP BY,
HAVING and Creation and dropping of Views.
AGGREGATE OPERATORS
AVG(age)
37.4
AVG(age)
25.5
MAX(age)
63.5
MIN(age)
16
Q5) Count the number of sailors
SNAME MAX(AGE)
Lubber 55.5
Q8) Find the names of sailors who are older than the oldest sailor with a rating of 10?
SNAME
Dustin
Lubber
Horatio
Bob
Q9) Find the age of the youngest sailor for each rating level.
RATING AGE
1 33.0
3 25.5
7 35.0
8 25.5
21
9 35.0
10 16.0
Q10) Find the age of the youngest sailor who is eligible to vote for each rating level with at least
two such sailors ?
RATING AGE
3 25.5
7 35.0
8 25.5
Q11) For each red boat find the number of reservations for this boat?
BID RESERVATIONCOUNT
102 3
104 2
Q12) Find the average age of sailors for each rating level that has at least two sailors ?
RATING AVGAGE
3 44.5
7 40.5
8 40.5
10 25.5
22
VIEWS
In the SQL language, a view is a representation of one or more tables. A view can be used to hide
the complexity of relationships between tables or to provide security for sensitive data in tables. In
the following example, a limited view of the emp table is created. When a view is defined, a SQL
statement is associated with the view name. Whenever the view is accessed, the SQL statement will
be executed.
Table Created
1 row created
In the following example, the view emp_1 is created as a limited number of columns
(Empno,Ename,salary) and limited set of data ( WHERE salary > 3000 ) from the EMP table.
View created.
Once the view is created, it can be queried with a SELECT statement as if it were a table.
23
Views can be dropped in a similar fashion to tables. The DROP VIEW command provides this
facility. In the following example, the view just created is dropped.
View can be again created with the same name emp_1 as a limited number of columns
(Empno,Ename,salary,dno) and limited set of data ( WHERE dno=10 ) from the EMP table.
View created.
Once the view is created, it can be queried with a SELECT statement as if it were a table.
1 row created
The same record will be inserted into base table also and Vice versa
The record will not be visible in view because the record does not satisfy the WHERE dn0=10
condition, but it will be inserted in base table EMP
Actually this record must not be accepted while inserted in view EMP_1 because it does not hold
the condition so we can enable this condition by including WITH CHECK OPTION in View
creation.
View droped
View created.
25
SQL> Insert into emp_1 values (108,’okl’,7500,20);
Table altered
View created.
Error: NULL values can not inserted in PRIMARY KEY field EMP.EMPNO
This view can not accept insertion because when it inserts a record it is trying to insert NULL into
primary key field of Base table EMP.
26
EXP.4
The Oracle implementation of SQL provides a number of functions that can be used in SELECT
statements. Functions are typically grouped into the following:
Single row functions - Operate on column values for each row returned by a query.
Group functions - Operate on a collection (group) of rows.
The following is an overview and brief description of single row functions. x is some number, s is
a string of characters and c is a single character.
Math functions :
ABS(10.5)
10
Character functions:
27
SUBSTR (s, x1, x2) - Return a portion of string s starting at position x1 and ending
with position x2. If x2 is omitted, it's value defaults to the end of s
UPPER (s) - Converts string s to all upper case letters.
Conversion functions:
TO_DATE (s, format) - Converts a character column (string s to a date. format is a set of
Date formatting codes as above.
Date functions:
SYSDATE - Returns the current date (and time if the TO_CHAR function is used) from
the system clock.
LAST_DAY(Date) – Returns the last days date of the month specified in the Date
MONTHS_BETWEEN(Date, Date) – Returns the number of months between the given
two dates
TIMESTAMP – Returns the current date time in hours, minutes, seconds and fractions
AM or PM and time zone with respect to GMT.
28
EXP.5(i)
AIM: Creation of simple PL/SQL program which includes declaration section, executable section
and
exception –Handling section .
PL/SQL
The development of database applications typically requires language constructs similar to those
that can be found in programming languages such as C, C++, or Pascal. These constructs are
necessary in order to implement complex data structures and algorithms. A major restriction of the
database language SQL, however, is that many tasks cannot be accomplished by using only the
provided language elements.
The basic construct in PL/SQL is a block. Blocks allow designers to combine logically related
(SQL) statements into units. In a block, constants and variables can be declared, and variables can
be used to store query results. Statements in a PL/SQL block include SQL statements, control
structures (loops), condition statements (if-then-else), exception handling, and calls of other
PL/SQL blocks.
PL/SQL blocks that specify procedures and functions can be grouped into packages. A package is
similar to a module and has an interface and an implementation part. Oracle offers several
predefined packages, for example, input/output routines, file handling, job scheduling etc.
Another important feature of PL/SQL is that it offers a mechanism to process query results in a
tuple-oriented way, that is, one tuple at a time. For this, cursors are used. A cursor basically is a
pointer to a query result and is used to read attribute values of selected tuples into variables. A
cursor typically is used in combination with a loop construct such that each tuple read by the
cursor can be processed individually.
29
STRUCTURE OF PL/SQL-BLOCK
PL/SQL is a block-structured language. Each block builds a (named) program unit, and blocks can
be nested. Blocks that build a procedure, a function, or a package must be named.
A PL/SQL block has an optional declare section, a part containing PL/SQL statements, and an
optional exception-handling part. Thus the structure of a PL/SQL looks as follows (brackets [ ]
enclose optional parts):
[<Block header>]
[DECLARE
<Constants>
<Variables>
<Cursors>
<User defined exceptions>]
BEGIN
<PL/SQL statements>
[EXCEPTION
<Exception handling>]
END;
The block header specifies whether the PL/SQL block is a procedure, a function, or a package. If
no header is specified, the block is said to be an anonymous PL/SQL block. Each PL/SQL block
again builds a PL/SQL statement. Thus blocks can be nested like blocks in conventional
programming languages. The scope of declared variables (i.e., the part of the program in which
one can refer to the variable) is analogous to the scope of variables in programming languages
such as C or Pascal.
Declarations
Constants, variables, cursors, and exceptions used in a PL/SQL block must be declared in the
declare section of that block. Variables and constants can be declared as follows:
<variable name> [constant] <data type> [not null] [:= <expression>];
Valid data types are SQL data types (see Section 1.1) and the data type boolean. Boolean data may
only be true, false, or null. The not null clause requires that the declared variable must always have
a value di_erent from null. <expression> is used to initialize a variable.
If no expression is specified, the value null is assigned to the variable. The clause constant states
that once a value has been assigned to the variable, the value cannot be changed (thus the variable
becomes a constant).
Example:
Declare hire date date; /* implicit initialization with null */
job title varchar2(80) := ’Salesman’;
emp found boolean; /* implicit initialization with null */
salary incr constant number(3,2) := 1.5; /* constant */
...
30
begin
...
end;
Instead of specifying a data type, one can also refer to the data type of a table column (so-called
anchored declaration). For example, EMP.Empno%TYPE refers to the data type of the column
Empno in the relation EMP. Instead of a single variable, a record can be declared that can store a
complete tuple from a given table (or query result). For example, the data type DEPT
%ROWTYPE specifies a record suitable to store all attribute values of a complete row from the
table DEPT. Such records are typically used in combination with a cursor. A field in a record can
be accessed using <record name>.<column name>, for example, DEPT.Deptno.
Exception Handling
A PL/SQL block may contain statements that specify exception handling routines. Each error or
warning during the execution of a PL/SQL block raises an exception. One can distinguish between
two types of exceptions:
System defined exceptions are always automatically raised whenever corresponding errors or
warnings occur. User defined exceptions, in contrast, must be raised explicitly in a sequence of
statements using raise <exception name>. After the keyword exception at the end of a block, user
defined exception handling routines are implemented. An implementation has the pattern when
The most common errors that can occur during the execution of PL/SQL programs are handled by
system defined exceptions.
Examples
Q3) Write a PL/SQL program to extract sailors sid and sname for a given sid?
SQL> declare
a number(10);
b varchar2(10);
c number(10) := &c;
begin
select sid,sname into a,b from sailors where sid = c;
dbms_output.put_line('sailors id = '||a||'sailors Name= '||b);
exception
when no_data_found then
dbms_output.put_line('no such sailor found with sid = '||c);
end;
/
Enter value for c: 22
old 4: c number(10) := &c;
new 4: c number(10) := 22;
sailors id = 22 sailors name = Dustin
PL/SQL procedure successfully completed.
SQL>/
31
Enter value for c: 20
old 4: c number(10) := &c;
new 4: c number(10) := 20;
Ino such sailor found with sid = 20
EXP. 5(ii)
AIM:Insert data into student table and use COMMIT, ROLLBACK and SAVEPOINT in PL/SQL
block.
TCL
Initially any application will have to connect to the database in order to access the data. It is
important to point out that when a user is issuing DML statements in an application the changes
are not visible to the user until a COMMIT or ROLLBACK has been issued.
SAVEPOINT – We can control transactions by using save points. These break transactions into
pieces so that we can roll back to a specified save point with out roll backing the total transaction.
SYNTAX:
savepoint name;
Example:
Table created
SQL> begin
savepoint a;
insert into empl values (101,'abc','acc',2000);
savepoint b;
insert into empl values (102,'bcd','clk',3000);
savepoint c;
insert into empl values (103,'sde','gar',1200);
rollback to c;
COMMIT;
end;
/
32
EID ENAME DSEG SALARY
101 Abc acc 2000
102 Bcd clk 3000
Here only two records are inserted because we are giving savepoints in above PL/SQL block as A,
B, C and we rollback to point C this will erase event insertion of third record.
EXP. 6
AIM: Develop a program that includes the features NESTED IF, CASE and CASE expression.
In PL/SQL there are three types of conditional control : IF, ELSIF and CASE
IF – THEN Statement
This is the most basic kind of a conditional control and has the following structure
If Condition Then
Statement 1;
….
Statement 2;
End If;
The reserved word IF marks the beginning of the IF statement.
Example:
Q1) Write a PL/SQL block to swap two numbers when the first number is greater
than second number ?
SQL> declare
a number(10) := &a;
b number(10) := &b;
c number(10);
begin
dbms_output.put_line('a value ='||a||' b value ='||b);
if a>b then
c := a;
a := b;
b := c;
end if;
dbms_output.put_line(' After swapping: a value ='||a||' b value ='||b);
end;
/
IF – THEN – ELSE
This statement enables you to specify two groups of statements One group of statements is
executed when the condition evaluates to TRUE and the other group of statements is executed
when the condition evaluates to FALSE.
If Condition Then
Statement 1;
ELSE
Statement 2;
End If;
Statement 3;
Example:
Q2) Write a PL/SQL block to test whether the given number is odd or even
SQL> declare
a number(10) := &a;
begin
if mod(a,2)=0 then
dbms_output.put_line('a value is even');
else
dbms_output.put_line('a value is odd');
end if;
end;
/
34
ELSIF Statement:
This statement has the following structure
If Condition 1 Then
Statement 1;
ELSIF Condition 2 Then
Statement 2;
ELSIF Condition 3 Then
Statement 3;
…
ELSE
Statement 4;
END IF;
Example:
Q3) Write a PL/SQL block to find the grade of sailor for a given sid
10, 9, 8 – Grade A
7, 6, 5 – Grade B
other – Grade C
SQL> declare
a number(10) := &a;
c number(10);
begin
select rating into c from sailors where sid = a;
if c in (10,9,8) then
dbms_output.put_line('sailor '||a||' has grade A');
elsif c in (7,6,5) then
dbms_output.put_line('sailor '||a||' has grade B');
else
dbms_output.put_line('sailor '||a||' has grade C');
end if;
end;
/
35
CASE:
A case statement has the following structure:
CASE selector
WHEN expression 1 THEN statement 1;
WHEN expression 2 THEN statement 2;
…..
WHEN expression n THEN statement n;
ELSE statement n+1;
END CASE;
The reserved word CASE marks the beginning of the case statement. A selector is a value that
determines which WHEN clause should be executed.
Example:
Q4) Write a PL/SQL block to print the day name for a given date?
SQL> declare
a date := '&a';
b char(10);
begin
b := to_char(a,'D');
case b
when '1' then
dbms_output.put_line('today is sunday');
when '2' then
dbms_output.put_line('today is monday');
when '3' then
dbms_output.put_line('today is thuesday');
when '4' then
dbms_output.put_line('today is wednesday');
when '5' then
dbms_output.put_line('today is thrusday');
when '6' then
dbms_output.put_line('today is friday');
when '7' then
dbms_output.put_line('today is saturday');
end case;
end;
/
EXP.7
AIM: Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops using
ERROR
Handling, BUILT –IN Exceptions, USE defined Exceptions, RAISE- APPLICATION ERROR.
ITERATIVE CONTROL
In PL/SQL there are three types of loops : Simple LOOP, WHILE loops and Numeric FOR loop
simple LOOP:
A simple loop, as you can see from its name, is the most basic kind of loop and has the following
structure:
LOOP
statement 1;
statement 2;
…….
statement n;
END LOOP;
The reserved word LOOP marks the beginning of the simple loop. Statement 1 through N are a
sequence of statements that is executed repeatedly.
EXIT statement causes a loop to terminate when exit condition evaluates to TRUE.
LOOP
statement 1;
statement 2;
IF condition THEN
EXIT;
END IF;
…….
statement n;
END LOOP;
Example:
Q1) Write a PL/SQL block to print number from 1 to 5 using loop statements
SQL> declare
a number :=0;
begin
loop
a := a+1;
dbms_output.put_line('a value='||a);
if a>5 then
37
exit;
end if;
end loop;
end;
/
a value=1
a value=2
a value=3
a value=4
a value=5
a value=6
PL/SQL procedure successfully completed.
Note: here numbers are printed 1 to 6 because this loop acts as do-while so it executes the
statements and then check the condition next.
LOOP
statement 1;
statement 2;
EXIT WHEN condition;
…….
statement n;
END LOOP;
Q2) Write a PL/SQL block to print number from 1 to 5 using loop statements
SQL> declare
a number :=0;
begin
loop
a := a+1;
dbms_output.put_line('a value'||a);
exit when a>5 ;
end loop;
end;
/
a value1
a value2
a value3
a value4
a value5
a value6
WHILE LOOPS:
The reserved word WHILE marks the beginning of a loop construct. The word CONDITION is the
test condition of the loop that evaluates to TRUE or FALSE.
Example:
Q3) Write a PL/SQL block to print number from 1 to 5 using while loop statements
SQL> declare
a number:=1;
begin
while a<5 loop
dbms_output.put_line('a value='||a);
a := a+1;
end loop;
end;
/
a value=1
a value=2
a value=3
a value=4
The reversed word FOR marks the beginning of a FOR loop construct. The variable loop_counter
is an implicitly defined index variable. There is no need to define the loop counter in the
declaration section. The values of the lower_limit and upper_limit are evaluated once for the
iteration of the loop.
Example:
Q4) Write a PL/SQL block to print number from 1 to 5 using for loop statements
SQL> begin
39
for a in reverse 1..5 loop
dbms_output.put_line('a value='||a);
end loop;
end;
/
SQL>
a value=5
a value=4
a value=3
a value=2
a value=1
PL/SQL procedure successfully completed.
Examples:
Q5) To write a PL/SQL block to find Sum of Digits of a given Number.
SQL> DECLARE
num number(5);
rem number(5);
sm number(5):=0;
num1 number(5);
BEGIN
num:=#
num1:=num;
while(num>0) loop
rem:=mod(num,10);
sm:=sm+rem;
num:=trunc(num/10);
end loop;
dbms_output.put_line('SUM OF DIGITS OF '||num1||' IS: '||sm);
END;
/
RESULT:
SQL>
Enter value for num: 123
old 7: num:=#
new 7: num:=123;
SUM OF DIGITS OF 123 IS: 6
PL/SQL procedure successfully completed.
SQL> /
Enter value for num: 456
old 7: num:=#
new 7: num:=456;
SUM OF DIGITS OF 456 IS: 15
PL/SQL procedure successfully completed.
Q7) To write a PL/SQL block to Check the Given String is Palindrome or Not.
SQL> DECLARE
name1 varchar2(20);
name2 varchar2(20);
l number(5);
BEGIN
name1:='&name1';
l:=length(name1);
while l>0 loop
name2:=name2||substr(name1,l,1);
l:=l-1;
end loop;
dbms_RESULT.put_line('REVERSE OF STRING IS:'||NAME2);
if(name1=name2) then
dbms_RESULT.put_line(name1||' IS PALINDROME ');
else
dbms_RESULT.put_line(name1||' IS NOT PALINDROME ');
end if;
END;
/
RESULT:
SQL>
Enter value for name1: LIRIL
41
old 6: name1:='&name1';
new 6: name1:='LIRIL';
REVERSE OF STRING IS: LIRIL
LIRIL IS PALINDROME
PL/SQL procedure successfully completed.
SQL> /
Enter value for name1: MADAM
old 6: name1:='&name1';
new 6: name1:='MADAM';
REVERSE OF STRING IS: MADAM
MADAM IS PALINDROME
PL/SQL procedure successfully completed.
EXCEPTION HANDLING
The table below lists some of these exceptions with their names and a short description.
Some type of errors can not be identified by in built exception handlers so we can design our own
exceptions to handle situations
To use a exception first we must declare it in the declaration section of PL/SQL block.
A user defined exception must be raised explicitly i.e., you need to specify in your program under
which circumstances an exception must be raised.
The exception statements associated with this exception are specified in the exception handling
section of the block.
DECLARE
Exception_name EXCEPTION;
42
BEGIN
….
IF condition THEN
RAISE exception_name;
ELSE
….
END IF;
EXCEPTION
WHEN exception_name THEN
--Error-Processing Statement;
END;
Example
Q1) Write a PL/SQL block to handle exception when the given sid is negative using user
defined exception?
SQL> declare
a number(10);
b varchar2(10);
c number(10) := &c;
d exception; --exception variable declaration
begin
if c<0 then
raise d; --raising an exception
else
select sid,sname into a,b from sailors where sid = c;
dbms_output.put_line('sailors id = '||a||'sailors Name= '||b);
end if;
exception
when d then --action to be taken
dbms_output.put_line('sailor id can not be negative');
when no_data_found then
dbms_output.put_line('no such sailor found with sid = '||c);
end;
/
SQL> /
Enter value for c: -22
old 4: c number(10) := &c;
new 4: c number(10) := -22;
sailor id can not be negative
PL/SQL procedure successfully completed.
43
RAISE_APPLICATION_ERROR
It is a special built in procedure provided by oracle. This procedure allows programmers to create
meaningful error messages for a specific application. This works with user defined exceptions
RAISE_APPLICATION_ERROR(error_number, error_message);
Q2) Write a PL/SQL block to handle exception when the given sid is negative using
RAISE_APPLICATION_ERROR?
SQL> declare
a number(10);
b varchar2(10);
c number(10) := &c;
begin
if c<0 then
raise_application_error(-20000,'sailor id can not be negative');
else
select sid,sname into a,b from sailors where sid = c;
dbms_output.put_line('sailors id = '||a||'sailors Name= '||b);
end if;
exception
when no_data_found then
dbms_output.put_line('no such sailor found with sid = '||c);
end;
/
SQL>
Enter value for c: 22
old 4: c number(10) := &c;
new 4: c number(10) := 22;
sailors id = 22sailors Name= dustin
SQL> /
Enter value for c: -22
old 4: c number(10) := &c;
new 4: c number(10) := -22;
declare
*
ERROR at line 1:
ORA-20000: sailor id can not be negative
ORA-06512: at line 7
44
EXP.8
AIM: Programs development using creation of procedures, passing parameters IN and OUT of
PROCEDURES.
PL/SQL MODULES
A PL/SQL module is any complete logical unit of work. There are four types of PL/SQL modules:
1) anonymous blocks that are run with a text script( you have used until now), 2) Procedures, 3)
Functions, and 4) Packages.
There are two main benefits to using modular code: 1) it is more reusable and 2) it is more
manageable.
PROCEDUREDS:
A procedure is a module performing one or more actions: it does not need to return any value. The
syntax for creating a procedure is
Example:
Q1) Create a procedure to add two number and call the block with a PL/SQL block?
SQL> create or replace procedure sum(a in number,b in number)
is
c number := 1;
begin
c := a+b;
dbms_output.put_line('c value '||c);
end;
/
Procedure created.
SQL> declare
a number := &a;
b number := &b;
begin
45
sum(a,b);
end;
/
SQL> Enter value for a: 10
old 2: a number := &a;
new 2: a number := 10;
Enter value for b: 20
old 3: b number := &b;
new 3: b number := 20;
c value 30
PL/SQL procedure successfully completed.
Q2) Create a procedure to add two number and return the value to a PL/SQL block?
SQL> create or replace procedure sum1(a in number,b in number,d out number)
is
c number := 1;
begin
c := a+b;
d:=c;
end;
/
Procedure created.
SQL> declare
a number := &a;
b number := &b;
d number;
begin
sum1(a,b,d);
dbms_output.put_line('addition= '||d);
end;
/
SQL> Enter value for a: 10
old 2: a number := &a;
new 2: a number := 10;
Enter value for b: 30
old 3: b number := &b;
new 3: b number := 30;
addition= 40
PL/SQL procedure successfully completed.
Q2) Create a procedure to accept sailors sid and return age of sailor to a PL/SQL block?
SQL> create or replace procedure sail(a in number,b out number)
is
c number;
begin
select age into c from sailors where sid = a;
b := c;
exception
when no_data_found then
dbms_output.put_line('no such sailors');
end;
/
Procedure created.
SQL> declare
46
a number := &a;
b number;
begin
sail(a,b);
dbms_output.put_line('sailors with '||a||' has age '||b);
end;
/
SQL> Enter value for a: 64
old 2: a number := &a;
new 2: a number := 64;
sailors with 64 has age 35
PL/SQL procedure successfully completed.
EXP.9
AIM: Program development using creation of stored functions, invoke functions in SQL
Statements and
write complex functions.
FUNCTIONS
The function does not necessarily have any parameters, but it must have a RETURN value
declared in the header, and it must return values for all the varying possible execution streams.
Q1) Create a function to add two numberS and return the value to a PL/SQL block?
SQL> declare
a number:=&a;
b number:=&b;
47
d number;
begin
d := addfun(a,b);
dbms_output.put_line('Addtion value='||c);
end;
/
SQL> Enter value for a: 20
old 2: a number := &a;
new 2: a number := 20;
Enter value for b: 30
old 3: b number := &b;
new 3: b number := 30;
Addition value= 50
PL/SQL procedure successfully completed.
Q2) Create a function to accept sailors sid and return age of sailor to a PL/SQL block?
Function created.
SQL> declare
a number:= &a;
c number;
begin
c := sailf(a);
dbms_output.put_line('sailor with sid '||a||'has age '||c);
end;
/
SQL>
Enter value for a: 58
old 2: a number:= &a;
new 2: a number:= 58;
sailor with sid 58has age 35
48
EXP. 10:
AIM: Program development using creation of package specification, package bodies, private
objects,
package variables and calling stored packages.
PACKAGES:
We can use package as a method to bundle your functions and procedures, the first being that a
well designed package is a logical grouping of objects – such as functions, procedures, global
variables and cursors.
Example:
Q1) Create a package which contains a procedure to add two numbers and a function which will
subtract two numbers?
addition= 70
subtraction= 10
50
EXP.11
AIM: Develop programs using features parameters in a CURSOR, FOR UPDATE CURSOR,
WHERE CURRENT of clause and CURSOR variables.
CURSOR:
A cursor is a handle or pointer to the context area. Through the cursor a PL/SQL program can
control the context area and what happens to it as the statements is processed.
1) Cursor allow you to fetch and process rows returned by a SELECT statement, one row at a time.
2) A cursor is named so that it can be referenced.
TYPES OF CURSORS:
1. An implicit cursor is automatically declared by oracle every time an SQL statement is
executed. The user will not be aware of this happening and will not be able to control or
process the information in an implicit cursor.
2. An explicit cursor is defined by the program for any query that returns more than one
row of data. That means the programmer has declared the cursor within the PL/SQL
code block. This declaration allows for the application to sequentially process each row
of data as it is returned by the cursor.
IMPLICIT CURSOR
In order to better understand the capabilities of an explicit cursor, you first need to run through the
process of an implicit cursor.
1) Any given PL/SQL block issues an implicit cursor when ever an SQL statement is
executed, as long as an explicit cursor does not exist for that SQL statement.
2) A cursor is automatically associated with every DML statement.
3) All UPDATE and DELETE statements have cursors that identify the set od rows that
will be affected by the operations.
4) An INSERT statement needs a place to receive the data that is to be inserted in the
database; the implicit cursor fulfills this need.
5) The most recently opened cursor is called the ‘SQL%’ cursor.
EXPLICIT CURSOR
The only means of generating an explicit cursor is for the cursor to be named in the DECLARE
section of the PL/SQL block.
1) Declaring the cursor defines the name of the cursor and associatedit with a SELECT
statements CURSOR cursor_name IS SELECT statement
2) Opening the cursor is to process the select statement and set a active pointer to the first
row OPEN cursor_name;
3) Fetching cursor into PL/SQL local variables, these variables are declared as
ROWTYPE in declare section FETCH cursor_name INTO PL/SQL variables
51
4) Closing a cursor by CLOSE cursor_name;
Explicit cursor attributes:
Cursor Syntax Explanation
Attribute
%NOTFOUN Cursor_name A Boolean attribute that returns TRUE if the
D %NOTFOUND previous FETCH did not return a row and FALSE
if it did
%FOUND Cursor_name%FOUND A Boolean attribute that returns TRUE if the
previous FETCH did return a row and FALSE if it
did not
%ROWCOUN Cursor_name No. of records fetched from a cursor at that point in
T %ROWCOUNT time
%ISOPEN Cursor_name%ISOPEN A Boolean attribute that returns TRUE if cursor is
open, FALSE if it is not.
Q1) Create a cursor which fetches data from sailors table whose rating is greater than 5?
SQL> declare
cursor sail is select sid,sname,age from sailors where rating>5;
s sail%rowtype;
begin
open sail;
loop
fetch sail into s;
exit when sail%notfound;
dbms_output.put_line('sailor sid = '||s.sid||' name = '||s.sname||' age =
'||s.age);
end loop;
close sail;
end;
/
SQL> sailor sid = 64 name = horatio age = 35
sailor sid = 22 name = dustin age = 45
sailor sid = 31 name = lubber age = 55.5
sailor sid = 32 name = andy age = 25.5
sailor sid = 58 name = rusty age = 35
sailor sid = 71 name = zobra age = 16
sailor sid = 74 name = horatio age = 35
52
end loop;
close bt;
end;
SQL> /
boat bid = 101 name = interlake color = blue
boat bid = 102 name = interlake color = red
boat bid = 103 name = clipper color = green
boat bid = 104 name = marine color = red
Q3) Create cursor which fetches data from reserves table where sid is22
SQL> declare
cursor reser is select * from reserves where sid=22;
r reser%rowtype;
begin
open reser;
loop
fetch reser into r;
exit when reser%notfound;
dbms_output.put_line('reserve sid = '||r.sid||' bid = '||r.bid||' day = '||
r.day);
end loop;
close reser;
end;
/
SQL>
reserve sid = 22 bid = 101 day = 10-OCT-98
reserve sid = 22 bid = 102 day = 10-OCT-98
reserve sid = 22 bid = 103 day = 10-SEP-98
reserve sid = 22 bid = 104 day = 10-JUL-98
53
EXP.12
AIM: Develop Programs using BEFORE and AFTER Triggers, Row and Statement Triggers and
INSTEAD OF Triggers
TRIGGERS
The Oracle RDBMS has the ability to store procedures within the data dictionary and execute
procedures in the RDBMS. Procedures (Program Units) are written in the PL/SQL language
(Procedural Language), which is proprietary to Oracle. PL/SQL runs in both the database engine as
well as in many of Oracle's development tools such as Oracle Developer.
It is common practice to store general business rule checking in procedures. This allows
applications to check data validity before a transaction is submitted to the database. Triggers can
also call the procedures to check data at the database level. Since the business rules are coded in a
single set of procedures, maintenance of this code is simplified. In this section, we will introduce
the syntax for creating triggers and demonstrate the use of a trigger to enforce a business rule.
Trigger Syntax
Creating a trigger is accomplished with the CREATE TRIGGER statement. There are numerous
options for a trigger that specify when the trigger should fire. These options include:
The SQL statement (INSERT, UPDATE, DELETE, SELECT) that causes the event. An
event can include more than one SQL statement per trigger.
The timing when the trigger code is executed. Options here include
o BEFORE - The trigger code is executed before the effects of the SQL statement are
put into place.
o INSTEAD OF - The trigger code is executed instead of the normal SQL statement.
o AFTER - The trigger code is executed after the normal SQL statement is processed.
Some SQL statements such as UPDATE, DELETE and SELECT may affect more than one
row. Triggers may be specified to fire once for the SQL statement or once for each row
affected by the SQL statement.
Example:
Q1) To write a TRIGGER to ensure that SAILORS TABLE does not contain duplicate of null
values in SID column.
54
else
select count(*) into a from sailors where sid=:new.sid;
if(a=1) then
raise_application_error(-20002,'error:: cannot have duplicate sid');
end if;
end if;
END;
/
Trigger created.
55
Enter value for dname: mana
Enter value for rating: 9
Enter value for age:25.5
old 1: insert into sailors values((&sid,'&sname',&rating,&age)
new 1: insert into sailors values(30,’mana’,9,25.5)
1 row created
56