Download as pdf or txt
Download as pdf or txt
You are on page 1of 60

An Autonomous Institution

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LAB MANUAL

191CS42A -DATABASE MANAGEMENT SYSTEMS LABORATORY


NAME:

REGISTER NUMBER:

ROLL NO:

YEAR/SEM: II/IV

BRANCH: B.E Computer Science and Engineering

REGULATION: 2019

Department of Computer Science and Engineering


Vision
To emerge as centre for academic excellence in the field of Computer Science andEngineering by
exposure to research and industry practices.

Mission
M1 - To provide good teaching and learning environment with conducive researchatmosphere in the
field of Computer Science and Engineering.
M2 - To propagate lifelong learning.

M3 - To impart the right proportion of knowledge, attitudes and ethics in students toenable them take
up positions of responsibility in the society and make significant contributions
Approved by AICTE, Affiliated to Anna University, Chennai.
ISO 9001:2015 Certified Institution, Accredited by NBA (BME, CSE, ECE, EEE,
IT & MECH), Accredited by NAAC
#42, Avadi-Vel Tech Road, Avadi, Chennai- 600062, Tamil
Nadu, India.

CERTIFICATE

Name …………………….……………………………............ Year: ………………………….


Semester:................. Branch: B.E– COMPUTER SCIENCE AND ENGINEERING
Register No…............ ……………….VM No:………………………..

Certified that this is the bonafide record of work done by the above student in the 191CS42A
DATABASE MANAGEMENT SYSTEMS LABORATORY during the academic year 2023-2024.

Signature of Course Incharge Signature of Head of the Department

Submitted for the University Practical Examination held on ............................ at VEL TECH MULTI TECH
Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE, No.42, AVADI – VEL TECH
ROAD, AVADI, CHENNAI- 600062.

Signature of Examiners

Internal Examiner:…………… ExternalExaminer:……………

Date:………………
DEPARTMENT OF COMPUTER SCIENCE AND
ENGINEERING

PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)

PEOs PROGRAMME EDUCATIONAL OBJECTIVES


Ability to identify, formulate and analyze complex Computer Science and
Engineering problems in the areas of hardware, software, theoretical Computer
PEO1 Science and applications to reach significant conclusions by applying Mathematics,
Natural sciences, Computer Science and
Engineering principles.

Apply knowledge of mathematics, natural science, engineering fundamentals and


system fundamentals, software development, networking & communication, and
PEO2 information security to the solution of complex engineering problems in computer
science and engineering
to get benefits in their professional career or higher education and research or
technological entrepreneur.

Design solutions for complex computer science and engineering problems using
state of the art tools and techniques, components or processes that meet specified
PEO3 needs with appropriate consideration for public health and safety, cultural,
societal, and environmental
considerations.

PROGRAMME SPECIFIC OUTCOMES (PSOs)

PSO’s PROGRAMME SPECIFIC OUTCOMES

An ability to apply, design and development of application oriented software systems


PSO1 and to test and document in accordance with Computer
Science and Engineering.
The design techniques, analysis and the building, testing, operation andmaintenance
PSO2 of networks, databases, security and computer systems
(both hardware and software).

PSO3 An ability to identify, formulate and solve hardware and softwareproblems using
sound computer engineering principles.
PROGRAMME OUTCOMES (POs)

PO’s PROGRAMME OUTCOMES


Engineering Knowledge: Apply knowledge of mathematics,
PO1 science, engineering fundamentals and an Engineering Specialization to thesolution of
complex engineering problems.
Problem Analysis: Identify, formulate, review research
PO2 literature and analyze complex engineering problems reaching substantiatedconclusions
using first principles of mathematics, natural sciences, and engineering sciences.

Design / Development of solutions: Design solutions for complex engineering problems


PO3 and design system components or processes that meetspecified needs with appropriate
consideration for public health and safety,
cultural, societal, and environmental considerations.
Conduct Investigations of Complex Problems: Use research-based knowledge and
PO4 research methods including design of experiments, analysisand interpretation of data, and
synthesis of the information to provide valid
conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and
PO5 modern engineering and IT tools including prediction and
modeling to complex engineering activities with an understanding of thelimitations.

The Engineer and Society: Apply reasoning informed by the contextual knowledge to
PO6 assess societal, health, safety, legal and cultural issues and theconsequent responsibilities
relevant to the professional engineering practice.

Environment and sustainability: Understand the impact of the professional engineering


PO7 solutions in societal and environmental contexts, and demonstratethe knowledge of, and need
for sustainable development.

Ethics: Apply ethical principles and commit to professional ethics andresponsibilities and
PO8 norms of the engineering practice.

Individual and team work: Function effectively as an individual, and as amember or leader
PO9 in diverse teams, and in multidisciplinary settings.

Communication: Communicate effectively on complex engineering activitieswith the


PO10 engineering community and with society at large, such as, being able
to comprehend and write effective reports and design documentation, makeeffective
presentations, and give and receive clear instructions
Project Management and Finance: Demonstrate knowledge and understanding of the
PO11 engineering and management principles and apply theseto one’s own work, as a member
and leader in a team, to manage projects and
in multidisciplinary environments.
Life-long learning: Recognize the need for, and have the preparation and ability to engage
PO12 in independent and life-long learning in the broadest context
of technological change.
COURSE OBJECTIVES

The student should be made to:

 To understand data definitions and data manipulation commands.


 To learn the use of nested and join queries.
 To understand functions, procedures and procedural extensions of data bases.
 To be familiar with the use of a front end tool.
 To understand design and implementation of typical database applications.

COURSE OUTCOMES

At the end of the course, the student should be able to

Course
Outcome CO Statements

CO1 Remember typical data definitions and manipulation commands.

CO2 Identify the design applications to test Nested and Join Queries.

CO3 Apply simple applications that use Views.

CO4 Analyze applications that require a Front-end Tool.

Evaluate and analyze the use of Tables, Views, Functions and


CO5
Procedures.

Course Mapping CO's with PO's & PSO’S


Outco
me
PSO1

PSO2

PSO3
PO10

PO11

PO12
PO 1
PO 2
PO 3
PO 4
PO 5

PO 6

PO 7

PO 8

PO 9

CO1 3 2 2 1 - 1 - - - - 1 1 3 2 1

CO2 3 2 2 1 - 1 - - - - 1 1 2 3 1

CO3 3 2 2 2 2 1 - - - - 1 1 2 2 2

CO4 3 2 2 2 2 2 - - - - 1 2 1 2 1

CO5 3 2 2 2 2 2 - - - - 1 2 1 2 2

CO 3 2 2 2 2 1 - - - - 1 1 2 2 1
1 – Low 2 – Medium 3 – High
Course Code: 191CS22A

Course: DATABASE MANAGEMENT SYSTEMS LABORATORY

LIST OF EXPERIMENTS
Page
Ex
Name of the Exercise COs No Signature
No DATE

1 Data definition commands, data manipulation CO1


commands forinserting, deleting, updating and
retrieving tables and transaction control statements.
Database querying – simple queries, nested CO2
2 queries, subqueries and join queries.
CO2
3 Creation of views, synonyms and sequence
using sqlqueries

4 Create Database programming: implicit and explicit CO3


cursors
5 Creation of procedures and functions CO4

CO4
6 Creation of database using triggers
CO5
7 PL/SQL block handles all types of exceptions
8 CO5
Database design using normalization

9 Design and implementation of personal CO1,2


informationsystem (mini project).
10 CO5
Oracle Database system - A case study
11
Design and implementation of hospital CO1,2,
management system(mini project) 3
12
Design and implementation of library management CO1,2,
system(mini project) 3
EX.NO: 1 DATA DEFINITION COMMANDS -Data Manipulation Commands forinserting,
DATE deleting, updating and retrieving Tables and Transaction Control statements

AIM:

To create database using Data Definition Commands of SQL queries in RDBMS

PROGRAM:

Data Manipulation Language:


Data manipulation language (DML) statements access and manipulate data in existing tables.
Examples of DML:
INSERT
SELECT
UPDATE
DELETE
INSERTING VALUES INTO TABLE
Create table:
SQL>Create table persons( pid number(5), firstnameVarChar(15),lastnameVarChar(15),address
VarChar(25),city varchar(10));

INSERT COMMAND
Insert command is used to insert values into table.
Insert a single record into table.
Syntax:SQL>insert into <table name> values (value list)
SQL>insert into persons values (001,'nelson','raj','no25,annai street','chennai');1 row
created.

Insert more than a record into persons table using a single insert command.
SQL> insert into persons values(&pid,'&firstname','&lastname','&address','&city');
Skipping the fields while inserting:
SQL> insert into persons(pid,firstname) values(500,'prabhu');

Select Commands
It is used to retrieve information from the table.it is generally referred to as querying thetable.We can
either display all columns in a table or only specify column from the table.Syntax:
SQL> Select * from tablename; // This query selects all rows from the table.
Example:
SQL>Select * from persons;

The retrieval of specific columns from a table:


It retrieves the specified columns from the table
Syntax: SQL>Select column_name1, …..,column_namen from table name;
Example: SQL>Select pid, firstnamefrom persons
Elimination of duplicates from the select clause:
It prevents retrieving the duplicated values .Distinct keyword is to be used.
Syntax:SQL>Select DISTINCT col1, col2 from table name;
Example:
SQL>Select DISTINCTlastname from persons

Select command with where clause:


To select specific rows from a table we include ‘where’ clause in the select command. Itcan appear only
after the ‘from’ clause.
Syntax: SQL>Select column_name1, …..,column_namen from table name where condition;
Example: SQL>Select firstname, lastname from persons where pid>2;

Select command with order by clause:


Syntax: SQL>Select column_name1, …..,column_namen from table name where condition
orderbycolmnname;
Example:
SQL>Select firstname, lastname from persons order by pid;
Select command to create a table:
Syntax:
SQL>create table tablename as select * from existing_tablename;
Example:
SQL>create table persons1 as select * from persons;Table
created
Select command to insert records:
Syntax:SQL>insert into tablename( select columns from existing_tablename);
Example:SQL>insert into persons1( select * from persons); PID
FIRSTNAME LASTNAMEADDRESS CITY PHONENO
- - - - - --
001 nelson raj no25,annai street Chennai
100 niranjan kumar 10/25 krishna street Mumbai 999999999102 arjun
kumar 30 sundaram street coimbatore
300 gugan chand 5/10 mettu street Coimbatore500
prabhu
Select command using IN keyword: 10

Syntax:SQL>Select column_name1, …..,column_namen from table name where

Syntax:SQL>Select column_name1, …..,column_namen from table name wherecolmnname IN


(value1,value2);
Example: SQL>Select * from persons where pid in (100,500);(OR)
SQL>Select * from persons where (pid=100 OR pid=500); PID
FIRSTNAME LASTNAMEADDRESS CITY PHONENO
- - - - - --
100 niranjan kumar 10/25 krishna street Mumbai 999999999
500 prabhu
Select command using BETWEEN keyword:
Syntax:SQL>Select column_name1, …..,column_namen from table name wherecolmnname
BETWEEN value1 AND value2;
Example: SQL>Select * from persons where pid between 100 and 500;PID
FIRSTNAME LASTNAMEADDRESS CITY PHONENO
- - - - - --
100 niranjan kumar 10/25 krishna street Mumbai 999999999
500 prabhu
Select command using pattern:
Syntax:SQL>Select column_name1, …..,column_namen from table name wherecolmnname LIKE
‘% or _‘;
Example: SQL>Select * from persons where firstname like ‘nir_n%’;PID
FIRSTNAME LASTNAMEADDRESS CITY PHONENO
- - - - - --
100 niranjan kumar 10/25 krishna street Mumbai 999999999
Renaming the fieldname at the time of display using select statement: Syntax:SQL>Select
old_column_namenew_column_namefrom table name where condition;Example: SQL>Select pidpersonid
from persons;
Select command to retrieve null values:
Syntax:SQL>Select column_namefrom table name where column_name is NULL ;

Example: SQL>Select * from persons where lastname is null; PID


FIRSTNAME LASTNAMEADDRESS CITY PHONENO
- - - - - --
500 prabhu
UPDATE COMMAND:
Syntax:
UPDATE table_nameSET column_name = value [, column_name = value]...[ WHERE
condition ];
Example:SQL>update persons set pid= 5 where firstname=’prabhu’;Table updated.
DELETE COMMAND
Syntax: SQL>Delete from table where conditions;
Example:SQL>delete from persons where pid=500;1 row
deleted.
Transaction Control statements
Transaction Control Language(TCL) commands are used to manage transactions in thedatabase.
Examples of TCL:
(i) Commit
(ii) Rollback
(iii) Savepoint
(i) Commit: Commit command saves all the work done.
Syntax:commi
(ii) Rollback: Rollback Command restores database to original since the last Commit.
Syntax:ROLLBACK TO SAVEPOINT <savepoint_name>;

(iii) Savepoint:
Syntax:SAVEPOINT <savepoint_name>;

RESULT
Thus the database is created using DDL,DML,TCL of SQL queries
EX.NO: 2 Database Querying – Simple queries, Nested queries, Sub queries and Join
DATE queries.

AIM:
To create database using Simple queries, Nested Queries, Sub queries and Join Queries inRDBMS.
Nested Queries:
Nesting of queries one within another is known as a nested queries.
Example:
SQL> select emp_no,e_name,job from empp where sal>(select sal from empp wheree_name=
'ravi');

Subqueries
The query within another is known as a subquery. A statement containing subquery is calledparent statement.
The rows returned by subquery are used by the parent statement.
Example:

Correlated subquery
A subquery is evaluated once for the entire parent statement whereas a correlated subquery isevaluated once
per row processed by the parent statement.
Example:
Select * from empp wheresal> (select avg(sal) from empp where emp_no = emp_no);

Relating Data through Join Concept


The purpose of a join concept is to combine data spread across tables. A join is actuallyperformed by the
‘where’ clause which combines specified rows of tables.
Syntax:
select columns from table1, table2 where logical expression;
Types of Joins
1. Simple Join
2. Self Join
3. Outer Join
1. Simple Join
It is the most common type of join. It retrieves the rows from 2 tables having a commoncolumn and is
further classified into
SQL> select * from emp;
EMPNO ENAME JOB DEPTNO SAL
- - - - -
1 Mathi AP 1 10000
2 Arjun ASP 2 12000
3 Gugan ASP 1 12000
10 xxx Lect 2 10000 SQL>
select * from dept;DEPTNO
DNAME LOC
- - -
1 ACCOUNTING NEW YORK
2 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
a) Equi-join
A join, which is based on equalities, is called equi-join.

Example:
select * from item, cust where item.id=cust.id;
In the above statement, item-id = cust-id performs the join statement. It retrieves rows fromboth the tables
provided they both have the same id as specified by the where clause. Since the where clause uses the
comparison operator (=) to perform a join, it is said to be equijoin.It combines the matched rows of tables.

b) Non Equi-join
It specifies the relationship between columns belonging to different tables by making use ofrelational operators
other than’=’.
Example:
2. Self join
Joining of a table to itself is known as self-join. It joins one row in a table to another. It cancompare each
row of the table to itself and also with other rows of the same table.
Example:
select * from empp ,cust where sal>= (select avg(sal) from empp where emp_no=cust_no);

3. Outer Join
It extends the result of a simple join. An outer join returns all the rows returned by simplejoin as well as
those rows from one table that do not match any row from the table. The symbol(+) represents outer join.
Example:
Sample table: foods
ITEM_ID | ITEM_NAME | ITEM_UNIT | COMPANY_ID |
+ -+ -+ +- --+
| 1 | Chex Mix | Pcs | 16 |
| 6 | Cheez-It | Pcs | 15 |
| 2 | BN Biscuit | Pcs | 15 |
| 3 | Mighty Munch | Pcs | 17 | |
+ -+ -+ +- --+
Sample table: company
COMPANY_ID | COMPANY_NAME | COMPANY_CITY |
+ +- + +
| 18 | Order All | Boston |
| 15 | Jack Hill Ltd | London |
| 16 | Akas Foods | Delhi |
| 17 | Foodies. | London ||
SQL>Selectcompany.company_name,company.company_id,foods.company_id,foods.ite
m_name,foods.item_unit FROM company, foods WHEREcompany.company_id=foods.company_id(+);
Different SQL JOINS
Before we continue with examples, we will list the types the different SQL JOINs you canuse:
• • INNER JOIN: Returns all rows when there is at least one match in BOTH tables
• • LEFT JOIN: Return all rows from the left table, and the matched rows from theright table
• • RIGHT JOIN: Return all rows from the right table, and the matched rows from theleft table
• • FULL JOIN: Return all rows when there is a match in ONE of the tables

SQL INNER JOIN


The INNER JOIN keyword selects all rows from both tables as long as there is a matchbetween the
columns in both tables

Syntax:
SELECT column_name(s)FROM table1INNER JOIN table2 ON table1.column_name =
table2.column_name;

LEFT OUTER JOIN


The LEFT JOIN keyword returns all rows from the left table (table_name1), even if there areno matches in
the right table (table_name2)
SQL> SELECT column_name(s) FROM table_name1 LEFT JOIN table_name2 ON
table_name1.column_name=table_name2.column_name

RIGHT OUTER JOIN


The RIGHT JOIN keyword Return all rows from the right table (table_name2), even if thereare no matches
in the left table (table_name1).
SQL> SELECT column_name(s) FROM table_name1 RIGHT JOIN table_name2 ON
table_name1.column_name=table_name2.column_name
FULL JOIN
The FULL JOIN keyword return rows when there is a match in one of the tables. SQL>SELECT
column_name(s) FROM table_name1 FULL JOIN table_name2 ON
table_name1.column_name=table_name2.column_name

RESULT:
The Database Querying – Simple Queries, Nested Queries, Sub Queries and Joins areexecuted
successfully.
EX.NO: 3
CREATION OF VIEWS, SYNONYMS AND SEQUENCE USING SQL QUERIES
DATE

AIM:

To create Views , Synonyms ,Sequences, commands in database using SQL queries inRDBMS.

CREATING VIEWS:
A view is a virtual table based on the result-set of an SQL statement. A view contains rowsand columns,
just like a real table. The fields in a view are fields from one or more real tables in the database.
Syntax
create view view_name as select column_name(s) from table_name where condition;
Example:
SQL> create view emp1 as select * from emp where salary>10000;View created
SQL> select * form emp1;
EMPNO ENAME JOB DEPTNO SAL
- - - - -
2 Arjun ASP 2 12000
3 Gugan ASP 1 12000
SQL>desc emp1;
Name Null? Type
- - -
empno NOT NULL number(5)
ename NOT NULL VarChar(15)job
Var Char(10)
deptno NOT NULL number(3)sal
number (5)
Updating a View
View can be updated. If view is already created with same name it will be replaced by createor replace
statement (or) if view already doesn’t exist, it will be created.
Syntax
SQL>create or replace view view_name as select column_name(s) from table_name wherecondition;
Example:

SQL> create or replace view emp1 as select * from emp where salary>10000;View created
Dropping a View
Deleting a view can be done with the DROP VIEW command.
Syntax :SQL>drop view view_name;
Example:SQL>drop view emp1;
CREATING SYNONYMS
A synonym is an alternative name for objects such as tables, views, sequences, storedprocedures, and other
database objects.
Syntax :
SQL>create or replace synonym synonym_name for table_name;
Example:
SQL>create public employee synonym for emp; SQL>create or
replace public synonym employee FOR emp;synonym created
Drop synonym
Used to drop the synonym that has been created .
Syntax :
SQL>Drop public synonymsynonym_name;
example:
SQL>drop public synonym employee;
SEQUENCES
In Oracle, you can create an auto number field by using sequences. A sequence is an objectin Oracle that
is used to generate a number sequence. This can be useful when you need to create a unique number to act
as a primary key.
CREATING SEQUENCES
Syntax
CREATE SEQUENCE sequence_name
MINVALUE value
MAXVALUE value
START WITH value

INCREMENT BY value
CACHE value; Example:
CREATE SEQUENCE emp_seq
MINVALUE 1
MAXVALUE 999999999999999999999999999
START WITH 1
INCREMENT BY 1
CACHE 20;
This would create a sequence object called supplier_seq. The first sequence number that it would use is 1
and each subsequent number would increment by 1 (ie: 2,3,4,...}. It will cacheup to 20 values for
performance.
SQL>INSERT INTO emp (empno, ename) VALUES (emp_seq.NEXTVAL, 'asha');
Drop Sequence
Once you have created your sequence in Oracle, you might find that you need to remove itfrom the
database.
Syntax
The syntax to a drop a sequence in Oracle is:
SQL>DROP SEQUENCE sequence_name;
sequence_name is the name of the sequence that you wish to drop.
Example
SQL>DROP SEQUENCE emp_seq;

RESULT:
The database created and applied Views, Sequences, Synonyms in a database.
Implicit and Explicit Cursors

A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor.A cursor holds
the rows (one or more) returned by a SQL statement. The set of rows the cursor holds is referred to as the
active set.

There are two types of cursors −


• • Implicit cursors
• • Explicit cursors

IMPLICIT CURSORS:
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed,when there is no
explicit cursor for the statement. Programmers cannot control the implicit cursors and the information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursoris associated
with this statement. For INSERT operations, the cursor holds the data that needs to be inserted. For
UPDATE and DELETE operations, the cursor identifies the rows that would be affected.
In PL/SQL, we can refer to the most recent implicit cursor as the SQL cursor, which alwayshas attributes
such as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. The SQL cursor has additional
attributes, %BULK_ROWCOUNT and
%BULK_EXCEPTIONS, designed for use with the FORALL statement. The followingtable provides
the description of the most used attributes −

SNO ATTRIBUTES AND DESCRIPTION

1 %FOUND
Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows or
a SELECT INTO statement returned one or more rows. Otherwise,it returns FALSE.

2 %NOTFOUND
The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE
statement affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it
returns FALSE.

3 %ISOPEN
Always returns FALSE for implicit cursors, because Oracle closes the SQLcursor
automatically after executing its associated SQL statement.

4 %ROWCOUNT
Returns the number of rows affected by an INSERT, UPDATE, or DELETEstatement, or
returned by a SELECT INTO statement.
EXPLICIT CURSORS
Explicit cursors are programmer-defined cursors for gaining more control over the context area. An explicit
cursor should be defined in the declaration section of the PL/SQL Block. Itis created on a SELECT
Statement which returns more than one row.
The syntax for creating an explicit cursor is –

CURSOR cursor_name IS select_statement;

Working with an explicit cursor includes the following steps −


• • Declaring the cursor for initializing the memory
• • Opening the cursor for allocating the memory
• • Fetching the cursor for retrieving the data
• • Closing the cursor to release the allocated memory

Declaring the Cursor


Declaring the cursor defines the cursor with a name and the associated SELECT statement.For example –

CURSOR c_customers IS
SELECT id, name, address FROM customers;

Opening the Cursor


Opening the cursor allocates the memory for the cursor and makes it ready for fetching therows returned
by the SQL statement into it. For example, we will open the above defined cursor as follows –

OPEN c_customers;

Fetching the Cursor


Fetching the cursor involves accessing one row at a time. For example, we will fetch rowsfrom the above-
opened cursor as follows –

FETCH c_customers INTO c_id, c_name, c_addr;

Closing the Cursor


Closing the cursor means releasing the allocated memory. For example, we will close theabove-opened
cursor as follows –

CLOSE c_customers;
EX.NO: 4
Database Programming: Implicit and Explicit Cursors
DATE

AIM: To Create a database using Implicit and Explicit Cursors.

Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed,when there is no
explicit cursor for the statement. Programmers cannot control the implicit cursors and the information in it.
Example:
SQL>create table customers(id varchar(10), name varchar(10),age varchar(10),address
varchar(10),salary varchar(10));
Table created.
SQL>insert into customers values(&id,’&name’,&age,’&address’,&salary);

The following program will update the table and increase the salary of each customer by 500and use the
SQL%ROWCOUNT attribute to determine the number of rows affected − PL/SQL PROGRAM :
SQL> DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN dbms_output.put_line('no
customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line(total_rows || ' customers selected ');END IF;
END;
/

6 customers selected
PL/SQL procedure successfully completed.
Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over the context area. An explicit
cursor should be defined in the declaration section of the PL/SQL Block. Itis created on a SELECT
Statement which returns more than one row.
Example
Following is a complete example to illustrate the concepts of explicit cursors &minua;
SQL> DECLARE
c_idcustomers.id%type;
c_namecustomers.name%type;
c_addrcustomers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;EXIT
WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);END
LOOP;

CLOSE c_customers;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −1 Ramesh
Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP
PL/SQL procedure successfully completed.

Result:

Data base created and applied Implicit and Explicit Cursors in a database
EX.NO: 5
CREATION OF PROCEDURES AND FUNCTIONS
DATE

AIM:
To study and execute the procedures using control structures in PL/SQL.

PL/SQL :
A procedure is a block that can take parameters (sometimes referred to as arguments) and beinvoked.
Procedures promote reusability and maintainability. Once validated, they can be used in number of
applications. If the definition changes, only the procedure are affected, this greatly simplifies maintenance.
Modularized program development: · Group logically related statements within blocks. · Nest sub-blocks
inside larger blocks to build powerful programs. · Break down a complex problem into a set of manageable
well defined logical modules and implement the modules with blocks.

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. Parenthesis can be omitted ifno 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 its callingenvironment 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 its calling environmentafter execution.
RETURN: It is the data type of the function’s return value because every function mustreturn a value,
this clause is required.

SYNTAX:

PROCEDURES :
create or replace procedure <procedure name> (argument {in,out,inout} datatype ) {is,as}variable
declaration;
constant declaration;
begin PL/SQL subprogram body;
exceptionexception PL/SQL block;end;
Tables used:
SQL> select * from ititems;
ITEMID ACTUALPRICE ORDID PRODID
- - - - -
101 2000 500 201
102 3000 1600 202
103 4000 600 202
PROGRAM FOR GENERAL PROCEDURE – SELECTED RECORD‘S PRICE ISINCREMENTED
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
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 PRODID
- -
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 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/
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( ainout number) is2 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.
FUNCTIONS:
SYNTAX:
create or replace function <function name> (argument in datatype,……) return datatype
{is,as} variable declaration;
constant declaration;
begin PL/SQL subprogram body;
exceptionexception PL/SQL block;end;

PROGRAM FOR FUNCTION AND IT‘S EXECUTION

SQL> create function trainfn (trainnumber number) return number is2


trainfunctionittrain.tfare % type;
3 begin
4 select tfare into trainfunction from ittrain where tno=trainnumber;5
return(trainfunction);
6 end;
7/
Function created.
SQL> declare
2 total number;
3 begin
4 total:=trainfn (1001);
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 is2 fact


number:=1;
3 b number;
4 begin
5 b:=a;
6 while b>0
7 loop
8 fact:=fact*b;
9 b:=b-1;
10 end loop;
11 return(fact);
12 end;
13 /
Function created.
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

RESULT:

Database created successfully. Procedures and Functions are executed successfully.


EX.NO: 6
CREATION OF DATABASE USING TRIGGERS
DATE

AIM:
To study and execute Triggers in database.

TRIGGER

A Trigger is a stored procedure that defines an action that the database automatically takewhen some
database-related event such as Insert, Update or Delete occur.
TRIGGER VS. PROCEDURE VS CURSOR

TRIGGER PROCEDURES CURSORS


These are named PL/SQL These are named PL/SQL These are named PL/SQL
blocks. blocks blocks.

These are invoked User as per need invokes These can be created both
automatically. these. explicitly and implicitly.

These can’t take parameters. These can take parameters. These can take parameters.

These are stored in database. These are stored in database. These are not stored in
database.

TYPES OF TRIGGERS The various types of triggers are as follows,


• • Before: It fires the trigger before executing the trigger statement.
• • After: It fires the trigger after executing the trigger statement.
• • For each row: It specifies that the trigger fires once per row.
• • For each statement: This is the default trigger that is invoked. It specifies that thetrigger fires
once per statement.

VARIABLES USED IN TRIGGERS


• • new
• • old

These two variables retain the new and old values of the column updated in the database.The values in
these variables can be used in the database triggers for data manipulation

Row Level Trigger vs. Statement Level Trigger:

Row Level Trigger Statement Level Trigger

These are fired for each row affected bythe These are fired once for the statement insteadof the no
DML statement. of rows modified by it.
These are used for generating/checking thevalues These are used for generated the summary
begin inserted or updated. information

Before trigger vs. after trigger

Before Triggers After Triggers

Before triggers are fired before the DML After triggers are fired after the DML
statement is actually executed. statement has finished execution.

Syntax:
Create or replace trigger <trg_name>Before /After Insert/Update/Delete[ofcolumn_name,
column_name….]
on<table_name>
[for each row]
[when condition]
begin
---statement
End
Create a trigger that insert current user into a username column of an existing table
SQL> create table itstudent4(name varchar2(15),username varchar2(15));Table created.
SQL> create or replace trigger itstudent4 before insert on itstudent4 for each row2 declare
3 name varchar2(20);
4 begin
5 select user into name from dual;6
:new.username:=name;
7 end;
8/
Trigger created.
Output:

SQL> insert into itstudent4 values('&name','&username');Enter value


for name: akbar
Enter value for username: ranjani
old 1: insert into itstudent4 values('&name','&username')new 1:
insert into itstudent4 values('akbar','ranjani')
1 row created.
SQL> /
Enter value for name: suji
Enter value for username: priya
old 1: insert into itstudent4 values('&name','&username')new 1:
insert into itstudent4 values('suji','priya')
1 row created.
SQL> select * from itstudent4;
NAME USERNAME
-
akbar SCOTT
suji SCOTT
Create a Simple Trigger that does not allow Insert Update and Delete Operations onthe Table
Table used:
SQL> select * from itempls;
ENAME EID SALARY
- -
xxx 11 10000
yyy 12 10500
zzz 13 15500
Trigger:
SQL> create trigger ittrigg before insert or update or delete on itempls for each row2 begin
3 raise_application_error(-20010,'You cannot do manipulation');4 end;
5/
Trigger created.

Output:
SQL> insert into itemplsvalues('aaa',14,34000);insert into
itempls values('aaa',14,34000)
*
ERROR at line 1:
ORA-20010: You cannot do manipulation ORA-06512:at"STUDENT.ITTRIGG", line 2ORA-04088:
error during execution of trigger 'STUDENT.ITTRIGG'
SQL> delete from itempls where ename='xxx';delete
from itempls where ename='xxx'
*
ERROR at line 1:
ORA-20010: You cannot do manipulation ORA-
06512: at "STUDENT.ITTRIGG", line 2
ORA-04088: error during execution of trigger 'STUDENT.ITTRIGG'SQL> update
itempls set eid=15 where ename='yyy';
updateitempls set eid=15 where ename='yyy' develop a
query to Drop the Created TriggerSQL> drop trigger
ittrigg;
Trigger dropped.

Result:
Trigger program executed successfully
EX.NO: 7
PL/SQL BLOCK HANDLES ALL TYPES OF EXCEPTIONS
DATE

AIM:
To write a PL/SQL block to handle all types of exceptions.
PL/SQL - EXCEPTIONS
An error condition during a program execution is called an exception in PL/SQL. PL/SQLsupports
programmers to catch such conditions using EXCEPTION block in the programand an appropriate
action is taken against the error condition. There are two types of exceptions:
• • System-defined exceptions
• • User-defined exceptions

Syntax for Exception Handling


The General Syntax for exception handling is as follows. Here you can list down as many asexceptions 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
SQL> create table customer(custid number(5),name varchar(20),address varchar(30));Insert values into
table.
DECLARE

c_idcustomer.custid%type := 10;
c_namecustomer.name%type;
c_addrcustomer.address%type;
BEGIN
SELECT name, address INTO c_name, c_addrFROM
customer
WHERE custid = c_id; DBMS_OUTPUT.PUT_LINE
('Name: '|| c_name); DBMS_OUTPUT.PUT_LINE
('Address: ' || c_addr);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');WHEN
others THEN dbms_output.put_line('Error!');
END;
/
OUTPUT
No such customer!
PL/SQL procedure successfully completed.
Raising Exceptions
Exceptions are raised by the database server automatically whenever there is any internaldatabase 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. Auser-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:
This program asks for a customer ID, when the user enters an invalid ID, the exceptioninvalid_id is raised.
DECLARE
c_idcustomer.custid%type :=&cc_id;
c_namecustomer.name%type;
c_addrcustomer.address%type;
-- user defined exception
ex_invalid_id EXCEPTION;
BEGIN
IF c_id<= 0 THEN
RAISE ex_invalid_id;
ELSE
SELECT name, address INTO c_name, c_addrFROM
customer
WHERE custid = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);END IF;
EXCEPTION
WHEN ex_invalid_id THEN dbms_output.put_line('ID must
be greater than zero!');WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!'); END;
/
OUTPUT:
Enter value for cc_id: -6 (let's enter a value -6)old 2:
c_idcustomers.id%type := &cc_id;
new 2: c_idcustomers.id%type := -6;ID
must be greater than zero!
PL/SQL procedure successfully completed.

RESULT:
The exception handling program is executed successfully.
EX.NO: 8
DATABASE DESIGN USING NORMALIZATION
DATE

Aim:
To design database using normalization.
Definition and Syntax:
Normalization
Normalization is the process of minimizing redundancy in a database.A relation schema istaken and
subjected to a series of tests to verify whether it is in normal form or not.This process proceeds in top-
down fashion evaluating each relation against criteria and decomposing relations.It is proposed by Codd.
Normalization of data is a process of analyzing the given relation schemas based on theirfunctional
dependencies and primary keys to achieve the desirable properties of
A normal form is a state of a table that results from applying simple rules regardingfunctional
dependencies to that table.The various types of normal form are:
➢ First Normal Form(1NF): The multi-valued should be removed i.e elimination ofredundant
groups.

➢ Second Normal Form(2NF): The partial functional dependencies have to be removed


i.e elimination of redundant data.

➢ Third Normal Form(3NF): The transitive dependencies have to be removed i.eelimination


of columns not dependent on the key.

➢ Boyce-Codd Normal Form(BCNF): The remaining anomalies that result fromfunctional


dependencies are removed.

➢ Fourth Normal Form(4NF): Multi-valued dependencies are removed i.e isolation ofindependent
multiple relationships.

➢ Fifth Normal Form(5NF): Any remaining anomalies are removed.Here we isolatesemantically


related multiple relationships.

First Normal Form(1NF)


1NF states that the domain of an attribute must include only atomic (simple,indivisible) values and that
value of any attribute in a tuple must be a single value from the domain of that attribute.Hence 1NF
disallows multi-valued attributes,compositeattributes.It disallows“relations
within relations”.
Second Normal Form(2NF)
A relation is said to be in 2NF if it is already in 1NF and it has no partial dependency. 2NF isbased on the
concept of full functional dependency.
A functional dependency(FD) X→Y is full functional dependency if (X-(A))→Y does nothold
dependency any more if A X.
A functional dependency X→Y is partial dependency if A can be removed which does notaffect the
dependency i.e. (X-(A))→Y holds.
A relation is in 2NF if it is in 1NF and every non-primary key attribute is fully andfunctionally
dependent on primary key.
A relation in the 1NF will be in the 2NF if one of the following conditions is satisfied:The primary key
consist of only one attribute.
No non-key attribute exist in relation i.e. all the attributes in the relation are components ofthe primary key.
Every non-key attribute is FD on full set of primary key attributes.
Third Normal Form(3NF)
A relation is said to be in 3NF if it is already in 2NF and it has no transitive dependency.
A FD X→Y in a relation schema R is a transitive dependency if there is a set of attributes Zthat is neither a
candidate key nor a subset of any key of the relation and both X→Z and Z→Y hold.
Boyce-Codd Normal Form(BCNF)
A relation is said to be in BCNF if it is already in 3NF and every determinant is a candidatekey.It is stronger
version of 3NF.Every relation in BCNF is also in 3NF but the vice-versa may not hold

The formal definition of BCNF differs from the definition of 3NF.A relatio schema R is inBCNF if
whenever a non-trivial functional dependency X→A holds in R,then X is a superkey of R.
Procedure:
1. Create a type ‘Address’ to represent composite attribute.
2. Create the table
3. Insert the values in the table.
4. Draw the E-R diagram for the table.
5. Convert the given table to the normalized form.
a) Converting a table to 1NF:
To convert a table to 1NF removes all the multi valued & composite attributes from thetable.
b) Converting a Table to 2NF: i) Find and remove attributes that are functionallydependent
on only a part of the key and not on the whole key. Place them in a different table.Group the
remaining attributes.

FIRST NORMAL FORM:


SQL>create type address as object(sno number(5),2 sname
varchar2(20),
3 city varchar2(20),
4 state varchar2(20));
/
Type created.
SQL>create table Employees(eno number(3) primary key,2
enmaevarchar2(20),
3 eadd address,
4 salnumber(7,2))
SQL> /
Table created.
SQL>desc employees
Name Null? Type
- --
ENO NOT NULL NUMBER(3)
ENMAE VARCHAR2(20)
EADD ADDR
SAL NUMBER(7,2)
SQL> insert into employees
values(&eno,'&enmae',address(&sno,'&sname','&city','&state'),&sal); Enter value
for eno: 001
Enter value for enmae: anbu
Enter value for sno: 12
Enter value for sname: Ist streetEnter
value for city: chennai Enter value
for state: tamilnaduEnter value for
sal: 10000
old 1: insert into employees
values(&eno,'&enmae',address(&sno,'&sname','&city','&state'),&sal) new 1: insert
into employees values(001,'anbu',address(12,'Ist
street','chennai','tamilnadu'),10000)
1 row created.
SQL> /
Enter value for eno: 002 Enter
value for enmae: baluEnter
value for sno: 13
Enter value for sname: car streetEnter
value for city: madurai Enter value
for state: tamilnadu Enter value for
sal: 10000
old 1: insert into employees
values(&eno,'&enmae',address(&sno,'&sname','&city','&state'),&sal) new 1: insert
into employees values(002,'balu',address(13,'car
street','madurai','tamilnadu'),10000)
1 row created.
SQL> /
Enter value for eno: 003 Enter
value for enmae: chiruEnter
value for sno: 10
Enter value for sname: 9th street Enter
value for city: hyderabad Enter value for
state: andhrapradeshEnter value for sal:
15000
old 1: insert into employees
values(&eno,'&enmae',address(&sno,'&sname','&city','&state'),&sal) new 1: insert
into employees values(003,'chiru',address(10,'9th
street','hyderabad','andhrapradesh')
1 row created.
SQL> select * from employees;
ENO ENMAE EADD(SNO, SNAME, CITY, STATE) SAL
- -
1 anbu ADDR(12, 'Ist street', 'chennai', 'tamilnadu') 10000
2 balu ADDR(13, 'car street', 'madurai', 'tamilnadu') 10000
3 chiru ADDR(10, '9th street', 'hyderabad', 'andhrapradesh') 15000
Normalizing the table to 1NF:
SQL> create table en1 as select eno, ename ,sal from employees;Table created.
SQL> alter table en1 add primary key(eno);Table
altered.
SQL>desc en1
Name Null? Type
- --
ENO NOT NULL NUMBER(3)
ENAME VARCHAR2(15)SAL
NUMBER(7,2)
SQL> create table en2 as select eno,eadd from employees;Table created.
SQL> alter table en2 add foreign key(eno) references en1(eno);Table
altered.
SQL>desc en2
Name Null? Type
- --
ENO NUMBER(3)
EADD ADDR
Normalizing to 1NF
employee

EMPNO EMPNAME EMPADDR SAL

SECOND NORMAL FORM:


SQL> create table empproject(eno number(3) primary key,2 ename
varchar2(20),
3 pno number(3) unique,4
pname varchar2(20),
5 hours number(3));
Table created.
SQL>descempproject Name
Null? Type
- --
ENO NOT NULL NUMBER(3)
ENAME VARCHAR2(20)
PNO NUMBER(3) PNAME
VARCHAR2(20)HOURS
NUMBER(3)
SQL> insert into empprojectvalues(&eno,'&ename',&pno,'&pname',&hours);Enter value
for eno: 101
Enter value for ename: raja
Enter value for pno: 12
Enter value for pname: compilersEnter
value for hours: 12
old 1: insert into empproject values(&eno,'&ename',&pno,'&pname',&hours)new 1: insert
into empproject values(101,'raja',12,'compilers',12)
1 row created.
SQL> /
Enter value for eno: 102 Enter
value for ename: raguEnter
value for pno: 13 Enter value
for pname: atmEnter value for
hours: 24
old 1: insert into empproject values(&eno,'&ename',&pno,'&pname',&hours)new 1: insert
into empproject values(102,'ragu',13,'atm',24)
1 row created.
SQL> /
Enter value for eno: 103 Enter
value for ename: sunilEnter
value for pno: 14
Enter value for pname: roboticsEnter
value for hours: 15
old 1: insert into empproject values(&eno,'&ename',&pno,'&pname',&hours)new 1: insert
into empproject values(103,'sunil',14,'robotics',15)
1 row created.
SQL> select * from empproject;
ENO ENAME PNO PNAME HOURS
- - - -
101 raja 12 compilers 12
102 ragu 13 atm 24
103 sunil 14 robotics 15
Normalizing the table to 2NF:
SQL>create table ep1 as select eno,ename from empproject;Table created.
SQL>alter table ep1 add primary key(eno);Table
altered.
SQL>desc ep1
Name Null? Type
- --
ENO NOT NULL NUMBER(3)
ENAME VARCHAR2(20)
SQL>create table ep2 as select pno,pname from empproject;Table
created.
SQL>alter table ep3 add primary key(pno);Table
altered.
SQL>desc ep2
Name Null? Type
- --
PNO NOT NULL NUMBER(3)
PNAME VARCHAR2(20)
SQL>create table ep3 as select eno,pno,hours from empproj;Table
created.
SQL>alter table ep3 add primary key(eno);Table
altered.
SQL>alter table ep3 add unique(pno);Table
altered.
SQL>desc ep3
Name Null? Type
- --
ENO NOT NULL NUMBER(3)
PNO NUMBER(3)
HOURS NUMBER(3)
Normalizing to 2NF:
EMPNO EMPNAME PNO PNAME HOURS

EMP NO EMP NAME

P NO P NAME

ENO PNO HRS

THIRD NORMAL FORM:


SQL>create table empdept (enonumber(3) primary key,2 ename
varchar2(20),
3 sal number(7),
4 dno number(3),
5 dnamevarchar2(20));
Table created.
SQL>descempdept
Name Null? Type
- --
ENO NOT NULL NUMBER(3)
ENAME VARCHAR2(20)SAL
NUMBER(7)
DNO NUMBER(3) DNAME
VARCHAR2(20)
SQL> insert into empdeptvalues(&eno,'&ename',&sal,&dno,'&dname');Enter value
for eno: 101
Enter value for ename: ravi
Enter value for sal: 10000
Enter value for dno: 1 Enter
value for dname: cse
old 1: insert into empdept values(&eno,'&ename',&sal,&dno,'&dname')new 1: insert
into empdept values(101,'ravi',10000,1,'cse')
1 row created.
SQL> /
Enter value for eno: 102 Enter
value for ename: ragu
Enter value for sal: 20000
Enter value for dno: 2 Enter
value for dname: eee
old 1: insert into empdept values(&eno,'&ename',&sal,&dno,'&dname')new 1: insert
into empdept values(102,'ragu',20000,2,'eee')
1 row created.
SQL> select * FROM EMPDEPT; ENO
ENAME SAL DNO DNAME
- - -
101 ravi 10000 1 cse
102 ragu 20000 2 eee
Normalizing the table to 3NF:
SQL>create table ed1 as select eno,ename,sal,dno from empdept;Table created.
SQL>alter table ed1 add primary key(eno);Table
altered.
SQL>desc ed1
Name Null? Type
- --
ENO NOT NULL NUMBER(3)
ENAME VARCHAR2(20)SAL
NUMBER(7,2)
DNO NUMBER(3)
SQL>create table ed2 as select dno,dname from empdept;Table
created.
SQL>alter table ed2 add primary key(dno);
SQL>desc ed2
Name Null? Type
- --
DNO NOT NULL NUMBER(3)
DNAME VARCHAR2(20)
SQL>alter table ed1 add foreign key(dno) references ed2(dno);Table
altered.
Normalizing to 3NF:
Empdept
EMP EMP SAL DNO DNAME
NO NAME

EMP EMP SAL DNO


NO NAME

DNO DNAME
RESULT:
Thus the database designed using normalization
EX.NO: 9 DESIGN AND IMPLEMENTATION OF PERSONAL INFORMATION
DATE SYSTEM (MINI PROJECT)

AIM:

To develop a personal information system using Oracle as a back end (data base) andMicrosoft
Visual Basic 6.0 as a Front end.
PROCEDURE:

1.Create an employee database with the following fields in Oracle namely


Empno,Empname,address,Basicpay and insert some record into the database. 2.Design the
corresponding form with labels ,text boxes and command buttons.Form1→Employee payroll
3. Connect the back end with the front end using DAO method by creating a dsn as followsa .Select
Administrative Tools option from Control Panel .
Then click on Data Sources (ODBC), which displays a dialog box namedODBC
DataSourceAdministrator in which click Add button.
b. In Create New Data Source dialog box, select “Microsoft ODBC forORACLE”and click
finish button.
c. Give a suitable DataSourceName =payrolldsn,
username=secit1 and
server name=oracle11g.
4. And then click OK and now move to visual basic 6.0
5. Go to ‘Project’ then click ’reference’ in menu bar and select “Microsoft DAO 3.6 ObjectLibrary” and
then give OK.
6. A fter completed adding of ‘references’ click ‘debug’ project in menu bar.
7. Execute the project and perform the transaction in banking system.
TABLE DESIGN:
Table Name : Employee
Name Type
----------------------------------- --------------------------- EMPNO
NUMBER(6)
EMPNAME VARCHAR2(30)
ADDRESS VARCHAR2(20)
BASIC NUMBER(8,2)
Form :

Dim db As Database
Dim rs As Recordset
Private Sub CALCULATE_Click()Dim
A, B, C As Double
A = Val(Text5.Text) * 0.05B =
Val(Text5.Text) * 0.03 C =
Val(Text5.Text) * 0.07
Text5.Text = A
Text6.Text = B
Text7.Text = C
Text8.Text = Val(Text4.Text) + A + B - CEnd
Sub
Private Sub CLEAR_Click()
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
Text5.Text = ""
Text6.Text = ""
Text7.Text = ""
Text8.Text = ""
End Sub
Private Sub DELETE_Click()
rs.DELETE
rs.MoveNext If
rs.EOF Then
MsgBox "NO MORE RECORD"
Else
Text1.Text = rs(0)
Text2.Text = rs(1)
Text3.Text = rs(2)
Text4.Text = rs(3)
End If
End Sub
Private Sub EXIT_Click()End
End Sub
Private Sub FIND_Click()
I = InputBox("ENTER THE EID", FIND)
rs.FindFirst "[EID]=" & IIf
rs.NoMatch Then
MsgBox "NO MATCHING RECORD FOUND"
Else
Text1.Text = rs(0)
Text2.Text = rs(1)
Text3.Text = rs(2)
Text4.Text = rs(3)
end If
End Sub
Private Sub FIRST_Click()
rs.MoveFirst
Text1.Text = rs(0)
Text2.Text = rs(1)
Text3.Text = rs(2)
Text4.Text = rs(3)
End Sub
Private Sub Form_Load()
Set db = OpenDatabase("payrolldsn", False, False, "ODBC;uid= secit1; pwd=secit1;") Set rs =
db.OpenRecordset("SELECT * FROM employee")
Text1.Text = rs(0)
Text2.Text = rs(1)
Text3.Text = rs(2)
Text4.Text = rs(3)
End Sub
Private Sub INSERT_Click()
rs.MoveLast
rs.AddNew
rs(0) = Text1.Text
rs(1) = Text2.Text
rs(2) = Text3.Text
rs(3) = Text4.Text
rs(4) = Text5.Text
rs.UPDATE
End Sub
Private Sub LAST_Click()
rs.MoveLast
Text1.Text = rs(0)
Text2.Text = rs(1)
Text3.Text = rs(2)
Text4.Text = rs(3)
End Sub
Private Sub NEXT_Click()
rs.MoveNext
If rs.EOF Then
MsgBox "NO MORE RECORDS"
Else
Text1.Text = rs(0)
Text2.Text = rs(1)
Text3.Text = rs(2)
Text4.Text = rs(3)
End If
End Sub
Private Sub PREVIOUS_Click()
rs.MovePrevious
If rs.BOF Then
MsgBox ("No more records")Else
Text1.Text = rs(0)
Text2.Text = rs(1)
Text3.Text = rs(2)
Text4.Text = rs(3)
End If
End Sub
Private Sub UPDATE_Click()
rs.Edit
rs(0) = Text1.Text
rs(1) = Text2.Text
rs(2) = Text3.Text
rs(3) = Text4.Text
rs(4) = Text5.Text
rs.UPDATE
End Sub
FORM

RESULT:
Thus the Database Connectivity with Front End Tools is designed successfully.
EX.NO:
10 Oracle Database system - A case study

DATE

Oracle Database system - A case study


The following case studies for SQL Server demonstrate some of the features of the Oracle Database
Gateway. You can verify that the gateway is installed and operating correctly byusing the demonstration
files included in the distribution media.
The demonstration files are automatically copied to disk when the gateway is installed.Case Descriptions
The cases illustrate:
• • A simple query (Case 1)
• • A more complex query (Case 2)
• • Joining SQL Server tables (Case 3)
• • The pass-through feature (Case 4)

Installation Media Contents


The installation media contains the following:
• • Demonstration files
• • One SQL script file that creates the demonstration tables and stored procedures in theSQL Server
database
• • One SQL script file that drops the demonstration tables and stored procedures fromthe SQL
Server database

Demonstration Files
After a successful gateway installation, use the demonstration files stored in the directory
ORACLE_HOME\dg4msql\demo where ORACLE_HOME is the directory under which thegateway is
installed. The directory contains the following demonstration files:
• • bldmsql.sql
• • case1.sql
• • case2.sql
• • case3.sql
• • case4a.sq Demonstration
Requirements
The case studies assume these requirements have been met:
• • The gateway demonstration tables and stored procedures are installed in the SQLServer
database
• • The Oracle database has an account named SCOTT with a password of TIGER
• • The Oracle database has a database link called GTWLINK (set up as public or private to the user
SCOTT) which connects the gateway to a SQL Server database as SCOTTwith password TIGER2

• For example, you can create the database link as follows


SQL> CREATE DATABASE LINK GTWLINK CONNECT TO SCOTT2
IDENTIFIED BY TIGER2 USING 'GTWSID';

Oracle Net Services is configured correctly and runningCreating


Demonstration Tables
The case studies are based on the GTW_EMP, GTW_DEPT, and GTW_SALGRADE tablesand the stored
procedures InsertDept and GetDept. If the demonstration tables and stored procedures have not been created in
the SQL Server database, use the bldmsql.sql script to create them. Enter the following:

> isql -USCOTT -PTIGER2 -ibldmsql.sql


The script creates the demonstration tables and stored procedures in the SQL Serverdatabase
accordingly:

CREATE TABLE GTW_EMP (


EMPNO SMALLINT NOT NULL
ENAME VARCHAR(10),
JOB VARCHAR(9

MGR SMALLINT,
HIREDATE DATETIME,
SAL NUMERIC(7,2), COMM
NUMERIC(7,2), DEPTNO
SMALLINT)
Go

Demonstration Table Definitions

The following table definitions use information retrieved by the SQL*PLUS DESCRIBEcommand:
GTW_EMP

CopyName Null? Type


-
EMPNO NOT NULL NUMBER(5)
ENAME VARCHAR2(10)
JOB VARCHAR2(9) MGR
NUMBER(5) HIREDATE
DATE SAL NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NUMBER(5)

Simple Queries
Case 1 demonstrates the following:
• • A simple query
• A simple query retrieving full date information
The first query retrieves all the data from GTW_DEPT and confirms that the gateway is working
correctly. The second query retrieves all the data from GTW_EMP including thetime portion of the hire
date because the default date format was set to DD-MON-YY HH24:MM:SS for the session by an
ALTER SESSION command.
A More Complex Query
Case 2 demonstrates the following:
• • The functions SUM(expression) and NVL(expr1, expr2) in the SELECT list
• • The GROUP BY and HAVING clauses

This query retrieves the departments from GTW_EMP whose total monthly expenses arehigher than
$10,000.
Joining SQL Server Tables
Case 3 demonstrates the following:
• • Joins between SQL Server tables
• • Subselects

The query retrieves information from three SQL Server tables and relates the employees to their department
name and salary grade, but only for those employees earning more than theaverage salary.
Write Capabilities
Case 4 is split into three cases and demonstrates the following:
• • DELETE Statement
• • UPDATE Statement
• • INSERT Statement

DELETE Statement
Case 4a demonstrates bind values and subselect. All employees in department 20 and oneemployee, WARD, in
department 30 are deleted.
UPDATE Statement
Case 4b provides an example of a simple UPDATE statement. In this example, employeesare given a
$100 a month salary increase

INSERT Statement
Case 4c is an example of a simple insert statement that does not provide information for allcolumns.
Case 6: The Pass-Through Feature
Case 6 demonstrates the gateway pass-through feature which allows an application to sendcommands or
statements to SQL Server.
This case demonstrates:
• • A pass-through UPDATE statement using bind variables
• • A pass-through SELECT statement
• UPDATE Statement
Case 6a provides an example of a pass-through UPDATE statement with bind variables. Inthis example, the
salary for EMPNO 7934 is set to 4000.
SELECT Statement Case 6b provides an example of a pass-through SELECT statement. Thedata that is
returned from the SELECT statement is inserted into a local table at the Oracle database
EX.NO:
DESIGN AND IMPLEMENTATION OF HOSPITAL MANAGEMENTSYSTEM
11
(MINI PROJECT)
DATE

AIM:
To design and implement the application, ‘Hospital management system’ using MS Access as a back end
(data base) and Microsoft Visual Basic 6.0 as a Front end.

PROCEDURE:

1. Create a two database (patient,staff)in MS Access with necessary fields.


2. Design the corresponding form with labels ,text boxes and command buttons.
3. Connect the back end with the front end using DAO method by creating a dsn as follows
a) Select control panel ->system and security - > choose Administrative Tools option
b) Then double click on Data Sources (ODBC), which displays a dialog box named ODBCData So
c) urce Administrator in which click Add button.
d) In Create New Data Source dialog box, select “Microsoft Access Driver (*.mdb,*.accdb) click finish
button.
e) Give a suitable DataSourceName =patientdsn, and click on select option→ choose your database location
“c:\users\secit10\documents” and choose your table which appears→OK→OK
4. And then click OK and now move to visual basic 6.0
5. Go to ‘Project’ then click ’reference’ in menu bar and select “Microsoft DAO 3.6 Object

Library” and then give OK.


6. Go to ‘Project’ then click ’components’ in menu bar and select “Microsoft ADO Data Control 6.0
(OLEDB) ”and also choose Microsoft DataGrid Control6.0(OLEDB)→Apply→OK.
7. Choose adodc and place on form2 and also choose datagrid control and place it on form2
8. Now click on adodc1→goto property window→ choose connection string→click 2nd option use
connection string →click build→by default Microsoft OLEDB provider for ODBC Driver will be
choosed→click next→choose machine datasource→click new→click user datasource→next→ Microsoft
access driver(*.md,*.accdb) →next→finish
9. Click testconnection→test connection succeed→ok→3.enter the initial catalog to use-
→choose your table→ok→apply
10. Choose 3rd option recordsource→ in cmd text of SQL→type “select * from
patient;”→ok
11. Also repeat the same for staff table
12. Click →text1.text →properties will be opened→datasource→adodc1 and also in datafield→choose
the appropriate field.
13. Repeat the from step 3-12 for connectivity of staff database.
14. Now give coding and execute the program

FORM 1:
Private Sub OK_Click()
If Text1.Text = "admin" Then
If Text2.Text = "admin" Then
MsgBox "welcome to user"
Form2.Show
Else
MsgBox" incorrect password"End
If
Else
MsgBox "incorrect User name"End
If
Text1.Text = ""
Text2.Text = ""
End Sub
Private Sub CANCEL_Click()
Unload me
End Sub
FORM 2:
Private Sub PATIENTDETAIL_Click()
Form3.Show
End Sub
Private Sub STAFFDETAIL_Click()
Form4.Show
End Sub
Private Sub HOME_Click()
Form1.Show
End Sub
FORM 3:
Dim DB As Database Dim
RS AsRecordset Private Sub
Form_Load()
Set db = OpenDatabase("C:\Users\Administrator\Documents\patient.mdb")Set rs=
db.OpenRecordset("patient", dbOpenDynaset)
End Sub
Private Sub CLEAR_Click()
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
Text5.Text = ""
End Sub
Private Sub DELETE_Click()
Adodc1.Recordset.Delete End Sub
Private Sub HOME_Click()
Form2.show
End Sub
Private Sub FIRST_Click()
Adodc1.Recordset.MoveFirstEnd Sub
Private Sub INSERT_Click()
Adodc1.Recordset.Update End
Sub
Private Sub LAST_Click()
Adodc1.Recordset.MoveLast End
Sub
Private Sub NEXT_Click()
Adodc1.Recordset.MoveNextEnd
Sub
Private Sub PREVIOUS_Click()
Adodc1.Recordset.MovePreviousEnd
Sub
Private Sub UPDATE_Click()
Adodc1.Recordset
End Sub
FORM 4 :
Dim DB As Database Dim
RS AsRecordset Private Sub
Form_Load()
Set db = OpenDatabase("C:\Users\Administrator\Documents\staff.mdb")Set rs=
db.OpenRecordset("staff", dbOpenDynaset)
End Sub
Private Sub CLEAR_Click()
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
Text5.Text = ""
Text6.Text = ""
End Sub
Private Sub DELETE_Click()
Adodc1.Recordset.DELETE MsgBox
"the record is delected"End Sub
Private Sub EXIT_Click()
Unload me
End Sub
Private Sub FIRST_Click()
Adodc1.Recordset.MoveFirstEnd Sub
Private Sub INSERT_Click()
Adodc1.Recordset.Update End
Sub
Private Sub LAST_Click()
Adodc1.Recordset.MoveLast End
Sub
Private Sub NEXT_Click() Adodc1.Recordset.MoveNext
End Sub
Private Sub PREVIOUS_Click()
Adodc1.Recordset.MovePreviousEnd
Sub
Private Sub UPDATE_Click()
Adodc1.Recordset.UPDATE
MsgBox "the record is updated"End
Sub

FORM1

FORM2
FORM3

FORM4

Result:
Thus the Hospital Management System Mini project has been implemented and executedsuccessfully.
EX.NO:
DESIGN AND IMPLEMENTATION OF LIBRARY MANAGEMENTSYSTEM (MINI
12
PROJECT)
DATE

AIM:
To design and implement the application, ‘Library management using Sql Queries.
Procedure:
LIBRARY MANAGEMENT SYSTEM:
1. Create the Database.
2. Create the following tablesTables Book_Details Binding_Details Category_Details
Borrower_Details Student_Details Staff_Details Student_Details Shelf_Details
3. Normalization
4. ER-Diagram
5. Use the SQL Command (select, update, insert, delete) Creating table “Book_Details”: Inserting Some
Data in “Book_Details” Creating table “Binding_Details”: Creating Relationship Between Book and
Binding Table: Creating Category Table: Building Relationship between Book & Category Table: Creating
Borrower Table: Building RelationBetween Book & Borrower Table Creating Staff Table Building
Relationship between student and Borrower table: Checking Full Relationship Adding Shelf Table Adding
Relationship Between Shelf and Book Table Combined All Relationship

Library Management System

Introduction

The Database Library System is intended to Automate the library activities such as creating anew borrower,
giving books to the borrowers, maintaining the details of all the item that were available in the books . This
also helps the librarians by providing information such as total copies available each book, list of books that
belong to a particular category (Short, Long Loan, Reference items, etc). Tables Book_Details: This is the
master table for all the books that are available in the Library. This table contains the complete list of books
that areavailable in the library. Each Book id provided with a unique ISBN which serves as a primary key.
The book details include the ISBN, Book Title, the year in which that particularbook was published, the type
of binding either soft cover or hard cover and the category.
Columns ISBN: This is unique ID given to every book .Since there may be a large no. ofbooks with
same TITLE, this ISBN no. will help us to distinguish between books of same title. Book_Title:
Provides the name of the book. Publication_year: Contains the year of publication in ‘YY’ format
(eg:2009à09) Language: Contains the language in which thisbook was published. Category_Type
This column contains the Category ID whose details can be fetched form the category_master table. The
category ID is a Unique number given to each category. Binding
_Id
This column contains the Binding ID whose details can be fetched form the Binding_Detailstable.The Binding
ID is a Unique number given to each type Binding. No_Of_Copies_Actual: This column contains the total no.
of copies of each book that wereinitially present. No_Of_Copies_Current: This column contains the total no.
of copies of
each book that were currently available . Binding_Details: This table is the Master table forthe binding
types.This includes the binding ID and Binding

Name. The Binding ID serves as a primary key. Columns: Binding_ID: This column contains the Unique
number that was given to each type of binding. Binding_Name: This column give the names of different
types of binding. Category_Details: This includes the Category ID and Category Name. The Category ID
servers as a primary key. Columns: Category _ID: This column contains the Unique number that was given
to each type of Category. Category _Name: This column give the names of different types of categories.
Borrower_Details: This table contains the details of all the persons who lent a book from the library. Each
Student will be given a Unique borrower ID. All the library related activity for a particular person will be
captured based on the Borrower ID. This table will be used to track the borrowing records. The borrower ID
will serve as a primary key here. Columns: Borrower_ID: Unique ID given to each Student. Book_ID:
This column contains the book ID which was give to the borrower. Borrowed_From_Date: The date on
which the book was given a particular borrower. Borrowed_To_Date: The date on which that book was
supposed to be returned back or should be renewed. Actual_Return_date: The date on which the borrower
returned the book to the library. Issued_by: The ID of the Librarian whoissued book to the borrower.
staff_Details: This table contains the details of the staff in the Library. Each Staff member will be given a
unique User ID which serves as a Primary Key. Columns

User_ID: The unique ID given to each staff member present in the Library. User_Name: The Name of the
staff member. Is_Admin: Just checking user is admin or not. Designation:The role of the staff member in
the library such as librarian, assistant, etc. Student_Details: This table contains the details of all the
students they are eligible for availing Library facilities. Each student will be provided with a unique Student
ID and Borrower ID. The student ID will be Primary Key, whereas Borrower_ID and Phone_no will be
Unique.
Columns: Student_id: Unique ID given to Each Student. Student_Name: The Name of theStudent. Sex :
Gender of the Student either Male or Female. Date_Of_Birth: The Date of Birth of the student.
Borrower_ID: The borrower ID assigned to each student. Department:This is contains student department.
Contact_Number: Contact number of the student.
Shelf_Details: This table contain the position of the book…That means which floor andshelf the book is
situated.
Column: Shelf_Id: Contains the shelf number. Floor: Which floor the shelf is situated.
Library Management System (SQL Commands) Creating table “Book_Details”:

1. CREATE TABLE Book_Details2. (


3. ISBN_Codeint PRIMARY KEY,
4. Book_Titlevarchar(100),
5. Language varchar(10),
6. Binding_Idint,
7. No_Copies_Actualint,
8. No_Copies_Currentint,
9. Category_idint,
10. Publication_yearint
11. )
Inserting Some Data in “Book_Details” :
1. INSERT INTO Book_details
2. VALUES('0006','Programming Concept','English',2,20,15,2,2006);

Creating table “Binding_Details”:


1. CREATE TABLE Binding_details2. (
3. Binding_idint PRIMARY KEY,
4. Binding_Namevarchar(50) 5. )

Describe Binding table: Describe binding_details Inserting Some data in Binding Table:
1. INSERT INTO Binding_DetailsVALUES(1,'McGraw Hill);
2. INSERT INTO Binding_DetailsVALUES(2,'BPB Publication');

All Data of Binding Table:


1. select *from binding_Details

Creating Relationship Between Book and Binding Table:


1. ALTER TABLE Book_details

2. ADD CONSTRAINT Binding_ID_FK FOREIGN KEY(Binding_Id) REFERENCES


Binding_Details(Binding_Id);
Checking Relationship:
1. selectb.Book_Title, e.binding_name
2. fromBook_Detailsb, Binding_Details e
3. whereb.binding_id = e.binding_id;

Creating Category Table:


1. CREATE TABLE Category_Details2. (
3. Category_Idint PRIMARY KEY,
4. Category_Namevarchar(50) 5. )

Inserting some data in Category Table:


1. INSERT INTO CATEGORY_DETAILS VALUES(1,'Database');
2. INSERT INTO CATEGORY_DETAILS VALUES(2,'Programming Language');

Building Relationship between Book & Category Table:


1. ALTER TABLE Book_details
2. ADD CONSTRAINT Category_Id_FK FOREIGN KEY(Category_Id) REFERENCES
Category_Details(Category_Id);

Checking Relationship:
1. selectb.Book_Title,e.Category_Name
2. fromBook_Detailsb,Category_Details e
3. whereb.binding_id = e.Category_id;

Creating Borrower Table:

1. CREATE TABLE Borrower_Details2. (


3. Borrower_Idint PRIMARY KEY,
4. Book_Idint,
5. Borrowed_From date,
6. Borrowed_TO date,
7. Actual_Return_Date date,
8. Issued_byint9.
)
Inserting Some data in Category Table:
1. Insert into BORROWER_DETAILS VALUES(1,0004,'01-Aug-2014','7-Aug-2014','7-Aug-2014',1)
2. Insert into BORROWER_DETAILS VALUES(2,6,'02-Aug-2014','8-Aug-
2014',NULL,1)

Building Relation Between Book & Borrower Table:


1. ALTER TABLE Borrower_details ADD CONSTRAINT Book_Id_FK FOREIGN
KEY(Book_Id) REFERENCES Book_Details(ISBN_Code);

Checking Relationship:
1. selectBorrower_Details.Borrower_id,Book_Details.Book_title
2. fromBorrower_Details,Book_Details
3. whereBorrower_Details.book_id=Book_Details.ISBN_Code

1. ALTER TABLE Borrower_Details


2. ADD CONSTRAINT Issued_by_FK FOREIGN KEY(Issued_by) REFERENCES
Staff_Details(Staff_Id);

Creating Staff Table :


1. CREATE TABLE Staff_Details2. (
3. Staff_Idint PRIMARY KEY,
4. Staff_Namevarchar(50),
5. Password varchar(16),
6. Is_Adminbinary_float,
7. Designation varchar(20)

8. )
Inserting some data in Staff Table:
1. Insert into STAFF_DETAILS values (1,'Tarek Hossain','1234asd',0,'Lib_mgr');
2. Insert into STAFF_DETAILS values (2,'Md.Kishor Morol','iloveyou',0,'Lib_clr');

All Data of Staff table:


1. select * from staff_details

Creating Student Table:


1. Create TABLE Student_Details2. (
3. Student_Idvarchar(10) PRIMARY KEY,
4. Student_Namevarchar(50),
5. Sex Varchar(20),
6. Date_Of_Birth date,
7. Borrower_Idint,
8. Department varchar(10),
9. contact_Numbervarchar(11)
10. )

Inserting Some Data in Student Table:


1. Insert into STUDENT_DETAILS values ('13-23059-1','Ahmed,Ali','Male','05-Oct-
1995',1,'CSSE','01681849871');
2. Insert into STUDENT_DETAILS values ('13-23301-1','MOrol MD.Kishor','Male','03-Jan-
1994',2,'CSE','01723476554');

All Data of Student Table:


1. select *from student_details

Building Relationship between student and Borrower table:

1. ALTER TABLE student_details


2. ADD CONSTRAINT borrower_id_FK FOREIGN KEY(Borrower_Id) REFERENCES
Borrower_Details(Borrower_Id);
Checking Full Relationship:
1. select student.student_id, student.student_name, book.Book_Title, staff.staff_name,
b.Borrowed_To
2. fromstudent_Detailsstudent, Staff_Detailsstaff, Borrower_Detailsb, book_details book
3. wherestudent.Borrower_id = b.Borrower_id and book.ISBN_Code = b.book_id andb.Issued_by =
staff.Staff_id;

Adding Shelf Table:


1. Create Table Shelf_Details
2. (
3. Shelf_idint PRIMARY KEY,
4. Shelf_Noint,
5. Floor_Noint6.
);

Inserting Some Data from Shelf Table:


1. Insert into Shelf_DetailsValues(1, 1, 1);
2. Insert into Shelf_DetailsValues(2, 2, 10001);
3. Insert into Shelf_DetailsValues(3, 1, 10002);

All Data In Shelf Table:


1. select*from Shelf_Details;

Adding Relationship Between Shelf and Book Table:


1. ALTER TABLE Book_Details
2. ADD(Shelf_Idint);

3.
4. UPDATE Book_Details set Shelf_Id = 1
5. where ISBN_CODE = 4;6.
7. UPDATE Book_Details set Shelf_Id = 2
8. where ISBN_CODE = 6;9.
10. ALTER TABLE Book_Details
11. ADD CONSTRAINT Shelf_Id_FK FOREIGN KEY(Shelf_Id) REFERENCES
Shelf_Details(Shelf_Id);
Combined all Relationship:
1. select student.student_id, student.student_name, book.Book_Title, staff.staff_name,
b.Borrowed_To, shelf.shelf_No
2. fromstudent_Detailsstudent, Staff_Detailsstaff, Borrower_Detailsb, book_detailsbook,Shelf_Details
shelf
3. wherestudent.Borrower_id = b.Borrower_id and book.ISBN_Code = b.book_id andb.Issued_by =
staff.Staff_id and book.Shelf_Id = shelf.Shelf_Id;

RESULT:
Thus the Library Management System Mini project has been implemented and executedsuccessfully

You might also like