5ks06dbms Lab Record
5ks06dbms Lab Record
Page
S.No Date Name of the Experiment Remarks
No
Introduction to SQL
Creation, altering and dropping of tables and
1. 3
inserting rows into a table
2. Queries (along with sub Queries) 20
Queries using Aggregate functions GROUP BY,
3. 26
HAVING and Creation and dropping of Views.
Queries using Conversion functions, string
4. 29
functions, date functions
PL/SQL Introduction 33
Write a PL/SQL program to find the total and
5. 34
average of 4 subjects and display the grade
Write a PL/SQL program to find the largest of
6. 38
three numbers
Write a PL/ SQL program to generate Fibonacci
7. 40
series
AIM: To create alter and dropping of tables and inserting rows into a table (use
constraints while creating tables) examples using SELECT command.
DESCRIPTION:
Oracle has many tools such as SQL * PLUS, Oracle Forms, Oracle Report Writer,
Oracle Graphics etc.
SQL * PLUS: The SQL * PLUS tool is made up of two distinct parts. These are
Interactive SQL: Interactive SQL is designed for create, access and
manipulate data structures like tables and indexes.
PL/SQL: PL/SQL can be used to developed programs for different
applications.
Oracle Forms: This tool allows you to create a data entry screen along with
the suitable menu objects. Thus it is the oracle forms tool that handles data
gathering and data validation in a commercial application.
2
Oracle Graphics: Some of the data can be better represented in the form of
pictures. The oracle graphics tool allows programmers to prepare graphs using
data from oracle structures like tables, views etc.
1. CHAR (Size): This data type is used to store character strings values of fixed
length. The size in brackets determines the number of characters the cell can
hold. The maximum number of character is 255 characters.
2. VARCHAR (Size) / VERCHAR2 (Size): This data type is used to store variable
length alphanumeric data. The maximum character can hold is 2000 character.
3. NUMBER (P, S): The NUMBER data type is used to store number (fixed or
floating point). Number of virtually any magnitude may be stored up to 38 digits of
precision. Number as large as 9.99 * 10 124. The precision (p) determines the
number of places to the right of the decimal. If scale is omitted then the default is
3
zero. If precision is omitted, values are stored with their original precision up to
the maximum of 38 digits.
4. DATE: This data type is used to represent date and time. The standard format is
DD-MM-YY as in 17-SEP-2009. To enter dates other than the standard format,
use the appropriate functions. Date time stores date in the 24-Hours format. By
default the time in a date field is 12:00:00 am, if no time portion is specified. The
default date for a date field is the first day the current month.
5. LONG: This data type is used to store variable length character strings containing
up to 2GB. Long data can be used to store arrays of binary data in ASCII format.
LONG values cannot be indexed, and the normal character functions such as
SUBSTR cannot be applied.
6. RAW: The RAW data type is used to store binary data, such as digitized picture
or image. Data loaded into columns of these data types are stored without any
further conversion. RAW data type can have a maximum length of 255 bytes.
LONG RAW data type can contain up to 2GB.
INTERACTIVE SQL:
Syntax : VERB(Parameter_1,Parameter_2,Parameter_3,........Parameter_n);
4
Predicates which specify conditions that can be evaluated to SQL three-valued
logic (3VL) Boolean truth values and which are used to limit the effects of
Statements which may have a persistent effect on schemas and data, or which
SQL statements also include the semicolon (";") statement terminator. Though
grammar.
5
(a)CREATE TABLE: This is used to create a new relation and the corresponding
Syntax: CREATE TABLE relation_name
(field_1 data_type(Size),field_2 data_type(Size), .. . );
Example:
SQL>CREATE TABLE Student (sno NUMBER(3),sname CHAR(10),class CHAR(5));
2. ALTER:
(a)ALTER TABLE ...ADD...: This is used to add some extra fields into existing
relation.
Syntax: ALTER TABLE relation_name ADD(new field_1 data_type(size), new field_2
data_type(size),..);
Example : SQL>ALTER TABLE std ADD(Address CHAR(10));
(b)ALTER TABLE...MODIFY...: This is used to change the width as well as data type
of fields of existing relations.
Syntax: ALTER TABLE relation_name MODIFY (field_1 newdata_type(Size), field_2
newdata_type(Size),....field_newdata_type(Size));
Example:SQL>ALTER TABLE student MODIFY(sname VARCHAR(10),class
VARCHAR(5));
3. DROP TABLE: This is used to delete the structure of a relation. It permanently
deletes the records in the table.
Syntax: DROP TABLE relation_name;
Example: SQL>DROP TABLE std;
6
4. RENAME: It is used to modify the name of the existing database object.
Syntax: RENAME TABLE old_relation_name TO new_relation_name;
Example: SQL>RENAME TABLE std TO std1;
5. TRUNCATE: This command will remove the data permanently. But structure will
not be removed.
Syntax: TRUNCATE TABLE <Table name>
Example TRUNCATE TABLE student;
7
FROM relation_name_2 WHERE field_x=data;
Example: SQL>INSERT INTO std SELECT sno,sname FROM student
WHERE name = Ramu;
3. DELETE-FROM: This is used to delete all the records of a relation but it will retain
the structure of that relation.
a) DELETE-FROM: This is used to delete all the records of relation.
Syntax: SQL>DELETE FROM relation_name;
Example: SQL>DELETE FROM std;
b) DELETE -FROM-WHERE: This is used to delete a selected record from a relation.
Syntax: SQL>DELETE FROM relation_name WHERE condition;
Example: SQL>DELETE FROM student WHERE sno = 2;
8
Example : SQL> select * from dept;
DEPTNO DNAME LOC
-------- ----------- ----------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
4. SELECT - FROM -GROUP BY: This query is used to group to all the records in a
relation together for each and every value of a specific key(s) and then display them
for a selected set of fields the relation.
Syntax: SELECT a set of fields FROM relation_name GROUP BY field_name;
Example: SQL> SELECT EMPNO, SUM (SALARY) FROM EMP GROUP BY
EMPNO;
EMPNO SUM (SALARY)
------ ----------
1 3000
2 4000
3 5000
4 6000
4 rows selected.
9
5. SELECT - FROM -ORDER BY: This query is used to display a selected set of fields
from a relation in an ordered manner base on some field.
Syntax: SELECT a set of fields FROM relation_name
ORDER BY field_name;
6. JOIN using SELECT - FROM - ORDER BY: This query is used to display a set of
fields from two relations by matching a common field in them in an ordered manner
based on some fields.
Syntax: SELECT a set of fields from both relations FROM relation_1, relation_2
WHERE relation_1.field_x = relation_2.field_y ORDER BY field_z;
Example: SQL>SELECT empno,ename,job,dname FROM emp,dept
WHERE emp.deptno = 20 ORDER BY job;
EMPNO ENAME JOB DNAME
------ ------ ------- ----------
7788 SCOTT ANALYST ACCOUNTING
7902 FORD ANALYST ACCOUNTING
------
7566 JONES MANAGER OPERATIONS
7566 JONES MANAGER SALES
20 rows selected.
7. JOIN using SELECT - FROM - GROUP BY: This query is used to display a set of
fields from two relations by matching a common field in them and also group the
corresponding records for each and every value of a specified key(s) while displaying.
Syntax: SELECT a set of fields from both relations FROM relation_1,relation_2
WHERE relation_1.field-x=relation_2.field-y GROUP BY field-z;
Example: SQL> SELECT empno,SUM(SALARY) FROM emp,dept
10
WHERE emp.deptno =20 GROUP BY empno;
EMPNO SUM (SALARY)
------- --------
7369 3200
7566 11900
7788 12000
7876 4400
8. UNION: This query is used to display the combined rows of two different queries,
which are having the same structure, without duplicate rows.
11
9. INTERSET: This query is used to display the common rows of two different queries,
which are having the same structure, and to display a selected set of fields out of
them.
10. MINUS: This query is used to display all the rows in relation_1,which are not
having in the relation_2.
Syntax: SELECT field_1,field_2,......FROM relation_1
WHERE(Condition) MINUS SELECT field_1,field_2,.....
FROM relation_2 WHERE(Conditon);
1. COMMIT: This command is used to end a transaction only with the help of the
commit command transaction changes can be made permanent to the database.
12
Syntax: SQL>COMMIT;
Example: SQL>COMMIT;
2. SAVE POINT: Save points are like marks to divide a very lengthy transaction to
smaller once. They are used to identify a point in a transaction to which we can latter
role back. Thus, save point is used in conjunction with role back.
3. ROLE BACK: A role back command is used to undo the current transactions. We
can role back the entire transaction so that all changes made by SQL statements are
undo (or) role back a transaction to a save point so that the SQL statements after the
save point are role back.
13
1. GRANT: The GRANT command allows granting various privileges to other users
and allowing them to perform operations with in their privileges
For Example, if a uses is granted as SELECT privilege then he/she can only view
data but cannot perform any other DML operations on the data base object
GRANTED privileges can also be withdrawn by the DBA at any time
2. REVOKE: To with draw the privileges that has been GRANTED to a uses, we use
the REVOKE command
14
Example : SQL>ALTER TABLE std ADD(Address CHAR(10));
(b)ALTER TABLE...MODIFY...: This is used to change the width as well as data type
of fields of existing relations.
Syntax: ALTER TABLE relation_name MODIFY (field_1 newdata_type(Size), field_2
newdata_type(Size),....field_newdata_type(Size));
Example: SQL>ALTER TABLE student MODIFY(sname VARCHAR(10),class
VARCHAR(5));
3. DROP TABLE: This is used to delete the structure of a relation. It permanently
deletes the records in the table.
Syntax: DROP TABLE relation_name;
Example: SQL>DROP TABLE std;
4. INSERT:
Syntax: INSERT INTO relation_name field_1,field_2,.....field_n) VALUES
(&data_1,&data_2,........&data_n);
Example: SQL>INSERT INTO student(sno,sname,class,address)
VALUES(&sno,&sname,&class,&address);
Enter value for sno: 101
Enter value for name: SIRISHA
Enter value for class: CSE
Enter value for address: Palakol
15
SNO SNAME
---- --------
101 SIRISHA
102 DEVAKI
103 KUMAR
104 RAVI
3. SELECT - FROM -WHERE: This query is used to display a selected set of fields for
a selected set of records of a relation.
Syntax: SELECT a set of fields FROM relation_name WHERE condition;
Example: SQL> select * FROM student WHERE class=CSE;
SNO SNAME CLASS ADDRESS
---- -------- ------ -------
101 SIRISHA CSE PALAKOL
102 DEVAKI CSE NARSAPUR
1. NOT NULL: When a column is defined as NOTNULL, then that column becomes a
mandatory column. It implies that a value must be entered into the column if the
record is to be accepted for storage in the table.
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) NOT NULL, );
Example:
CREATE TABLE student (sno NUMBER(3)NOT NULL, name CHAR(10));
2. UNIQUE: The purpose of a unique key is to ensure that information in the
column(s) is unique i.e. a value entered in column(s) defined in the unique constraint
must not be repeated across the column(s). A table may have many unique keys.
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) UNIQUE, .);
Example:
CREATE TABLE student (sno NUMBER(3) UNIQUE, name CHAR(10));
16
3. CHECK: Specifies a condition that each row in the table must satisfy. To satisfy the
constraint, each row in the table must make the condition either TRUE or unknown
(due to a null).
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) CHECK(logical
expression), .);
Example: CREATE TABLE student (sno NUMBER (3), name CHAR(10),class
CHAR(5),CHECK(class IN(CSE,CAD,VLSI));
5. FOREIGN KEY: It is a table level constraint. We cannot add this at column level. To
reference any primary key column from other table this constraint can be used. The
table in which the foreign key is defined is called a detail table. The table that defines
the primary key and is referenced by the foreign key is called the master table.
Syntax: CREATE TABLE Table_Name(column_name data_type(size)
FOREIGN KEY(column_name) REFERENCES table_name);
Example:
CREATE TABLE subject (scode NUMBER (3) PRIMARY KEY,
17
subname CHAR(10),fcode NUMBER(3),
FOREIGN KEY(fcode) REFERENCE faculty );
(or)
18
EXP NO: 2 Queries (along with sub Queries)
AIM: To execute queries along with sub queries by using ANY, ALL, IN,
EXISTS, NOTEXISTS, UNION, INSERT and Constraints.
10 rows selected.
Selecting data from reserves table
SQL> select * from reserves;
19
SID BID DAY
--------- --------- ------
22 101 10-OCT-98
22 102 10-OCT-98
22 103 10-AUG-98
22 104 10-JUL-98
31 102 11-OCT-98
31 103 11-JUN-98
31 104 11-DEC-98
64 101 09-MAY-98
64 102 09-AUG-98
74 104 09-AUG-98
10 rows selected.
SNAME
--------------
dustin
lubber
2 rows selected.
Q: find the names of sailors who have reserved a red boat.
20
SQL> select s.sname from sailors s where s.sid in
(select r.sid from reserves r where r.bid in (select b.bid
from boats b where b.color='red'));
SNAME
--------------------
dustin
lubber
horatio
horatio
4 rows selected.
Q: Find the name and age of the oldest sailors.
MAX(S.AGE)
----------
10
21
7 where b.color='red'))
SNAME
--------
brutus
andy
rusty
zorba
art
bob
6 rows selected.
Q: find the names of sailors who have not reserved boat 103.
SQL> select s.sname from sailors s where exists(select * from
reserves r where r.bid=103 and r.sid=s.sid);
SNAME
-------
dustin
lubber
2 rows selected.
Q: find the names of sailors who have reserved at least one boat.
SQL> select s.sname from sailors s, reserves r where
s.sid=r.sid;
SNAME
----------
dustin
dustin
dustin
dustin
lubber
lubber
lubber
22
horatio
horatio
horatio
10 rows selected.
Q: Compute increments for the ratings of persons who have sailed two
different boats on the same day.
SNAME RATING
-------------------- ---------
dustin 46
dustin 46
Q: 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')
SNAME
--------------------
dustin
dustin
dustin
lubber
lubber
lubber
horatio
horatio
8 rows selected.
Q: find the all sids of sailors who have rating 10 or have reserved boat
104..
SQL> select s.sid from sailors s where s.rating=10 union
select r.sid from reserves r where r.bid=104;
SID
------
23
22
31
74
Q: Find the number of reservations for each red boat.
SQL> select b.bid,count(*)As sailorcount from boats b,
reserves r where r.bid=b.bid AND b.color='red' group by b.bid;
BID SAILORCOUNT
--------- -----------
102 3
104 3
Q: Find the minimum age of the sailor.
Q: find the id and names of sailors who have reserved id=22 or age<25.
SID SNAME
-- --------
22 dustin
24
EXP NO: 3
AIM: To execute a Queries using Aggregate functions (COUNT, SUM,
AVG, MAX and MIN), GROUP BY, HAVING and Creation and dropping
of Views.
PROCEDURE:
Aggregative operators: In addition to simply retrieving data, we often want to
perform some computation or summarization. SQL allows the use of arithmetic
expressions. We now consider a powerful class of constructs for computing aggregate
values such as MIN and SUM.
1. Count: COUNT following by a column name returns the count of tuple in that
column. If DISTINCT keyword is used then it will return only the count of unique tuple
in the column. Otherwise, it will return count of all the tuples (including duplicates)
count (*) indicates all the tuples of the column.
Syntax: COUNT (Column name)
Example: SELECT COUNT (Sal) FROM emp;
2. SUM: SUM followed by a column name returns the sum of all the values in that
column.
Syntax: SUM (Column name)
25
Example: SELECT SUM (Sal) From emp;
3. AVG: AVG followed by a column name returns the average value of that column
values.
Syntax: AVG (n1,n2..)
Example: Select AVG(10, 15, 30) FROM DUAL;
4. MAX: MAX followed by a column name returns the maximum value of that column.
Syntax: MAX (Column name)
Example: SELECT MAX (Sal) FROM emp;
SQL> select deptno,max(sal) from emp group by deptno;
DEPTNO MAX(SAL)
------ --------
10 5000
20 3000
30 2850
DEPTNO MAX(SAL)
----- --------
30 2850
5. MIN: MIN followed by column name returns the minimum value of that column.
Syntax: MIN (Column name)
Example: SELECT MIN (Sal) FROM emp;
DEPTNO MIN(SAL)
----- --------
10 1300
VIEW: In SQL, a view is a virtual table based on the result-set of an SQL statement.
26
A view contains rows and columns, just like a real table. The fields in a view are
fields from one or more real tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and
present the data as if the data were coming from one single table.
A view is a virtual table, which consists of a set of columns from one or more
tables. It is similar to a table but it doest not store in the database. View is a query
stored as an object.
Syntax: CREATE VIEW view_name AS SELECT set of fields FROM
relation_name WHERE (Condition)
1. Example:
SQL>CREATE VIEW employee AS SELECT empno,ename,job FROM EMP
WHERE job = clerk;
View created.
SQL> SELECT * FROM EMPLOYEE;
EMPNO ENAME JOB
---- ------ -------
7369 SMITH CLERK
7876 ADAMS CLERK
7900 JAMES CLERK
7934 MILLER CLERK
2.Example:
DROP VIEW: This query is used to delete a view , which has been already created.
Syntax: DROP VIEW View_name;
Example : SQL> DROP VIEW EMPLOYEE;
View dropped
27
EXP NO: 4
AIM: To execute 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)
PROCEDURE:
1. Conversion functions:
To_char: TO_CHAR (number) converts n to a value of VARCHAR2 data type, using
the optional number format fmt. The value n can be of
type NUMBER, BINARY_FLOAT, or BINARY_DOUBLE.
LXV
28
To_date: TO_DATE converts char of CHAR, VARCHAR2, NCHAR,
or NVARCHAR2 data type to a value of DATE data type.
SQL>SELECT TO_DATE('January 15, 1989, 11:00 A.M.')FROM DUAL;
TO_DATE('
---------
15-JAN-89
2. String functions:
Concat: CONCAT returns char1 concatenated with char2. Both char1 and char2 can
be any of the datatypes
SQL>SELECT CONCAT(ORACLE,CORPORATION)FROM DUAL;
ORACLECORPORATION
Lpad: LPAD returns expr1, left-padded to length n characters with the sequence of
characters in expr2.
SQL>SELECT LPAD(ORACLE,15,*)FROM DUAL;
*********ORACLE
Rpad: RPAD returns expr1, right-padded to length n characters with expr2, replicated
as many times as necessary.
SQL>SELECT RPAD (ORACLE,15,*)FROM DUAL;
ORACLE*********
Instr: The INSTR functions search string for substring. The function returns an
integer indicating the position of the character in string that is the first character of this
occurrence.
SQL>SELECT INSTR('CORPORATE FLOOR','OR',3,2)FROM DUAL;
14
3. Date functions:
Sysdate:
SQL>SELECT SYSDATE FROM DUAL;
29-DEC-08
next_day:
SQL>SELECT NEXT_DAY(SYSDATE,WED)FROM DUAL;
05-JAN-09
add_months:
SQL>SELECT ADD_MONTHS(SYSDATE,2)FROM DUAL;
28-FEB-09
last_day:
30
SQL>SELECT LAST_DAY(SYSDATE)FROM DUAL;
31-DEC-08
months_between:
SQL>SELECT MONTHS_BETWEEN(SYSDATE,HIREDATE)FROM EMP;
4
Least:
SQL>SELECT LEAST('10-JAN-07','12-OCT-07')FROM DUAL;
10-JAN-07
Greatest:
SQL>SELECT GREATEST('10-JAN-07','12-OCT-07')FROM DUAL;
10-JAN-07
Trunc:
SQL>SELECT TRUNC(SYSDATE,'DAY')FROM DUAL;
28-DEC-08
Round:
SQL>SELECT ROUND(SYSDATE,'DAY')FROM DUAL;
28-DEC-08
to_char:
SQL> select to_char(sysdate, "dd\mm\yy") from dual;
24-mar-05.
to_date:
SQL> select to_date(sysdate, "dd\mm\yy") from dual;
24-mar-o5.
31
PL/SQL
32
EXP NO: 5 PL/SQL Introduction
AIM: (i)To write a PL/SQL program declaration selection, executable
selection and Exception Handling.
ii) To insert data into student table and use COMMIT, ROLLBACK
and SAVEPOINT using PL/SQL block.
DESCRIPTION:
PL/SQL stands for Procedural Language extension of SQL. PL/SQL is a
combination of SQL along with the procedural features of programming languages. It
was developed by Oracle Corporation in the early 90s to enhance the capabilities of
SQL.
Oracle uses a PL/SQL engine to processes the PL/SQL statements. A PL/SQL
code can be stored in the client system (client-side) or in the database (server-side).
Advantages of PL/SQL:
Block Structures: PL SQL consists of blocks of code, which can be nested
within each other. Each block forms a unit of a task or a logical module.
PL/SQL Blocks can be stored in the database and reused.
33
Procedural Language Capability: PL SQL consists of procedural language
constructs such as conditional statements (if else statements) and loops like
(FOR loops).
Better Performance: PL SQL engine processes multiple SQL statements
simultaneously as a single block, thereby reducing network traffic.
Error Handling: PL/SQL handles errors or exceptions effectively during the
execution of a PL/SQL program. Once an exception is caught, specific actions
can be taken depending upon the type of the exception or it can be displayed to
the user with a message.
Variable declaration;
Begin
Executable statements;
end;
34
1) IF condition THEN
statement 1;
ELSE
statement 2;
END IF;
2) IF condition 1 THEN
statement 1;
statement 2;
ELSIF condtion2 THEN
statement 3;
ELSE
statement 4;
END IF
PROCEDURE:
5. Write a PL/SQL program to find the total and average of 4 subjects and
display the grade
declare
java number(10);
dbms number(10);
co number(10);
mfcs number(10);
total number(10);
avgs number(10);
per number(10);
begin
dbms_output.put_line('ENTER THE MARKS');
35
java:=&java;
dbms:=&dbms;
co:=&co;
mfcs:=&mfcsl;
total:=(java+dbms+co+mfcs);
per:=(total/600)*100;
if java<40 or dbms<40 or co<40 or mfcs<40 then
dbms_output.put_line('FAIL');
if per>75 then
dbms_output.put_line('GRADE A');
elsif per>65 and per<75 then
dbms_output.put_line('GRADE B');
elsif per>55 and per<65 then
dbms_output.put_line('GRADE C');
else
dbms_output.put_line('INVALID INPUT');
end if;
dbms_output.put_line('PERCENTAGE IS '||per);
end;
/
OUTPUT:
SQL> @ GRADE.sql
Enter value for java: 80
old 11: java:=&java;
new 11: java:=80;
Enter value for dbms: 70
old 12: dbms:=&dbms;
36
new 12: dbms:=70;
Enter value for co: 89
old 13: co:=&co;
new 13: co:=89;
Enter value for mfcs: 71
old 14: mfcs:=&mfcs;
new 14: mfcs:=71;
GRADE A
PERCENTAGE IS 77
PL/SQL procedure successfully completed.
37
else
dbms_output.put_line('C IS GREATER');
end if;
end;
/
OUTPUT:
SQL> @ GREATESTOF3.sql
Enter value for a: 8
old 6: a:=&a;
new 6: a:=8;
Enter value for b: 9
old 7: b:=&b;
new 7: b:=9;
Enter value for c: 7
old 8: c:=&c;
new 8: c:=7;
B IS GREATER
PL/SQL procedure successfully completed.
38
EXP NO: 7 Loops in PL/SQL
AIM: Write a PL/SQL program by using WHILE LOOPS and FOR
LOOPS.
DESCRIPTION:
There are three types of loops in PL/SQL:
1. Simple Loop
2. While Loop
3. For Loop
1. Simple Loop: A Simple Loop is used when a set of statements is to be executed at
least once before the loop terminates. An EXIT condition must be specified in the
loop, otherwise the loop will get into an infinite number of iterations. When the EXIT
condition is satisfied the process exits from the loop.
Syntax:
LOOP
statements;
EXIT;
{or EXIT WHEN condition ;}
END LOOP;
39
2. While Loop: A WHILE LOOP is used when a set of statements has to be executed
as long as a condition is true. The condition is evaluated at the beginning of each
iteration. The iteration continues until the condition becomes false.
Syntax:
WHILE <condition>
LOOP statements;
END LOOP;
40
dbms_output.put_line(b);
for i in 1..n-2
loop
c:=a+b;
dbms_output.put_line(c);
a:=b;
b:=c;
end loop;
end;
/
OUTPUT:
SQL> @ FIBONACCI.sql
Enter value for n: 3
old 8: n:=&n;
new 8: n:=3;
0
1
1
PL/SQL procedure successfully completed.
41
EXP NO: 8 CREATING PROCEDURES
PROGRAM:
declare
a number;
rev number;
d number;
begin
a:=&a;
rev:=0;
while a>0
loop
d:=mod(a,10);
rev:=(rev*10)+d;
a:=trunc(a/10);
end loop;
dbms_output.put_line('no is'|| rev);
42
end;
/
OUTPUT:
SQL> @ REVERSE2.sql
Enter value for a: 536
old 6: a:=&a;
new 6: a:=536;
no is 635
43
Exp no:9 FUNCTIONS
AIM: To write a PL/SQL program to a funtion for finding the factorial of given number.
PROGRAM:
create a funtion fact (n in number)
return number is c number(3);
BEGIN
if n=0 or n=1 then
c:=1;
else
c:=n*fact(n-1);
end if;
return(c)
end;
/
OUTPUT:
funtion is created.
44
Aim: write a PL/SQL block to apply string functions on a given input string.
PROGRAM:
DECLARE
A varchar2(20);
I number(5);
a:=&a;
I:=length(a);
dbms_RESULT.put_line(Using Lower Function:||lower(a));
dbms_RESULT.put_line(Using UPPER Function:||upper(a));
END;
OUTPUT:
SQL>@STR
Enter value for a: santosh reddy
old 5: a=&a;
new 5: a:=santosh reddy;
Using Lower Function:santosh reddy
Using Upper Function:SANTOSHREDDY
PL/SQL procedure successfully completed
45
..
AIM :- Write a trigger on sailors table that runs for every insert statement that should
have age value <18.
THEORY:
Syntax :- create a trigger trigger name before insert update on table name.
create a trigger trigger name after insert update on table name.
PROGRAM :-
46
create trigger T1 before insert on sailors for each row
when (new.age<18)
begin
raise-application-error('-2008','U cant insert the record');
end;
/
OUTPUT :-
trigger created
SQL>select * from sailors
SQL>insert into sailors values('Jeevani',28,'Margo');
47