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

Dbms Lab Record

The document outlines experiments performed in a database management systems laboratory class, including creating tables, inserting, updating, and deleting data, joining tables, using cursors and triggers, and developing applications using an SQL database. It provides the name of the student, register number, experiments conducted with dates, and an index of the experiments.

Uploaded by

Rogith M
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
157 views

Dbms Lab Record

The document outlines experiments performed in a database management systems laboratory class, including creating tables, inserting, updating, and deleting data, joining tables, using cursors and triggers, and developing applications using an SQL database. It provides the name of the student, register number, experiments conducted with dates, and an index of the experiments.

Uploaded by

Rogith M
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 135

1

VELAMMAL INSTITUTE OF TECHNOLOGY


(Approved by AICTE & Affiliated to Anna University)

Velammal Knowledge Park, Panchetti, Chennai - 601204

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CS8481 – DATABASE MANAGEMENT SYSTEMS LABORATORY

NAME OF THE STUDENT : SURENDAR.S

REGISTER NUMBER : 113319104087

YEAR : II

SEMESTER : IV
2

VELAMMAL INSTITUTE OF TECHNOLOGY


(Approved by AICTE & Affiliated to Anna University)

Velammal Knowledge Park, Panchetti,

Chennai - 601 204

BONAFIDE CERTIFICATE

Register number: 113319104087

Certified that this is a Bonafide Record of Practical Work done by Mr SURENDAR.S…………of B.E .
……………………CSC…………………………… in CS8481 – DATABASE MANAGEMENT SYSTEMS

LABORATORY during the academic year 2020-2021.

Staff-in-Charge Head of the Department

Submitted for the Practical Examination held on …………………………..


3

INTERNAL EXAMINER EXTERNAL EXAMINER

INDEX
S. No DATE NAME OF THE EXPERIMENTS Page No
1. 24.02.2021 Implementation of Data Definition Language 4
2. 03.03.2021 Implementation of Data Manipulation Language 8
3. 10.03.2021 Implementation of Nested Queries in SQL 19
4. 24.03.2021 Implementation of Join Operations in SQL 26
Implementation of Views, Synonyms, Sequence,
5. 31.03.2021 37
Indexes, Save point
6. 07.04.2021 Implementation of Implicit and Explicit Cursors 44
7. 21.04.2021 Implementation of Integrity Constraints 47
8. 28.04.2021 Study of PL / SQL Block 57
Implementation of Programming Language
9. 28.04.2021 69
Extensions to Satisfy Conditions
Implementation of Procedures and Functions in
10. 12.05.2021 77
PL/SQL
11. 12.05.2021 Implementation of Triggers in SQL 89
Implementation of PL / SQL Blocks - Handling
12. 24.05.2021 93
Exceptions
Implementation of Library Information System
13. 24.05.2021 99
using VB
Implementation of Student Information System
14. 26.05.2021 112
using VB
15. 26.05.2021 Implementation of Simple calculator using VB 122
4

Ex. No: 1
Data Definition Language
Date: 24.02.2021

Aim

To write SQL Statements using Data Definition Language (DDL) to create, alter, truncate and
drop table.

Description:

Data Definition Language

The Data Definition Language (DDL) is used to

 Creating a table 

 Altering table structure by adding, deleting or modifying columns

 Destroy databases and database objects. 

These commands will primarily be used by database administrators during the setup and
removal phases of a database project.

CREATE TABLE COMMANDS

SQL> create table stud (snamevarchar2(30), sid varchar2(10), sage number(2),


sarea varchar2(20));

Table created.

SQL>desc stud;
Name Null? Type

----------------------------------------------------- -------- --------------------------------


5

SNAME VARCHAR2(30)

SID VARCHAR2(10)

SAGE NUMBER(2)
SAREA VARCHAR2(20)

ALTER TABLE

SQL>alter table stud modify ( sage number(10));

Table altered.
SQL>desc stud;
Name Null? Type
----------------------------------------------------- -------- --------------------------------

SNAME VARCHAR2(30)
SID VARCHAR2(10)

SAGE NUMBER(10)
SAREA VARCHAR2(20)

SQL> alter table stud add ( sdept varchar2(20));

Table altered.

SQL>desc stud;
Name Null? Type

----------------------------------------------------- -------- --------------------------------


SNAME VARCHAR2(30)
SID VARCHAR2(10)

SAGE NUMBER(10)
SAREA VARCHAR2(20)

SDEPT VARCHAR2(20)

SQL> alter table stud drop (sdeptvarchar2(20));

Table altered.

SQL>desc studs;
6

Name Null? Type

----------------------------------------------------- -------- ------------------------------------


SNAME VARCHAR2(30)

SID VARCHAR2(10)
SAGE NUMBER(10)
SAREA VARCHAR2(20)

TRUNCATE TABLE

TRUNCATE TABLE removes all rows from a table, but the table structure and its columns,
constraints, indexes and so on remain.

SQL> truncate table studs;


Table truncated.

SQL>desc studs;

Name Null? Type


----------------------------------------------------- -------- ------------------------------------

SNAME VARCHAR2(30)
SID VARCHAR2(10)

SAGE NUMBER(10)
SAREA VARCHAR2(20)
SDEPT VARCHAR2(20)

DROP TABLE

DROP TABLE removes one or more table definitions completely from the database,by
removing all data, indexes, triggers, constraints, and permission specifications for
those tables.

SQL> drop table studs;

Table dropped.
7

Result

Thus the Data Definition Language (DDL) statements were successfully implemented.
8

Ex. No: 2
Data Manipulation Language
Date: 3-3-2021

Aim

To write Insert, Select, Update, and Delete Commands in Data Manipulation Language (DML)

using SQL

COMMANDS

CREATION OF TABLE

SQL>create table stud (snamevarchar2(30), sid varchar2(10), sage


number(10), sarea varchar2(20), sdept varchar2(20));

Table created.
INSERTION OF VALUES INTO THE TABLE

Syntax:

INSERT INTOtable (column1, [column2, ... ]) VALUES (value1, [value2, ...])

INSERT INTOtableVALUES (value1, [value2, ...])

SQL> insert into stud values ('ashwin',101,19,'anna nagar','aeronautical');

1 row created.

SQL> insert into stud values ('bhavesh',102,18,'nungambakkam','marine');

1 row created.

SQL> insert into stud values ('pruthvik',103,20,'anna


nagar','aerospace'); 1 row created.

SQL> insert into stud values ('charith',104,20,'kilpauk','mechanical');

1 row created.
SQL> select * from stud;
9

SNAME SID SAGE SAREA SDEPT


------------------------------ ---------- --------- -------------------- --------------------

ashwin 101 19 annanagar aeronautic


al
bhavesh 102 18 marine
nungambakkam
pruthvik 103 20 annanagar aerospace
charith 104 20 kilpauk mechanica
l

RENAMING THE TABLE ‗STUD‘

SQL> rename stud to studs;


Table renamed.

ARITHMETIC OPERATION

SQL> select sname, sid+100 "stid" from studs;


SNAME stid

------------------------------ ---------
ashwin 201
bhavesh 202

pruthvik 203
charith 204

CONCATENATION OPERATOR

SQL> select sname || ' is a ' || sdept || ' engineer. ' AS "PROFESSION" from studs;

PROFESSION
-------------------------------------------------------------------

ashwin is a aeronautical engineer.

bhavesh is a marine engineer.

pruthvik is a aerospace engineer.

charith is a mechanical engineer.

DISPLAY ONLY DISTINCT VALUES


SQL> select distinct sarea from
10

studs; SAREA
--------------------

annanagar

kilpauk

nungambakkam

USING THE WHERE CLAUSE


SQL> select sname,sage from studs where sage<=19;

SNAME SAGE
------------------------------ ---------

ashwin 19
bhavesh 18
BETWEEN OPERATOR

SQL> select sname,sarea, sid from studs where sid between 102 and 104;

SNAME SAREA SID


------------------------------ -------------------- ----------
bhaveshnungambakkam 102

pruthvikannanagar 103
charithkilpauk 104

IN PREDICATE
SQL> select sname,sarea , sid from studs where sid in(102,104);

SNAME SAREA SID


------------------------------ -------------------- ----------

bhaveshnungambakkam 102

charithkilpauk 104

PATTERN MATCHING
SQL> select sname, sarea from studs where sarea like '%g%';

SNAME SAREA
------------------------------ --------------------

ashwinannanagar
11

bhaveshnungambakkam

pruthvikannanagar

LOGICAL AND OPERATOR

SQL> select sname ,sid from studs where sid>102 and sarea='annanagar';

SNAME SID

------------------------------ ----------
pruthvik 103

LOGICAL OR OPERATOR
SQL> select sname ,sid from studs where sid>102 or sarea='annanagar';

SNAME SID
------------------------------ ----------

ashwin 101
pruthvik 103

charith 104
NOT IN PREDICATE
SQL> select sname, sid from studs where sid not in(102,104);

SNAME SID

------------------------------ ----------
ashwin 101
pruthvik 103

UPDATING THE TABLE


Syntax:

UPDATEtable_nameSETcolumn_name = value [, column_name = value ...]


[WHEREcondition];

SQL> alter table studs add ( spocket varchar2(20) );

Table altered.

SQL> update studs set spocket=750 where sid=101;


12

1 row updated.

SQL> update studs set spocket=500 where sid=102;

1 row updated.

SQL> update studs set spocket=250 where sid=103;

1 row updated.

SQL> update studs set spocket=100 where sid=104;

1 row updated.

SQL> select * from studs;

SNAME SID SAGE SAREA SDEPT


------------------------------ ---------- --------- -------------------- --------------------

SPOCKET
--------------------

ashwin 101 19 annanagar aeronautic


al
750
bhavesh 102 18 nungambakka marine
m
500
pruthvik 103 20 annanagar aerospace
250
charith 104 20 Kilpauk mechanical
100
AGGREGATE FUNCTIONS

SQL> select avg(spocket ) result from studs;

RESULT
------------
400
SQL> select resu from studs;
min(spocket) lt
RESULT
-------------
100
13

SQL> select result from studs;


count(spocket)
RESULT
------------
4
SQL> select count(*) from studs;
result
RESULT
------------
4

SQL> select count(spocket) result from studs where sarea='annanagar';


RESULT
------------

SQL> select max(spocket) result from


studs;
RESULT
------------
750

SQL> select sum(spocket) result from


studs; RESULT
------------
1600

NUMERIC FUNCTIONS

SQL> select abs(-20) result from


dual;
RESULT

-------------
20

SQL> select power (2,10) result from


dual;
RESULT

---------
1024

SQL> select round(15.359,2) result from


14

dual;
RESULT

---------
15.36

SQL> select sqrt (36) result from


dual;
RESULT

---------
6

STRING FUNCTIONS

SQL> select lower('ORACLE') result from


dual;
RESULT

------
oracle

SQL> select initcap('Oracle') result from dual;


RESULT
------

Oracle

SQL> select substr('oracle' ,2 ,5) result from dual;


RESULT

-----
racle

SQL> select lpad('oracle',10,'#') result from dual;


RESULT

----------
####oracle

SQL> select rpad ('oracle',10,'^') result from dual;


RESULT

----------
oracle^^^^
15

CONVERSION FUNCTIONS

SQL> update studs set sage=to_number(substr(118,2,3));

4 rows updated.
SQL> select * from studs;

SNAME SID SAGE SAREA SDEPT SPOCKET


-------------------- ---------- --------- -------------------- --------------------
ashwin 101 18 annanagar aeronauti 750
cal
bhavesh 102 18 nungambakka marine 500
m
pruthvik 103 18 annanagar aerospac 250
e
charith 104 18 kilpauk mechani 100
cal
SQL> select to_char( 17145, result from
'099,999') dual;
RESULT

--------
017,145

SQL> select to_char(sysdate,'dd-mon-yyyy') result from dual;

RESULT

-----------
16-jul-2008

DATE FUNCTIONS

SQL> select sysdate from dual;

SYSDATE

---------
16-JUL-08

SQL>select sysdate,add_months(sysdate,4) result from dual;

SYSDATE RESULT
--------- ---------
16

16-JUL-08 16-NOV-08

SQL> select sysdate, last_day(sysdate) result from dual;

SYSDATE RESULT

--------- ---------
16-JUL-08 31-JUL-08

SQL>select sysdate, next_day(sysdate,'sunday') result from dual;

SYSDATE RESULT
--------- ---------
16-JUL-08 20-JUL-08

SQL> select months_between('09-aug-91','11-mar-90') result from dual;

RESULT
---------

16.935484

GROUP BY CLAUSE

SQL> select sarea, sum(spocket) result from studs group by sarea;

SAREA RESULT

-------------------- ------------
annanagar 1000
nungambakkam 500

kilpauk 100

HAVING CLAUSE

SQL> select sarea, sum(spocket) result from studs group by sarea having spocket<600;

SAREA RESULT
-------------------- ------------
nungambakkam 500
kilpauk 100
DELETION
17

Syntax:

DELETE FROM table_name [WHERE condition]

SQL> delete from studs where sid=101;

1 row deleted.

SQL> select * from studs;

SNAME SID SAGE SAREA SDEPT SPOCKET

------------------------------ ---------- --------- -------------------- -------------------- -------------------

bhavesh 102 18 nungambakka marine 500


m
pruthvik 103 20 annanagar aerospace 250
charith 104 20 kilpauk mechanica 100
l

CREATING TABLES FOR DOING SET OPERATIONS

TO CREATE PRODUCT TABLE

SQL> create table product(prodname varchar2(30), prodno varchar2(10));

Table created.

SQL> insert into product values('table',10001);

1 row created.

SQL> insert into product


values('chair',10010); 1 row created.

SQL> insert into product


values('desk',10110); 1 row created.

SQL> insert into product


values('cot',11110); 1 row created.
SQL> insert into product
values('sofa',10010); 1 row created.
18

SQL>

SQL> insert into product


values('tvstand',11010); 1 row created.

SQL> select * from product;

PRODNAME PRODNO
------------------------------ ----------

table 10001

chair 10010

desk 10110
cot 11110
sofa 10010

tvstand 11010

TO CREATE SALE TABLE

SQL> create table sale(prodname varchar2(30),orderno


number(10),prodno varchar2(10)); Table created.

SQL> insert into sale


values('table',801,10001); 1 row created.

SQL> insert into sale


values('chair',805,10010); 1 row created.

SQL> insert into sale


values('desk',809,10110); 1 row created.

SQL> insert into sale


values('cot',813,11110); 1 row created.

SQL> insert into sale


values('sofa',817,10010); 1 row created.

SQL> select * from sale;

PRODNAME ORDERNO PRODNO


------------------------------ --------- ----------
Table 801 10001
19

Chair 805 10010


Desk 809 10110

Cot 813 11110


Sofa 817 10010

SET OPERATIONS

SQL> select prodname from product where prodno=10010 union select prodname
from sale where prodno=10010;

PRODNAME
------------------
Chair

Sofa

SQL> select prodname from product where prodno=11110 intersect select prodname
from sale where prodno=11110;
PRODNAME

------------------
Cot

Result

Thus the DML commands using SQL were executed successfully.


20

Ex. No: 3
Nested Queries
Date: 10-03-2021

Aim

To write an SQL application that creates tables and perform certain operations based
on the concept of nested queries.

GIVEN APPLICATION

Given relational schema are


sempls ( eno primary key, ename, edob, gender,doj,desg, bpay, dno)
sdments ( dno, dname)
spros( pno primary key,pname,dno)
sworks ( eno , pno , datework, intime, outtime)

A department can control any number of projects but a project is controlled only by one
department. An employee can work in any number of projects on a day but an employee is
not permitted to work more than once on a project on the same day. Develop suitable
queries.

TO CREATE ‗SEMPLS‘ TABLE

SQL> create table sempls( eno number(10) primary key, ename varchar2(10),
edob varchar2(15), gender varchar2(10), doj varchar2(15),desg varchar2(30),
bpay number(10), dno number(10));

Table created.

SQL> insert into sempls values( 1, 'bala','15/1/84','m','16th july','lec',7000,1);

1 row created.

SQL> insert into sempls values( 2,


'kala','13/9/84','m','18th july','lec',10000,2); 1 row
created.

SQL> insert into sempls values( 3, 'mala','17th june','f','19th june','lec',19000,1);

1 row created.
21

SQL> insert into sempls values(4, 'nila','20th june','f','19th june','sr.lec',20000,1);

1 row created.

SQL> insert into sempls values( 5, 'vina','2nd jan','f','12th july','prof.',50000,2);


22

1 row created.

SQL> select * from sempls;

ENO ENAME EDOB GENDER DOJ DESG BPAY DNO


--------- ---------- --------------- ---------- --------------- -------------------------------------- ---------
1 bal 15/1/84 M 16th july lec 7000 1
a
2 kala 13/9/84 M 18th july lec 10000 2
3 mal 17th june F 19th lec 19000 1
a june
4 nila 20th june F 19th sr.lec 20000 1
june
5 vina 2nd jan F 12th july prof. 50000 2

TO CREATE ‗SDMENTS‘ TABLE

SQL> create table sdments( dno number(10), dname varchar2(30)); Table created.

SQL> insert into sdments values (1, 'cse');


1 row created.

SQL> insert into sdments values (2, 'it');


1 row created.

SQL> select * from sdments;

DNO DNAME
--------- ------------------------------
1 cse

2 it

TO CREATE ‗SPROS‘ TABLE

SQL> create table spros (pno number(20) primary key,


pname varchar2(30),dno number(10)); Table created.

SQL> insert into spros values(81, 'aaa',1);


1 row created.

SQL> insert into spros values(82, 'bbb',1);


23

1 row created.

SQL> insert into spros values(83, 'ccc',1);

1 row created.

SQL> insert into spros values(84, 'ddd',2);


1 row created.
24

SQL> insert into spros values (85,


'eee',2); 1 row created.
SQL> select * from spros;

PNO PNAME DN
O
------- ------------------------------ ---------
--
81 aaa 1
82 bbb 1
83 ccc 1
84 ddd 2
85 Eee 2

TO CREATE SWORKS TABLE

SQL> create table sworks (eno number(10) , pno number(20) , date work
varchar2(20) , intime number(10),outtime number(10));

Table created.

SQL> insert into sworks values(1,81,'11th july',9,10);


1 row created.

SQL> insert into sworks values(1,82,'11th july',10,11);


1 row created.

SQL> insert into sworks values(1,83,'11th july',11,12);


1 row created.

SQL> insert into sworks values(1,84,'11th july',12,1);


1 row created.

SQL> insert into sworks values(1,85,'11th july',1,2);


1 row created.

SQL> insert into sworks values(2,85,'12th july',8,9);


1 row created.

SQL> select * from sworks;


ENO PNO DATEWORK INTIME OUTTIM
E
--------- --------- -------------------- --------- ---------
1 81 11th july 9 10
25

1 82 11th july 10 11
1 83 11th july 11 12
1 84 11th july 12 1
1 85 11th july 1 2
2 85 12th july 8 9

QUERY 1

This querylists the details of employees who earn a basic pay that is less than the
average basic pay of the employees.

SQL> select * from sempls where bpay < (select avg(bpay) from sempls);

ENO ENAME EDOB GENDER DOJ DESG BPAY DNO


---------- --------------- ------------------ ------- ------------------ ------------ ---------
1 bala 15/1/8 m 16th july lec 7000 1
4
2 kala 13/9/8 m 18th july lec 10000 2
4
3 mala 17th f 19th june lec 19000 1
june
4 nila 20th f 19th sr.lec 20000 1
june june
QUERY 2

This query lists the department number , number of employees in


each
department. SQL> select dno,count(eno) from sempls group by dno;
DNO COUNT(ENO)
-------- ----------
-
1 3

2 2

QUERY 3

This query lists the details of employees who earn a basic pay in the range 10000 to
20000. SQL> select * from sempls where bpay between 10000 and 20000;

ENO ENAME EDOB GENDER DOJ DESG BPAY DNO


----- -------- ---------- ----------- ------- --------------- ------------------------------
-- -
2 kala 13/9/8 M 18th lec 10000 2
26

4 july
3 mala 17th F 19th lec 19000 1
june june
4 nila 20th F 19th sr.le 20000 1
june june c

QUERY 4

This query lists the details of employees who have worked in projects controlled
by department name = cse.

SQL> select * from sempls, sdments,spros where


sdments.dno=spros.dno and sdments.dno=sempls.dno and
dname='cse';

QUERY 5

This query lists the employee number, employee name, department number, date worked if
the employee has worked in more than 4 projects on a day.

SQL> select sempls.eno,ename,dno,datework from sempls,sworks where sempls.eno


in(select eno from (select eno,datework from sworks group by eno,datework having
count(pno)>4)) and datework in (select datework from (select eno,datework from
sworks group by eno,datework having count(pno)>4));

ENO ENAME DNO DATEWORK


--------- ---------- --------- --------------------
1 bala 1 11th
july
1 bala 1 11th
july
1 bala 1 11th
july
1 bala 1 11th
july
27

Result

Thus the application for nested queries was implemented successfully.


28

Ex. No: 4
Join Operation
Date: 24-03-2021

Aim

To study and implement various Join operations in SQL

Description

JOINS
INNER Join

This is a simple JOIN in which the result is based on matched data as per the equality condition
specified in the query.

Inner Join Syntax is,

SELECT column-name-list from table-name1 INNER JOIN table-name2 WHERE table-


name1.column-name = table-name2.column-name;

Example:

The class table,

ID NAME

1 abhi
2 adam

3 alex
4 anu

The class_info table,

ID Address
1 DELHI

2 MUMBAI
3 CHENNAI
29

SELECT * from class, class_info where class.id = class_info.id;

The result table is,

ID NAME ID Address
1 abhi 1 DELHI
2 ada 2 MUMBA
m I
3 alex 3 CHENNA
I

Natural JOIN

Natural Join is a type of Inner join which is based on column having same name and same
datatype present in both the tables to be joined.

Natural Join Syntax is,

SELECT * from table-name1 NATURAL JOIN table-name2;

Example:

The class table,

ID NAME

1 abhi

2 adam
3 alex

4 anu

The class_info table,

ID Address

1 DELHI
2 MUMBAI

3 CHENNAI
30

SELECT * from class NATURAL JOIN class_info;

The result table is,


31

ID NAME Address

1 abhi DELHI
2 adam MUMBAI

3 alex CHENNAI

Outer JOIN

Outer Join is based on both matched and unmatched data. Outer Joins subdivide further into,

Left Outer Join


Right Outer Join

Full Outer Join

Left Outer Join

The left outer join returns a result table with the matched data of two tables then remaining
rows of the left table and null for the right table's column.

Left Outer Join syntax is,

SELECT column-name-list from table-name1 LEFT OUTER JOIN table-


name2 on table-name1.column-name = table-name2.column-name;

Left outer Join Syntax for Oracle is,

select column-name-list from table-name1, table-name2 on table-name1.column-


name = table-name2.column-name(+);

Example:

The class table,

ID NAME

1 abhi
2 adam

3 alex
4 anu

5 ashish
32

The class_info table,

ID Address
33

1 DELHI

2 MUMBAI
3 CHENNAI

7 NOIDA
8 PANIPAT

Left Outer Join query will be,

SELECT * FROM class LEFT OUTER JOIN class_info ON (class.id=class_info.id);

The result table is,

ID NAME ID Address
1 abh 1 DELHI
i
2 ada 2 MUMBA
m I
3 alex 3 CHENNA
I
4 anu nul null
l
5 ashish null null

Right Outer Join

The right outer join returns a result table with the matched data of two tables
then remaining rows of the right table and null for the left table's columns.

Right Outer Join Syntax is,

select column-name-list from table-name1 RIGHT OUTER JOIN table-name2 on


table-name1.column-name = table-name2.column-name;

Right outer Join Syntax for Oracle is,

select column-name-list from table-name1, table-name2 on table-name1.column-


name(+) = table-name2.column-name;

Example :

The class table,


34

ID NAME
1 abhi
2 adam

3 alex
4 anu

5 ashish
35

The class_info table,

ID Address
1 DELHI

2 MUMBAI
3 CHENNAI
7 NOIDA

8 PANIPAT

Right Outer Join query will be,

SELECT * FROM class RIGHT OUTER JOIN class_info on (class.id=class_info.id);

The result table is,

ID NAME ID Address
1 abhi 1 DELHI

2 ada 2 MUMBA
m I
3 alex 3 CHENNA
I
Nu null 7 NOIDA
ll
Nu null 8 PANIPA
ll T

Full Outer Join

The full outer join returns a result table with the matched data of two table then remaining
rows
of both left table and then the right table.

Full Outer Join Syntax is,

select column-name-list from table-name1 FULL OUTER JOIN table-name2 on


table-name1.column-name = table-name2.column-name;

Example:

The class table,

ID NAME
36

1 abhi

2 adam
3 alex
4 anu

5 ashish

The class_info table,


37

ID Address

1 DELHI
2 MUMBAI
3 CHENNAI

7 NOIDA
8 PANIPAT

Full Outer Join query will be like,

SELECT * FROM class FULL OUTER JOIN class_info on (class.id=class_info.id);

The result table is

ID NAME ID Address
1 abhi 1 DELHI

2 ada 2 MUMBA
m I
3 alex 3 CHENNA
I
4 anu nul null
l
5 ashi nul null
sh l
Nu null 7 NOIDA
ll
Nu null 8 PANIPA
ll T
38

Result

Thus the various Join operations in SQL were implemented.


39

Ex. No : Views, Synonyms, Sequence, Indexes, Save point


5

Date :
31- 03-
2021

Aim:

To Implement Simple Views, Complex Views Synonyms, Sequence, Indexes and Save point.
Description:

View

Syntax:

CREATE [OR REPLACE] VIEW view_name


AS (select query)

CREATE VIEW view_stud


A
S
SELECT registerno FROM student;
This command creates a new view called VIEW_STUD

We can query this view view like this:


SELECT * FROM view_stud WHERE registerno BETWEEN 11305205001 AND 1130520506

1. Create a View that holds only the Branch name. Name the View as Branch_Name_View

Ans:

Create view branch_name_view as select Branch name from student;

SQL> select * from Branch_Name_View;

BRANCHNAME
------------------------------
Civil

Computer Science

Electrical
Electronics

Information Technology
40

Instrumentation

Mechanical
MBA
MCA
9 rows selected.

2. Create a View that holds Branch Number and Average Mark of Each Branch. Name the
view as Average_Mark_View.

Give alias name for columns as follow

Column Alias
Name
Avg(Mark) - Average
Mark
Branchno - Branch
Number

Create view Average_Mark_View as select Avg(Mark) Average Mark, Branchno Branch


Number from student;

SQL> select * from Average_Mark_View;

BRANCHNO Average Mark

---------- ------------

1 71.5
2 92.6666667
3 90
4 75

5 100
6 85
7 82.5

7 rows selected.
Synonym

A synonym is an alternative name for objects such as tables, views, sequences, stored
procedures, and other database objects

Syntax
41

CREATE SYNONYM synonym_name for object_name:

SQL>Create synonym E_MP for SCOTT.Emp;


Synonym created

A synonym name E_MP is created for EMP table located in SCOTT schema. Now we can able
to access the EMP table from SYSTEM schema itself(I.E the schema in which you currently
logged in)

SQL>Select COUNT(*) from E_MP;

COUNT(*)

----------------
14

DROP SYNONYM synonym_name;

Drop synonym E_MP ;

This DROP statement would drop the synonym called E_MP that we defined earlier.

SEQUENCE

Create sequence syntax

CREATE SEQUENCE sequence_name

INCREMENT BY n(intervals between sequence numbers)


START WITH n(First sequence number to be generated)
MINVALUE n(Minimum value of a sequence)
MAXVALUE n(Maximum value of a sequence)
CYCLE(recycle even after the sequence reached the minimum or maximum value)
CACHE(Pre allocated values of sequence that are placed in server memory for faster access)

Creation of sequence
42

Example:1

SQL>Create sequence e_id_seq


Minvalue 1

Maxvalue 100
Start with 1

Increment by 1
No cache
No cycle

Sequence created.

USER_SEQUENCES data dictionary tables contain details of the sequence.

Example:2

CREATE SEQUENCE studentid

MINVALUE 1

MAXVALUE 120

START WITH 1

INCREMENT BY 1

CACHE 20;

MAXVALUE 999999999999999999999999999

PSEUDO COLUMN:

Syntax:

Sequence_name.CURRVAL;
43

Sequence_name.NEXTVAL:

Example:
SQL>Select e_id_seq.NEXTVAL from dual;

NEXTVAL
-----------------

1
SQL>Select e_id_seq.CURRVAL from dual;

CURRVAL
-----------------

Example of using sequence in EMP table

SQL>Insert Into EMP Values (e_id_seq.NEXTVAL,’JAK’,’MANAGER’,1234,’01-jan-08’,30)

Sequence is used to insert empno values in the

EMP table.

Example of using sequence to insert value in student table

SQL>INSERT INTO Student VALUES('NANDAKUMARAN',studentid.NEXTVAL,2,'B',

'30-MAY-2005',80,'[email protected]');

Drop Sequence

Once you have created your sequence in Oracle, you might find that you need to remove it

from the database.

Syntax
44

The syntax to a drop a sequence in Oracle is:

DROP SEQUENCE sequence_name;

sequence_name is the name of the sequence that you wish to drop.

For example:

DROP SEQUENCE studentid;

This example would drop the sequence called studentid.

INDEX

Creating an Index

An index can be created manually or automatically:

Manual creation:User can create index manually on columns to speed up the


data retrieval process.

Automatic creation:A unique index is created automatically,when a PRIMARY KEY or


UNIQUE constraint is defined in a table.

Syntax

SQL> CREATE [UNIQUE] INDEX INDEX_NAME ON TABLE_NAME


(COLUMN1,COLUMN2,…COLUMN_N)

Confirming an Index

USER_INDEXES data dictionary view contains the name of the INDEX and its uniqueness.

SQL> Select index_name,index_type,uniqueness from user_indexes;

Example:

CREATE INDEX Student_idx


45

ON student(registerno);

In this example, we've created an index on the student table called student_idx. It consists
of only one field - the registerno field.

We could also create an index with more than one field as in the example below:

CREATE INDEX Student_idx

ON student (registerno,name);

Drop an index

Syntax

The syntax for dropping an index is:

DROP INDEX index_name;

EXAMPLE

DROP INDEX student_idx;


46

Result

Thus the creation of Simple Views, Complex Views Synonyms, Sequence, Indexes and Save
point were successfully completed.

Ex. No :6
Implicit and Explicit Cursors
Date : 7-4-21

Aim :

To implement Implicit and Explicit Cursors.

Procedure:

The oracle engine uses a work area for its internal processing in order to execute an SQL
statement. This work area is private to SQL’s operations and is called a cursor. A cursor is a
mechanism by which you can assign a name to a "select statement" and manipulate the
information within that SQL statement.

There are two types of Cursors.


47

Inplicit Cursors
Explicit Cursors

Both the types of Cursors have following General attributes.

Attribute Name Description

%ISOPEN returns true if cursor is open, false otherwise

%FOUND returns true if record was fetched successfully, false otherwise.


%NOTFOUND returns true if record was not fetched successfully, false otherwise.

%ROWCOUNT returns number of records processed from the cursor.

Implicit cursor attributes can be used to access information about status of last insert,
update, delete or single - row select statement. This can be done by preceding the implicit
cursor attribute with cursor name (i.e. sql)

Explicit cursor is defined in the declarative part of a pl/sql block. This is done by naming the
cursor and mapping it to a query.

The commands used to control the cursor are DECLARE, OPEN, FETCH and CLOSE.

• Oracle/PLSQL: Declare a Cursor

A cursor is a SELECT statement that is defined within the declaration section of your
PLSQL code. We'll take a look at three different syntaxes for cursors.
1. Cursor without parameters (simplest)

The basic syntax for a cursor without parameters is:

CURSOR cursor_name

IS
SELECT_statement;

2. Cursor with parameters

The basic syntax for a cursor with parameters is:

CURSOR cursor_name (parameter_list)

IS
SELECT_statement;

3. Cursor with return clause


48

The basic syntax for a cursor with a return clause is:

CURSOR cursor_name

RETURN field%ROWTYPE
IS

SELECT_statement;

Oracle/PLSQL: OPEN Statement

Once you've declared your cursor, the next step is to open the cursor.

The basic syntax to OPEN the cursor is:

OPEN cursor_name;

Oracle/PLSQL: FETCH Statement

The purpose of using a cursor, in most cases, is to retrieve the rows from your cursor so
that some type of operation can be performed on the data. After declaring and opening
your cursor, the next step is to FETCH the rows from your cursor.

The basic syntax for a FETCH statement is:

FETCH cursor_name INTO <list of variables>;

Oracle/PLSQL: CLOSE Statement

The final step of working with cursors is to close the cursor once you have finished using it.

The basic syntax to CLOSE the cursor is:

CLOSE cursor_name;

Result

Thus the implementation of Implicit and Explicit cursors were successfully completed.
49

Ex. No :7
Integrity Constraints
Date : 21-4-21

Aim

To study the various constraints available in the SQL query language.

DOMAIN INTEGRITY CONSTRAINTS

NOT NULL CONSTRAINT

SQL> create table empl (enamevarchar2(30) not null, eid varchar2(20)


not null);
Table created.

SQL> insert into empl values ('abcde',11);

1 row created.

SQL> insert into empl values ('fghij',12);


1 row created.

SQL> insert into empl values ('klmno',null);

insert into empl values ('klmno',null)

*
ERROR at line 1:

ORA-01400: cannot insert NULL into ("ITA"."EMPL"."EID")

SQL> select * from empl;


ENAME EID
------------------------------ --------------------

abcde 11
fghij 12

CHECK AS A COLUMN CONSTRAINT

SQL> create table depts( dname varchar2(30) not null, did number(20) not null check
(did<10000));
50

Table created.

SQL> insert into depts values ('sales ',9876);


1 row created.

SQL> insert into depts values


('marketing',5432); 1 row created.

SQL> insert into depts values ('accounts',789645);

insert into depts values ('accounts',789645)

*ERROR at line 1:
51

ORA-02290: check constraint (ITA.SYS_C003179)


violated SQL> select * from depts;

DNAME DID
------------------------------ ---------

sales 9876
marketing 5432

CHECK AS A TABLE CONSTRAINT

SQL> create table airports (anamevarchar2(30) not null , aid number(20) not null, acity

varchar2(30) check( acity in


('chennai','hyderabad','bangalore'))); Table created.

SQL> insert into airports values( 'abcde',


100,'chennai'); 1 row created.

SQL> insert into airports values( 'fghij',


101,'hyderabad'); 1 row created.

SQL> insert into airports values( 'klmno',


102,'bangalore'); 1 row created.

SQL> insert into airports values( 'pqrst',


103,'mumbai'); insert into airports values( 'pqrst',
103,'mumbai')
*

ERROR at line 1:
ORA-02290: check constraint (ITA.SYS_C003187) violated

SQL> select * from airports;


ANAME AID ACITY

------------------------------ --------- ------------------------------

abcde 100 chenna


i
fghij 101 hydera
bad
klmno 102 bangal
ore
52

ENTITY INTEGRITY CONSTRAINTS


UNIQUE AS A COLUMN CONSTRAINT

SQL> create table book (bnamevarchar2(30) not null, bid number(20) not
null unique); Table created.

SQL> insert into book values ('fairy tales',1000);


1 row created.

SQL> insert into book values ('bedtime


stories',1001); 1 row created.
53

SQL> insert into book values ('comics',1001);

insert into book values ('comics',1001)

*
ERROR at line 1:

ORA-00001: unique constraint (ITA.SYS_C003130) violated

SQL> select * from book;

BNAME BID

------------------------------ ---------

fairy tales 1000


bedtime stories 1001

UNIQUE AS A TABLE CONSTRAINT

SQL> create table orders(oname varchar2(30) not null , oid number(20) not null

, unique(oname,oid))
; Table created.

SQL> insert into orders values ('chair', 2005);

1 row created.

SQL> insert into orders values ('table',2006);

1 row created.

SQL> insert into orders values ('chair',2007);


1 row created.

SQL> insert into orders values ('chair', 2005);

insert into orders values ('chair', 2005)

*
ERROR at line 1:
54

ORA-00001: unique constraint (ITA.SYS_C003152) violated


SQL> select * from orders;

ONAME OID
------------------------------ ---------
chair 2005

table 2006
chair 2007

PRIMARY KEY AS A COLUMN CONSTRAINT

SQL> create table custo( cname varchar2(30) not null , cid number(20) not
null primary key);

Table created.
55

SQL> insert into custo values ( 'jones', 506);


1 row created.

SQL> insert into custo values ('hayden',508);

1 row created.

SQL> insert into custo values ('ricky',506);

insert into custo values ('ricky',506)

ERROR at line 1:
ORA-00001: unique constraint (ITA.SYS_C003165) violated

SQL> select * from custo;


CNAME CID

------------------------------ ---------
jones 506
hayden 508

PRIMARY KEY AS A TABLE CONSTRAINT

SQL> create table branches(bname varchar2(30) not null , bid number(20) not
null , primary key(bname,bid));

Table created.

SQL> insert into branches values ('annanagar',


1005); 1 row created.

SQL> insert into branches values ('adyar',1006);


1 row created.

SQL> insert into branches values ('anna


nagar',1007); 1 row created.

SQL> insert into branches values ('annanagar',


1005); insert into branches values ('annanagar',
1005)

*
56

ERROR at line 1:

ORA-00001: unique constraint (ITA.SYS_C003173) violated

SQL> select * from branches;

BNAME BID
------------------------------ ---------

annanagar 1005
adyar 1006
annanagar 1007
57

REFERENTIAL INTEGRITY CONSTRAINTS

TO CREATE ‘DEPTS’ TABLE

SQL> create table depts(city varchar2(20), dno number(5) primary key);


Table created.

SQL> insert into deptsvalues('chennai', 11);


1 row created.

SQL> insert into deptsvalues('hyderabad', 22);


1 row created.

TO CREATE ‘SEMP’ TABLE


SQL> create table varchar2(20), dno number(5) references
semp(ename depts(dno));
Table
created.
SQL> insert into 11);
sempvalues('x',
1 row
created.
SQL> insert into 22);
sempvalues('y',
1 row
created.
SQL> select * from semp;
ENAME DNO
-------------------- ---------
x 11
y 22

ALTER TABLE

SQL> alter table sempadd(eddress


varchar2(20)); Table altered.

SQL> update semp set eddress='10 gandhi road'


where dno=11; 1 row updated.

SQL> update semp set eddress='12 m.g. road'


where dno=22; 1 row updated.

SQL> select * from semp;


58

ENAME DN EDDRESS
O
-------------------- --------- --------------------
x 11 10 gandhi road
y 22 12 m.g. road
SQL> select city, ename from depts, s2emp where depts.dno = s2emp.dno;

CITY ENAME
-------------------- --------------------
chennai x
hyderabad y

Res
ult
Thus the constraints were implemented and the tables were created
various successfully.
59

Ex. No: 8

Study of PL / SQL Block


Date : 28 - 04 - 21

Aim

To Study PL / SQL Block

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 90’s to enhance the capabilities of SQL.

The PL/SQL Engine:

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).

PL/SQL Block consists of three sections:

 The Declaration section (optional). 



 The Execution section (mandatory). 

 The Exception (or Error) Handling section (optional). 

Declaration Section:

The Declaration section of a PL/SQL Block starts with the reserved keyword DECLARE.
This section is optional and is used to declare any placeholders like variables, constants, records
and cursors, which are used to manipulate data in the execution section. Placeholders may be
any of Variables, Constants and Records, which stores data temporarily. Cursors are also
declared in this section.
60

Execution Section:

The Execution section of a PL/SQL Block starts with the reserved keyword BEGIN and
ends with END. This is a mandatory section and is the section where the program logic is written
to perform any task. The programmatic constructs like loops, conditional statement and SQL
statements form the part of execution section.
61

Exception Section:

The Exception section of a PL/SQL Block starts with the reserved keyword EXCEPTION.
This section is optional. Any errors in the program can be handled in this section, so that the
PL/SQL Blocks terminates gracefully. If the PL/SQL Block contains exceptions that cannot be
handled, the Block terminates abruptly with errors.

Every statement in the above three sections must end with a semicolon ; . PL/SQL blocks
can be nested within other PL/SQL blocks. Comments can be used to document code.

Sample PL/SQL Block:

DECLARE

Variable declaration
BEGIN

Program Execution
EXCEPTION
Exception handling

END;

The 'Hello World' Example:

DECLARE

message varchar2(20):= 'Hello, World!';


BEGIN

dbms_output.put_line(message);

END;

/
The end; line signals the end of the PL/SQL block. To run the code from SQL command line, we
need to type / at the beginning of the first blank line after the last line of the code. When the
above code is executed at SQL prompt, it produces following result:
62

Hello World

PL/SQL procedure successfully completed.


Ends a comment.

PL/SQL - Constants and Literals

A constant holds a value that once declared, does not change in the program. A constant
declaration specifies its name, data type, and value, and allocates storage for it. The declaration
can also impose the NOT NULL constraint.

Declaring a Constant

A constant is declared using the CONSTANT keyword. It requires an initial value and does not

allow that value to be changed. For example:

DECLARE

- constant
declaration pi
constant number :=

3.141592654; -- other
declarations radius number(5,2);

dia number(5,2);

circumference number(7,
2); area number (10, 2);
BEGIN

- processing

radius := 9.5; dia

:= radius * 2;

circumference := 2.0 * pi * radius;

area := pi * radius * radius;


63

-- output

dbms_output.put_line('Radius: ' || radius);


dbms_output.put_line('Diameter: ' || dia);

dbms_output.put_line('Circumference: ' ||
circumference); dbms_output.put_line('Area: ' ||
area); END;

When the above code is executed at SQL prompt, it produces the following result:
Radius: 9.5
Circumference: 59.69

Area: 283.53
Pl/SQL procedure successfully completed.

Diameter: 19
PL/SQL – Conditions

IF-THEN Statement

It is the simplest form of IF control statement, frequently used in decision making and changing
the control flow of the program execution.

Syntax:

Syntax for IF-THEN statement is:

IF condition THEN
S;

END IF;

Where condition is a Boolean or relational condition and S is a simple or compound statement.


Example of an IF-THEN statement is:

IF (a <= 20)
THEN c:= c+1;
END IF;

Flow Diagram:
64

IF-THEN-ELSE Statement

A sequence of IF-THEN statements can be followed by an optional sequence of ELSE


statements, which execute when the condition is FALSE.

Syntax:

Syntax for the IF-THEN-ELSE statement is:

IF condition THEN
S1;

ELSE
S2;

END IF;

Where, S1 and S2 are different sequence of statements. In the IF-THEN-ELSE statements, when
the test condition is TRUE, the statement S1 is executed and S2 is skipped; when the test
condition is FALSE, then S1 is bypassed and statement S2 is executed. For example,
IF color = red THEN

dbms_output.put_line('You have chosen a red car')


ELSE

dbms_output.put_line('Please choose a color for your car');


END IF;

Flow Diagram:
65

IF-THEN-ELSIF Statement

The IF-THEN-ELSIF statement allows you to choose between several alternatives. An IF-THEN
statement can be followed by an optional ELSIF...ELSE statement. The ELSIF clause lets

Syntax:

The syntax of an IF-THEN-ELSIF Statement in PL/SQL programming language is:

IF(boolean_expression 1)THEN

S1; -- Executes when the boolean expression 1 is true


ELSIF(boolean_expression 2) THEN

S2; -- Executes when the boolean expression 2 is true


ELSIF(boolean_expression 3) THEN
S3; -- Executes when the boolean expression 3 is true

ELSE
S4; -- executes when the none of the above condition is true
66

END IF;
67

PL/SQL – Loops

There may be a situation when you need to execute a block of code several number of times. In
general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on.

Programming languages provide various control structures that allow for more complicated
execution paths.

A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages:

Basic Loop Statement


68

Basic loop structure encloses sequence of statements in between the LOOP and END
LOOPstatements. With each iteration, the sequence of statements is executed and then control
resumes at the top of the loop.

Syntax:

The syntax of a basic loop in PL/SQL programming language is:

LOOP

Sequence of statements;
END LOOP;

Here, sequence of statement(s) may be a single statement or a block of statements. An EXIT


statement or an EXIT WHEN statement is required to break the loop.
69

WHILE LOOP Statement

A WHILE LOOP statement in PL/SQL programming language repeatedly executes a target


statement as long as a given condition is true.

Syntax:

WHILE condition LOOP

sequence_of_statements

END LOOP;

FOR LOOP Statement

A FOR LOOP is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.

Syntax:

FOR counter IN initial value..final value LOOP


sequence_of_statements;
END LOOP;

Nested Loops

PL/SQL allows using one loop inside another loop. Following section shows few examples to
illustrate the concept.

The syntax for a nested basic LOOP statement in PL/SQL is as follows:

LOOP

Sequence of statements1
LOOP

Sequence of statements2
END LOOP;
END LOOP;

The syntax for a nested FOR LOOP statement in PL/SQL is as follows:

FOR counter1 IN initial_value1 ..final_value1 LOOP


sequence_of_statements1
70

FOR counter2 IN initial_value2 ..final_value2


LOOP sequence_of_statements2
END LOOP;
END LOOP;

The syntax for a nested WHILE LOOP statement in Pascal is as follows:

WHILE condition1 LOOP


sequence_of_statements1

WHILE condition2 LOOP


sequence_of_statements2

END LOOP;
END LOOP;
71

Result

Thus the study of PL / SQL was successfully completed.


72

Ex. No: 9

Date: 28-04-21 Programming Language Extensions to


Satisfy Conditions

Aim

To write PL/SQL block to satisfy conditions

TO DISPLAY HELLO MESSAGE

SQL> set serveroutput on;

SQL> declare
2 a varchar2(20);
3 begin

4 a:='Hello';
5 dbms_output.put_line(a);

6 end;
7 /
Hello

PL/SQL procedure successfully completed.

TO INPUT A VALUE FROM THE USER AND DISPLAY IT

SQL> set serveroutput on;


SQL> declare
2 a varchar2(20);

3 begin
4 a:=&a;

5 dbms_output.put_line(a);
6 end;

7 /

Enter value for a: 5


old 4: a:=&a; new
4: a:=5;
5
73

PL/SQL procedure successfully completed.

GREATEST OF THREE NUMBERS

SQL> set serveroutput on;

SQL> declare
2 a number(7);

3 b number(7);
4 c number(7);
74

5 begin
6 a:=&a;

7 b:=&b;
8 c:=&c;

9 if(a>b and a>c) then


10 dbms_output.put_line (' The greatest of the three is ' || a);
11 else if (b>c) then

12 dbms_output.put_line (' The greatest of the three is ' || b);


13 else

14 dbms_output.put_line (' The greatest of the three is ' || c);


15 end if;

16 end if;

17 end;
18 /

Enter value for a: 5


old 6: a:=&a; new

6: a:=5; Enter
value for b: 7 old

7: b:=&b; new 7:
b:=7; Enter value
for c: 1 old 8:
c:=&c; new 8:
c:=1;

The greatest of the three is 7

PL/SQL procedure successfully completed.

PRINT NUMBERS FROM 1 TO 5 USING SIMPLE LOOP

SQL> set serveroutput on;


SQL> declare
2 a number:=1;

3 begin
4 loop
75

5 dbms_output.put_line (a);
6 a:=a+1;

7 exit when a>5;

8 end loop;
9 end;

10 /
1
2

3
4

5
PL/SQL procedure successfully completed.
76

PRINT NUMBERS FROM 1 TO 4 USING WHILE LOOP

SQL> set serveroutput on;

SQL> declare
2 a number:=1;
3 begin

4 while(a<5)
5 loop

6 dbms_output.put_line (a);
7 a:=a+1;

8 end loop;

9 end;
10 /

1
2
3

PL/SQL procedure successfully completed.

PRINT NUMBERS FROM 1 TO 5 USING FOR LOOP

SQL> set serveroutput on;


SQL> declare

2 a number:=1;
3 begin
4 for a in 1..5

5 loop
6 dbms_output.put_line (a);

7 end loop;
8 end;
9 /

1
2
77

3
4
5

PL/SQL procedure successfully completed.

TO CREATE SACCOUNT TABLE

SQL> create table saccount (accno number(5), name varchar2(20), bal number(10));

Table created.

SQL> insert into saccount values ( 1,'mala',20000);


78

1 row created.

SQL> insert into saccount values (2,'kala',30000);

1 row created.

SQL> select * from saccount;

ACCNO NAME BAL

--------- -------------------- ---------


1 mala 20000

2 kala 30000

SQL> set serveroutput on;

SQL> declare
2 a_bal number(7);

3 a_no varchar2(20);
4 debit number(7):=2000;
5 minamt number(7):=500;

6 begin
7 a_no:=&a_no;

8 selectbal into a_bal from saccount where accno= a_no;


9 a_bal:= a_bal-debit;
10 if (a_bal>minamt) then

11 updatesaccount set bal=bal-debit where accno=a_no;


12 end if;

13 end;
14
15 /

Enter value for a_no: 1


old 7: a_no:=&a_no;
new 7: a_no:=1;

PL/SQL procedure successfully completed.


79

SQL> select * from saccount;

ACCNO NAME BAL


--------- -------------------- ---------

1 mala 18000
2 kala 30000

Result

Thus the various programs in PL/SQL were implemented and their output was verified.
80

Ex. No : 10
Procedures and Functions
Date: 12 - 05- 21

Aim

To write PL/SQL programs that executes the concept of functions and procedures.

Definition

A procedure or function is a logically


grouped set of SQL and PL/SQL statements
that perform a specific task. They are
essentially sub-programs. Procedures and
functions
are made up of,
Declarative part
Executable part
Optional exception handling part
These procedures and functions do not show the errors.

KEYWORDS AND THEIR PURPOSES

REPLACE: It recreates the procedure if it already exists.

PROCEDURE: It is the name of the procedure to be created.

ARGUMENT: It is the name of the argument to the procedure. Paranthesis can be omitted if
no arguments are present.

IN: Specifies that a value for the argument must be specified when calling the procedure ie.
used to pass values to a sub-program. This is the default parameter.

OUT: Specifies that the procedure passes a value for this argument back to it’s calling
environment after execution ie. used to return values to a caller of the sub-program.

INOUT: Specifies that a value for the argument must be specified when calling the
procedure and that procedure passes a value for this argument back to it’s calling
environment after execution.
81

RETURN: It is the datatype of the function’s return value because every function must
return a value, this clause is required.

PROCEDURES – SYNTAX

create or replace procedure <procedure name> (argument {in,out,inout}


datatype ) {is,as} variable declaration;

constant
declaration; begin
PL/SQL subprogram
body; exception

exception PL/SQL
block; end;
82

FUNCTIONS – SYNTAX

create or replace function <function name> (argument in datatype,……) return datatype

{is,as}

variable declaration;

constant declaration;

begin

PL/SQL subprogram
body; exception

exception PL/SQL
block; end;

CREATING THE TABLE ‗ITITEMS‘ AND DISPLAYING THE CONTENTS

SQL> create table ititems(itemid number(3), actualprice number(5), ordid


number(4), prodid number(4));

Table created.

SQL> insert into ititems values(101,2000, 500, 201);


1 row created.

SQL> insert into ititems values(102,3000, 1600, 202);


1 row created.

SQL> insert into ititems values(103,4000, 600, 202);


1 row created.

SQL> select * from


ititems;
ITEMID ACTUALPRICE ORDID PRODI
D
-------- ----------- -------- -------
- --
101 2000 500 201
102 3000 1600 202
103 4000 600 202
83

PROGRAM FOR GENERAL PROCEDURE – SELECTED RECORD‘S PRICE IS INCREMENTED BY


500 , EXECUTING THE PROCEDURE CREATED AND DISPLAYING THE UPDATED TABLE

SQL> create procedure itsum(identity number, total number) is


price number; 2 null_price exception;
3 begin

4 select actualprice into price from ititems where itemid=identity;


5 if price is null then

6 raise null_price;
7 else
84

8 update ititems set actualprice=actualprice+total where itemid=identity;


9 end if;

10 exception
11 when null_price then

12 dbms_output.put_line('price is null');
13 end;
14 /

Procedure created.

SQL> exec itsum(101, 500);


PL/SQL procedure successfully completed.

SQL> select * from


ititems;
ITEMID ACTUALPRICE ORDID PRODI
D
-------- ----------- --------- -------
- --
101 2500 500 201
102 3000 1600 202
103 4000 600 202

PROCEDURE FOR ‗IN‘ PARAMETER – CREATION, EXECUTION SQL> set


serveroutput on;
SQL> create procedure yyy (a IN number) is price number;

2 begin
3 select actualprice into price from ititems where itemid=a;

4 dbms_output.put_line('Actual price is ' || price);


5 if price is null then
6 dbms_output.put_line('price is null');

7 end if;
8 end;

9 /
Procedure created.

SQL> exec yyy(103);


Actual price is 4000
85

PL/SQL procedure successfully completed.

PROCEDURE FOR ‗OUT‘ PARAMETER – CREATION, EXECUTION

SQL> set serveroutput on;


SQL> create procedure zzz (a in number, b out number) is identity number;

2 begin
3 select ordid into identity from ititems where itemid=a;
4 if identity<1000 then

5 b:=100;
6 end if;

7 end;
8 /
86

Procedure created.
SQL> declare

2 a number;
3 b number;

4 begin
5 zzz(101,b);
6 dbms_output.put_line('The value of b is '|| b);

7 end;
8 /

The value of b is 100


PL/SQL procedure successfully completed.

PROCEDURE FOR ‗INOUT‘ PARAMETER – CREATION, EXECUTION

SQL> create procedure itit ( a in out number) is


2 begin
3 a:=a+1;

4 end;
5 /

Procedure created.

SQL> declare

2 a number:=7;
3 begin

4 itit(a);
5 dbms_output.put_line(‘The updated value is ‘||a);
6 end;

7 /
The updated value is 8

PL/SQL procedure successfully completed.

CREATE THE TABLE ‗ITTRAIN‘ TO BE USED FOR FUNCTIONS

SQL>create table ittrain ( tno number(10), tfare


number(10)); Table created.
87

SQL>insert into ittrain values (1001, 550);

1 row created.

SQL>insert into ittrain values (1002, 600);


1 row created.
SQL>select * from ittrain;

TNO TFARE
--------- ------------

1001 550

1002 600
88

PROGRAM FOR FUNCTION AND IT‘S EXECUTION

SQL> create function aaa (trainnumber number) return


number is 2 trainfunction ittrain.tfare % type;

3 begin
4 select tfare into trainfunction from ittrain where tno=trainnumber;
5 return(trainfunction);

6 end;
7 /

Function created.

SQL> set serveroutput on;

SQL> declare
2 total number;
3 begin

4 total:=aaa (1001);
5 dbms_output.put_line('Train fare is Rs. '||total);

6 end;
7 /

Train fare is Rs.550

PL/SQL procedure successfully completed.

FACTORIAL OF A NUMBER USING FUNCTION — PROGRAM AND EXECUTION

SQL> create function itfact (a number) return number is

2 fact number:=1;
3 b number;
4 begin

5 b:=a;
6 while b>0

7 loop
8 fact:=fact*b;
89

9 b:=b-1;

10 end loop;
11 return(fact);

12 end;
13 /

Function created.

SQL> set serveroutput on;


90

SQL> declare

2 a number:=7;
3 f number(10);

4 begin
5 f:=itfact(a);

6 dbms_output.put_line(‘The factorial of the given number is’||f);

7 end;
8 /

The factorial of the given number is 5040

PL/SQL procedure successfully completed.


91

Result

Thus the PL/SQL programs were executed successfully.


92

Ex. No. 11
Triggers
Date: 12-05-21

Aim

To write triggers using Oracle PL/SQL

Theory

In a DBMS, a trigger is a SQL procedure that initiates an action (i.e., firesan action) when
an event (INSERT, DELETE or UPDATE) occurs. Since triggers are event-driven specialized
procedures, they are stored in and managed by the DBMS. A trigger cannot be called or
executed; the DBMS automatically fires the trigger as a result of a data modification to the
associated table.
Syntax

The CREATE TRIGGER command defines and names a trigger that will be stored in the database.

CREATE [ OR REPLACE ] TRIGGER name

{ BEFORE | AFTER } { INSERT | UPDATE | DELETE } [ OR { INSERT | UPDATE |


DELETE } ]... ON

table

[ FOR EACH ROW

] [DECLARE

declarations ]

BEGIN

statements

END
Example:
93

SQL>CREATE OR REPLACE TRIGGER

student_alert_trig BEFORE INSERT ON student

BEGIN

DBMS_OUTPUT.PUT_LINE('New Student Record is about to be


added'); END;

Sample Output :
SQL> INSERT INTO Student VALUES('ADITYA KUMAR',11305104005,2,'A','24 -JUL-
2005',99,'[email protected]');

New Student Record is about to be

added 1 row created.

Exercise

1. Write a after statement-level trigger. Whenever an insert, update, or delete operation


occurs on the Student table, a row is added to the Studentauditlogtable recording the date,
user, and Action. Name the Trigger as Student_Audit_trig.

Step 1: Create a table Studentauditlog with following Fields Field Name Data Type

Audit_date Date

Audit_user Varchar2(25)

Audit_desc VARCHAR2(50)

SQL>CREATE TABLE VARCHAR2(25), audit_descstudentauditlog VARCHAR2(50)


(audit_dateDATE,audit_user));
Step 2: Create Trigger Named student_audit_trig SQL>CREATE OR REPLACE TRIGGER

student_audit_trig AFTER INSERT OR UPDATE OR DELETE ON student DECLARE

v_actionVARCHAR2(50);

BEGIN
94

IF INSERTING THEN

v_action := 'Added Student(s)';

ELSIF UPDATING THEN

v_action := 'Updated
Student(s)'; ELSIF DELETING THEN

v_action := 'Deleted
Student(s)'; END IF;

INSERT INTO studentauditlog VALUES (SYSDATE, USER,v_action); END;

Step 3: Verify Trigger

SQL>INSERT INTO Student VALUES('ADITYA KUMAR',11305104005,2,'A','24-JUL-


2005',99,'[email protected]');

New Student Record is about to be added

1 row created.

SQL> select * from studentauditlog;

AUDIT_DAT AUDIT_USER AUDIT_DESC

--------- ------------------------- --------------------

30-NOV-09 I7205312 Added Student(s)

2. Write a Before row-level trigger that displays a message Number 3' before every new
student belonging to Branch student table. Name the Trigger as Student_Branch3_trig.
'New Students are added to Branch Number 3 is inserted into the

CREATE OR REPLACE TRIGGER


Student_Branch3_trig BEFORE INSERT ON student

FOR EACH
ROW BEGIN
95

IF :NEW.branchno = 3 THEN

DBMS_OUTPUT.PUT_LINE('New Student(s )are added to Branch Number3(Electrical)’);

END IF;

END;

NOTE : Trigger Variables

In the trigger code block, several special variables are available for use.

NEW

NEW is a pseudo-record name that refers to the new table row for insert and update operations
in row-level triggers. This variable is not applicable in statement-level triggers and in delete
operations of row-level triggers.

Its usage is: :NEW.column where column is the name of a column in the table on which the
trigger is defined.

The initial content of :NEW.column is the value in the named column of the new row to be
inserted or of the new row that is to replace the old one when used in a before row-level
trigger. When used in an after row-level trigger, this value has already been stored in the table
since the action has already occurred on the affected row.

In the trigger code block, :NEW.column can be used like any other variable. If a value is assigned
to :NEW.column, in the code block of a before row-level trigger, the assigned value will be used
in the new inserted or updated row

3. Write a Row level Trigger that displays a message prior to Delete operation on the
Student table. Name the Trigger as Student_DeleteAlert_trig.
CREATE OR REPLACE TRIGGER
Student_DeleteAlert_trig BEFORE DELETE ON student

FOR EACH
ROW BEGIN

DBMS_OUTPUT.PUT_LINE('Student(s)Records are about to be Deleted'); END;


96

Result

Thus the triggers in Oracle PL/SQL was successfully completed.


Ex. No: 12
PL / SQL Blocks - Handling Exceptions
97

Date: 24-5-21

Aim

To Write a PL / SQL block that handles all types of exceptions.

Syntax for Exception Handling 

The General Syntax for exception handling is as follows. Here you can list down as many as
exceptions you want to handle. The default exception will be handled using WHEN others THEN:

DECLARE
<declarations
section> BEGIN

<executable command(s)>

EXCEPTION

<exception handling goes here >


WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements

........

WHEN others THEN


exception3-handling-
statements END;

Example

Let us write some simple code to illustrate the concept. We will be using the employee205 table

we had created and used in the previous Exercise No 4:

DECLARE
98

pssn number(4);
pfname varchar2(15);
pbdate date;

BEGIN

SELECT fname, bdate INTO pfname, pbdate FROM


employee205
WHERE ssn = &pssn;

DBMS_OUTPUT.PUT_LINE ('Name: '|| pfname);


DBMS_OUTPUT.PUT_LINE ('Date of Birth: ' || pbdate);

EXCEPTION

WHEN no_data_found THEN


dbms_output.put_line('No such
Employee!'); WHEN others THEN
dbms_output.put_line('Error!');
END;

When the above code is executed at SQL prompt, it produces the following result:

Execution 1:
Enter value for pssn: 999

old 8: WHERE ssn =


&pssn;
new 8: WHERE ssn = 999;
Name: NANDA
Date of Birth: 30-MAY-05

PL/SQL procedure successfully completed.

Execution 2:

Enter value for pssn: 100

old 8: WHE ss = &pssn


RE n ;
new 8: WHE ss = 100;
RE n
No such Employee!

PL/SQL procedure successfully completed.


99

Raising Exceptions

Exceptions are raised by the database server automatically whenever there is any
internal

database error, but exceptions can be raised explicitly by the programmer by using the
command

RAISE. Following is the simple syntax of raising an exception:

DECLARE

exception_name
EXCEPTION; BEGIN

IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION

WHEN exception_name THEN


statement;
END;

User-defined Exceptions

PL/SQL allows you to define your own exceptions according to the need of your program. A

user-defined exception must be declared and then raised explicitly, using either a RAISE

statement or the procedure

DBMS_STANDARD.RAISE_APPLICATION_ERROR.

The syntax for declaring an exception is:

DECLARE
my-exception EXCEPTION;

Example:
100

The following example illustrates the concept. This program asks for assn, when the user enters
an invalid ssn, the exception invalid_ssn is raised.

DECLARE

pssn number(4);
inputssn number(4);
pfname varchar2(15);
pbdate date;
invalid_ssn EXCEPTION;
BEGIN
PSSN:=&inputssn;

IF Pssn<= 0 THEN
RAISE invalid_ssn;
ELSE

SELECT fname, bdate INTO pfname, pbdate FROM


employee205
WHERE ssn = pssn;

DBMS_OUTPUT.PUT_LINE ('Name: '|| pfname);


DBMS_OUTPUT.PUT_LINE ('Date of Birth: ' || pbdate);
END IF;
EXCEPTION
WHEN invalid_ssn THEN

dbms_output.put_line('SSN must be greater than zero!'); WHEN


no_data_found THEN

dbms_output.put_line('No such
Employee!'); WHEN others THEN
dbms_output.put_line('Error!');
END;

When the above code is executed at SQL prompt, it produces the following result:

SQL> /

Enter value for inputssn: 999


old 8: PSSN:=&inputssn; new

8: PSSN:=999;
Name: NANDA
101

Date of Birth: 30-MAY-05

PL/SQL procedure successfully completed.

SQL> /

Enter value for inputssn: 200


old 8: PSSN:=&inputssn; new
8: PSSN:=200;
No such Employee!

PL/SQL procedure successfully completed.

SQL> /

Enter value for inputssn: 0

old 8: PSSN:=&inputssn; new


8: PSSN:=0;
SSN must be greater than zero!

PL/SQL procedure successfully completed.

Result

Thus the PL / SQL blocks that handle all types of exceptions were successfully completed.
102

Ex. No: 13
Library Information System
Date:24 -05-21

Aim

To develop an application for automating the Library Information System

Phases of Project Development:

1. Requirement Analysis (collect client requirements and analyze it.)

2. Design phase(prepare design according to the requirements)

2.1 Database Design:

A good database design is, therefore, one that:

 Divides your information into subject-based tables to reduce redundant data.

 Provides Access with the information it requires to join the information in the
tables together as needed. 

 Helps support and ensure the accuracy and integrity of your information. 

 Accommodates your data processing and reporting needs. 



2.1.1 The Design process: The design process consists of the following steps:

Determine the purpose of your database: This helps prepare you for the remaining steps.

2.1.2 Find and organize the information required: Gather all of the types of information you
might want to record in the database, such as product name and order number.

2.1.3 Divide the information into tables: Divide your information items into major entities or
subjects, such as Products or Orders. Each subject then becomes a table.
103

2.1.4 Turn information items into columns: Decide what information you want to store in
each table. Each item becomes a field, and is displayed as a column in the table. For example,
an Employees table might include fields such as Last Name and Hire Date.

2.1.5 Specify primary keys: Choose each table’s primary key. The primary key is a column that
is used to uniquely identify each row. An example might be Product ID or Order ID.
104

2.1.6 Set up the table relationships: Look at each table and decide how the data in one table
is related to the data in other tables. Add fields to tables or create new tables to clarify the
relationships, as necessary.

2.1.7 Refine your design: Analyze your design for errors. Create the tables and add a few
records of sample data. See if you can get the results you want from your tables. Make
adjustments to the design, as needed.

2.1.8. Apply the Normalization rules:

2.1.9. Draw Entity Relationship Diagram:

2.2 User Interface Design

These are ten general principles for user interface design. They are called "heuristics"
because they are more in the nature of rules of thumb than specific usability guidelines.
105

2.2.1 Visibility of system status

The system should always keep users informed about what is going on, through appropriate
feedback within reasonable time.

2.2.2 Match between system and the real world

The system should speak the users' language, with words, phrases and concepts familiar to the
user, rather than system-oriented terms. Follow real-world conventions, making information
appear in a natural and logical order.

2.2.3 User control and freedom

Users often choose system functions by mistake and will need a clearly marked "emergency
exit" to leave the unwanted state without having to go through an extended dialogue. Support
undo and redo.

2.2.4 Consistency and standards

Users should not have to wonder whether different words, situations, or actions mean the
same thing. Follow platform conventions.

2.2.5 Error prevention

Even better than good error messages is a careful design which prevents a problem from
occurring in the first place. Either eliminate error-prone conditions or check for them and
present users with a confirmation option before they commit to the action.

2.2.6 Recognition rather than recall


106

Minimize the user's memory load by making objects, actions, and options visible. The user
should not have to remember information from one part of the dialogue to another.
Instructions for use of the system should be visible or easily retrievable whenever appropriate.

2.2.7 Flexibility and efficiency of use

Accelerators -- unseen by the novice user -- may often speed up the interaction for the expert
user such that the system can cater to both inexperienced and experienced users. Allow users
to tailor frequent actions.

2.2.8 Aesthetic and minimalist design


107

Dialogues should not contain information which is irrelevant or rarely needed. Every extra of
information in a dialogue competes with the relevant units of information and diminishes
relative visibility.

2.2.9 Help users recognize, diagnose, and recover from errors

Error messages should be expressed in plain language (no codes), precisely indicate the
problem, and constructively suggest a solution.

2.2.10 Help and documentation

Even though it is better if the system can be used without documentation, it may be necessary
to provide help and documentation. Any such information should be easy to search, focused on
the user's task, list concrete steps to be carried out, and not be too large unit their
Front End Tool
Visual Basic 6.0 is a robust, object-oriented, sophisticated and powerful development platform,
ideally suited for producing impressive Windows applications.

The major advantages of VB are:


It is a powerful and complete Windows application development system that enables us to use built-in
functions and subroutines for dozens of different tasks.

It also provides capability to produce custom libraries and objects that can be loaded at runtime
or bound into the distributed application.
108

Every time you load a VB or VBA project, you will be greeted by roughly the layout shown in
Figure and these five GUI tools. First, the toolbox(1) contains all the GUIelements/controls
needed to create any VB form and the front end to all VB programs. For example, after the
pointer tool there is the image control, label, textbox, and frame and command button as the
first five of 20 standard controls which are used constantly in VB programs. Another advantage
of these basic controls is that they fill 60-90% of all our programming needs and are
automatically included in the VB runtime.

Second is form(2). Think of it as yours- you can size it, color it, give it a caption
("Database Test" in this case) and fill the form with GUI controls which help your program do
useful works. Putting controls on your form is as easy as clicking on the control (say the
command button) in the toolbox and then dragging and sizing it on your form (see the "Exit"
button on the form).

The third part of the Basic canvas is the menus and toolbars (3) which manage and
control all of VB/VBA.Most of us will be familiar with many of the menu and icons. File, Edit,
View, Run, Window, Help menus should be familiar to any Word Perfect, Excel, or Netscape
users. Likewise icons for File Open, File Save, Cut, Copy, Paste, Find, Run programs, Pause
Program, Halt Program can be seen along the toolbar. Along with built in wizards and custom
command centers in some controls, this is the heart of VB.

Fourth is the Project Explorer (4) which you use to access all the forms and coding files
in your VB program. The PE-Project Explorer is such a handy navigation device you will find
yourself using it all the time to switch among different forms and code.

Fifth and even more frequently used than the Project Explorer is the Properties sheet

(5). Note that the "Exit" command button is highlighted in the form and is also the control listed
in the Properties sheet. The Properties sheet is both the elegance and the swamp of VB. If you
want to change the property of any control like its color, shape, caption, or whatever - the
Property sheet is the place to go. But a command button has 32 properties - and some controls
have hundreds, hence the swamp.
109

You will find in developing in Visual Basic that you spend a large percentage of time
using the Project Explorer and Property sheet. It is worthwhile to get to know them well.
Project Explorer is your means of navigating around the various parts of VB; while Property
sheets allow you to set the very basic look and feel plus behavior of all your forms in Visual
Basic.
Form Design

Develop proper forms

Forms don’t usually get much attention from code-level developers. We add a form and off
we go, plugging in various controls and using them as containers for information. But setting up
forms’ properties is important for creating visually pleasant, consistent, and intuitive interfaces.

You should specify the proper border style of a form. Your options are:

None
Fixed Single
Sizable
Fixed Dialog
Fixed Tool Window
Sizable Tool Window

Using None is rarely a good idea, since such forms don’t have a title bar or the control menu
box, so users can’t close or resize them. The default form value is Sizable (allowing users to

resize the form), but this is a good choice only in cases where all the form elements are
designed to resize along with the form itself.
The Fixed Dialog style offers a border and doesn’t allow a form to be resized, but it lacks
Minimize and Maximize buttons in the top-right corner. To include those buttons, use the
Fixed Single style. Sizable Tool Window and Fixed Tool Window styles are generally used for
forms that need to float over and allow changes to be made to the main forms.
110

You should also address the form’s start position. The available start position styles are:

Manual
Windows Default
CenterScreen
CenterOwner

The default style is Manual, which means that the form will appear in the same location at both
runtime and design time. Windows Default puts a form in the upper-left corner on the screen.

CenterScreen places a form in the center of the user’s screen regardless of the screen
resolution. CenterOwner places a form in the center of the owner form. An owner is a form on
top of which the current form is to appear. When no owner is specified, the form shows up in
the center of the desktop.

Keep controls consistent and appropriate

Before simply dropping controls on a form, consider what kind of data the control will
oversee and how your users will interact with that data. The guidelines provided below will help
you choose the best controls for a particular type of data.

The first rule of form controls is that they should have consistent characteristics, such as
look, feel, and size. Users shouldn't need to learn specific visual cues and usage parameters for
each control.

Your text box controls should be the same height as the combo boxes. By default, the height
property of text boxes is different from that of the combo boxes. You should change the height
value of the text boxes to match that of the combo boxes (since the height property is read-only
in combo boxes). Obviously, this rule applies only to single-line text boxes.

You should use the proper controls for the data you need to display. If you're displaying
read-only data, you should not use a text box and modify its properties so that users can’t make
changes to its text. Instead, use a label. Text box controls should be used only for editable data.
111

When you need to display fewer than five options in a list and you want the user to choose
only one item, option buttons are your best choice. Many applications use combo boxes to
display such information, but from the user's standpoint, it’s much better to see all options at
once rather than having to scroll through the listings in a combo box.

Keep in mind that when you want your users to be able to select more than one item from a
small list of selections, using check boxes is a good idea. As with option buttons, check boxes let
users see all options available at the same time, but check boxes also allow the selection of
multiple items from the list.

When you need to display a larger number of items for users to choose from, it’s not
feasible to use option buttons or check boxes because of the amount of real estate they would
take up on the form. In such cases, you should display data either in combo boxes or list boxes
to save space. You can use multiple-selection list boxes to let users select more than one item at
a time; combo boxes allow only one item to be selected.

Developers sometimes use combo boxes and list boxes to display more than one column of
data; however, grid controls may be easier for users to understand (and easier for you to code).

When using labels next to corresponding controls, left-align the labels and follow label
captions with a colon for better readability. Also, align labels vertically to the corresponding
controls. Figure A provides an example of these label rules in action.

Figure A
112

Always set the BackStyle property of label controls to Transparent to make sure your
labels have the same BackColor as the parent form.

Whenever you need to prevent users from using a control temporarily, it’s preferable to
disable the control rather than hide it. Disabling a control prevents the user from clicking it, but
it doesn’t significantly alter the way the form looks. Hiding controls may take your users by
surprise or lead them to believe that something is wrong with an application. When selecting
controls, also consider newer VB options, such as Tab Control, Tree View, Progress Bar, and
Toolbar, to improve the form layout and design.

SCREENSHOTS:

Login Form User Interface Design View


113

Login Form after Execution

Sample User Interface Design To Display Book Details


114
115

Result

Thus the Library Information system was implement in VB successfully.


116

Ex. No: 14
Student Information System
Date: 26 - 5 - 21

Aim

To develop an application for automating Student Information System

Menu Design

Theory

Adding Menu Bar Using Menu Editor

To start adding menu items to your application, open an existing project or start a new
project, then click on Tools in the menu bar of the Visual Basic IDE and select Menu Editor. When
you click on the Menu Editor, the Menu Editor dialog will appear. In the Menu Editor dialog , key
in the first item File in the caption text box. You can use the ampersand ( & ) sign in front of F so
that F will be underlined when it appears in the menu, and F will become the hot key to initiate
the action under this item by pressing the Alt key and the letter F. After typing &File in the Caption
text box, move to the name textbox to enter the name for this menu item, you can type in
mnuFile here. Now, click the Next button and the menu item &File will move into the empty space
below, as shown in the following diagram:
117

You can then add in other menu items on the menu bar by following the same procedure,
as shown in the diagram below:

when you click Ok, the menu items will be shown on the menu bar of the form.
118

Now, you may proceed to add the sub menus. In the Menu Editor, click on the Insert button
between File and Exit and then click the right arrow key, and the dotted line will appear.
This
119

shows the second level of the menu, or the submenu. Now key in the caption and the name.
Repeat the same procedure to add other submenu items. Here, we are adding New, Open,
Save, Save As and Exit.

Now click the OK button and go back to your form. You can see the dropped
down submenus when you click on the item File, as shown.
120

Finally, you can enter the code by clicking on any of the submenu items.
121

Exercise

Add Menu as per Specification and sample given. In the intro form add following Menus
Personal
Personal Detail
Branch wise Detail
Mark
Mark Detail
Grade Detail
Exit

In the Personal Information form add Menu to navigate to the Main Menu(IntroForm)
In the Mark form add Menu to navigate to the Grade Details(Grade Form)

In the Grade form add Menu to navigate to the Mark Details(Mark Form)
Add Exit and Back as Required.

Coding
Sample Coding for Intro Form

Private Sub Exit_Click()


End

End Sub
Private Sub GradeDetail_Click()

Unload Me
Load Grade
Grade.Show

End Sub

Private Sub MarkDetail_Click()


Unload Me
Load Mark

Mark.Show
End Sub

Private Sub PersonalDetail_Click(Index As Integer)


Unload Me
122

Load Student
Student.Show

End Sub

Sample Coding for Registration Form

Private Sub cmdmovenext_Click()


Adodc1.Recordset.MoveNext

If Adodc1.Recordset.EOF Then
Adodc1.Recordset.MoveLast

End If
End Sub

Private Sub cmdmoveprev_Click()


Adodc1.Recordset.MovePrevious

If Adodc1.Recordset.BOF Then
Adodc1.Recordset.MoveFirst
End If

End Sub

Private Sub cmdnew_Click()


Adodc1.Recordset.AddNew
End Sub

Private Sub cmdsave_Click()

Adodc1.Recordset.Update
End Sub

Private Sub Command1_Click()

cs = "select * from branch where branchname = '"


& Adodc2.Recordset("branchname") & "'"

MsgBoxcs
End Sub

Private Sub Mainmenu_Click()


Unload Me
123

Load Intro
Intro.Show
End Sub
124

SCREENSHOTS:

Intro Form:
125

Registration Form
126

Result

Thus the Library Information System application was created successfully.


127

Ex. No :15

Simple Calculator
Date : 26- 5- 21

Aim

To implement a simple calculator by using Visual Basic front end tools.

Procedure:

Step1: create a new project in visual basic using the option file---> new project.

Step2: In the form use the front end tools in the toolbox like textbox, label, command button
and create a front end Design for the simple calculator.

Step3: Open the properties window for the toolsand select properties. Now the properties
Window is opened.

Step4: Set properties for each tool in the form like caption, name, etc.

Step5: Double click each and every tool to open the project code window.

Step6: write the code for the events of the tools.

Step7: write the code for the simple operations in the calculator like Addition, subtraction,
multiplication and division.

Step7: The code is Automatically compiled at the end of each line while pressing the Enter key.

Step7: now execute the code by click the F5 button in the keyboard or select Run--->start.

Step8: after successfully executing the project create the executable file by Select the option
file---> make file.exe.
128

SCREENSHOT:

CODING:
129

Dim a, b, c, d As Integer

Private Sub button0_Click()

display.Text = display.Text +
button0.Caption End Sub

Private Sub button1_Click()

display.Text = display.Text +
button1.Caption End Sub

Private Sub button2_Click()

display.Text = display.Text +
button2.Caption End Sub
130

Private Sub button3_Click()

display.Text = display.Text +
button3.Caption End Sub

Private Sub button4_Click()

display.Text = display.Text +
button4.Caption End Sub

Private Sub button5_Click()

display.Text = display.Text +
button5.Caption End Sub

Private Sub button6_Click()

display.Text = display.Text +
button6.Caption End Sub

Private Sub button7_Click()

display.Text = display.Text +
button7.Caption End Sub

Private Sub button8_Click()

display.Text = display.Text +
button8.Caption End Sub

Private Sub button9_Click()

display.Text = display.Text +
button9.Caption End Sub

Private Sub add_Click()

a = Val(display.Text)

display.Text = ""

d=1
131

End Sub

Private Sub sub_Click()

a = Val(display.Text)

display.Text = ""

d=2

End Sub

Private Sub mul_Click()

a = Val(display.Text)

display.Text = ""

d=3

End Sub
132

Private Sub div_Click()

a = Val(display.Text)

display.Text = ""

d=4

End Sub

Private Sub equalto_Click()

b = Val(display.Text)

If d = 1 Then

c=a+b

display.Text = c
ElseIf d = 2

Then c = a - b
display.Text = c
ElseIf d = 3

Then c = a * b
display.Text = c

ElseIf d = 4
Then c = a / b

display.Text = c
End If

End Sub

Private Sub
clear_Click() a = 0

b=0
c=0

display.Text =
133

"" End Sub

Private Sub off_Click()

MSG = MsgBox("THANKS FOR USING FX990ES FROM NASA COPY RIGHTS


RESERVED", vbOKOnly, "BYE")

End End

Sub

Private Sub decimalpoint_Click()

display.Text = display.Text +
decimalpoint.Caption End Sub
134
OUTPUT:
135

Result

Thus the simple calculator application was created successfully.

You might also like