0% found this document useful (0 votes)
94 views56 pages

DBMS Lab Manual

Uploaded by

pallapurnachandu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
94 views56 pages

DBMS Lab Manual

Uploaded by

pallapurnachandu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Database Management Systems

Laboratory Manual

G. Mahesh
Associate Professor

(For private circulation among the students)

Department of Computer Science and Engineering


S.R.K.R. Engineering College
Bhimavaram – 534204.
Dedicated to

To Honorable Secreatary and Correspondent of our College


Sri S.Atchutha Rama Raju

To Our beloved Head of C.S.E. Department


Prof. G.V.Padma Raju

Author:
G.MAHESH,
Associate professor,
Dept of C.S.E.

Co-Authors:
K.V Krishnam Raju,
Associate professor,
Dept of C.S.E.

K.Aruna Kumari,
Assistant professor,
Dept of C.S.E.
Index

Exp. No. Title of Experiment Page No.

1. Simple SQl commands 1

2. Creation of tables 5

3. Set Operations 12

4. Functions and Procedures 18

5. Triggers 26

6. Creation of Database in MS-Access 30

7. Creation of Forms & Reports in


MS-Access 36

8. Importing Tables 41

9. Mini Project 45

10. MySQL 46
Database Management System Lab Manual 1

Expno: 01 Date:
Simple SQL commands
Aim:-
To Practice simple SQL commands for retrieving data contained in
‘Emp’ and ‘ Dept’ tables.
Theory:-
Questions including data stored in a Data Base are called Queri es.
The SQL stands for structured quer y language. It is a non procedural
language used to define, access and manipulate data. The meani ng of non -
procedural is that it describes the necessary components (i.e., t ables) and
desired results without dictating exactly how results should be computed.
To bring confor mit y among vendors , the American National Standards
Institute (ANSI) publ ished its first SQL standard in 1986 and a second
widel y adopted standard in1989. ANSI released updates in 1992, known as
SQL92 and SQL2, and again in 1999, ter med as both SQL99 and SQL3.
In SQL92, SQ L statements are grouped into three broad categor ies.
They are the Data Manipulation Language (DML), the Data Definition
Language (DDL), and the Data Control Language ( DCL) . The DML provides
specific data -manipul ation commands such as SELECT, INSERT, UPDAT E,
and DELETE. The DDL contains commands that handle the accessibility and
manipulation of database obj ects, including CREATE and DROP, while the
DCL contains the per mission -related commands GRANT and REVOKE.
The SELECT statement is used to retrieve data f rom a database. The
basic for m of an SQL query is
select [distinct ] sel ect -list f rom from-l ist w here qualification;
Where select, distinct, from and where are key words. Select -list is
list of column names separated by commas and from -list is table or list of
tables from which data is obtained. If from -list is list of tables, then the
result is cross product of both table’s contents. The Qualification in the
optional where clause is a Boolean combination of conditions. The optional
distinct key word is used to select unrepeated values.
We can also use an optional order by clause to display the contents in
sorting order .
Relational operators are <, <=, >, >=, <>, =
They are for less than, less than or equal to, greater than, great er than or
equal to, not equal to, equal to.

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 2

Logical operators are and, or and not.

Some rules about SQL statements are


• SQL statements are not case sensitive but values li ke scott, SCOTT
are different.
• SQL statements can be on one or more lines.
• Keywords cannot be abbreviated or split acr oss lines.
• Statement ends with a semicolon.

Procedure:
1. For getting SQL prompt
a. Click start
b. Click all programs
c. Click Oracle
d. Click Applicattion development
e. Click SQL plus
2. At Logon window enter the following data.
a. User name : syste m
b. Password : manager
c. Host string : oracle9
3. After getting SQL prompt t ype the following command to create a new
user user001 for dial y log in with 100mb of space.
create user user001
identif ied by password001
quota 100m on users;
4. Grant per missions to user using the following command.
grant connect,create session,resource to user001;
5. Now copy emp and dept tables from scott to user001 using the
folowing commands,
create table user001.dept as select * f rom scott.dept ;
create table user001.emp as select * f rom scott.emp;
6. Now use the following sequence to save the wor k and quit from SQL
prompt.
commit;
exit;
7. Again go to SQL prompt.

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 3

8. At Logon window enter the following data.


a. User name : user001
b. Password : password001
c. Host string : oracle9
9. Now t ype the foolowing commands start the wor k.
show user ;
set linesize 100;
10. Now start doing the queries and note down t he queries and results.
It may be noted that af ter executing ever y SQL command we have to
execute
select * from table;
and check manuall y that the result is the desired one or not.
Questions: -

1. Display the contents of the emp table.

Ans. (SQl quer y): Select * from emp;

2. Display the contents of the dept table.

3. Display all the employees’ names.

4. Display all the depart ment names.

5. Display all the employees’ names along with their designations.

6. Display the details of employees whose salar ies are greater than 2000.

7. Display the details of employee whose empno is 7788.

8. Display the desi gnation of employee whose empno is 7788.

9. Display the name, designation and salar y of employees whose salaries


are greater than 2000.

10. Display the name, designation and salar y of employees whose salaries
are less than 2000.

11. Display the name, designation and salar y of employees whose salaries
are between 2500 and 3000.

12. Display the name, designation and salar y of employees whose salaries
are less than 2500 and that of employees whose salaries are greater
than 3000.

13. Display the details of employee whose name is scott.

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 4

14. Display the details of employees whose designation is manager.

15. Display the names and designation of employees whose desi gnation is
manager and whose salary is greater than 2500.

16. Display the details of employees whose names start with letter s.

17. Display the details of employees whose names end with letter t.

18. Display the salaries of employees without repetitions.

19. Display names of empl oyees without any commission.

20. Display names of employees with some commission along with


commission.

21. Display names of employees and salaries if the salaries were


incremented by 200.

22. Display names and designation of employees after concatenating.

23. Display names of empl oyees in an alphabetical order.

24. Display empno of employees and salaries in order of salaries such


that employee with max salary is on top.

25. Display names o f employees and salaries in order of salaries such that
employee with max sal ary is at the bottom.

26. Display names of all employees with the heading as employee_name.

27. Display names of employees and j oining dates in the order of j oining
dates.

28. Display the de tails of salesman and manager whose salary is 1500 or
more.

29. Calculate and display salary of scott for one year.

30. Display location of depart ment number 20 .

31. Display depart ment number of scott .

32. Display location of the depart ment in which ‘scott’ is wor king.

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 5

Expno: 02 Date:
Creation of tables
Aim: -
To create, modif y and update tables and t o practice some aggregate
functions.
Theory:-
Create table: Tables are defined using the create command. The simplified
for m of create command is
create table r
( A1 D1, A2 D2,…, An Dn,
[ integrit y_constraint1 ],…,[ integrity_constr aintn])
| as select_statement;

Where create and tabl e are key words.


 create, table and as are keywords.
 r is the name of relation
 A1, A2, .. , An are attributes of the re lation separated by
domain t ypes D1,D2,…
 the way of mentioning integrit y constraints are
1. primary key(attribute).
It is a set of attributes that uniquely identifies a tuple in a
relation and selected by the DBA f or the pur pose.
2. f oreign key (Ar) ref erences r1.
or
3. constraint c1 f oreign key (Ar) ref erences r 1.
Here c1 is constraint name. Forei gn key is a combination of
attributes with values based on the pri mar y key values from
another table. The meaning of this referenti al integrit y here
is that for each tupple in the relation, the values of ‘ Ar’
must exist in the refer ring relation.
4. check(condition)
 The optional select statement can be used to create a table from
another reference table.
insert :Tables are constructed using the i nsert command. The simplified
for m of insert command is

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 6

insert into r
[(A1, A2, ..,An)] val ues(v1, v2, ..,vn)
| select statement ;

 insert, into and values are key words.


 r is the name of relation
 A1, A2, … ,An are attributes of the relation and v1,v2,.., vn
are the corresponding values. If the optional attribute list is
not gi ven, all the attri butes in the relation ar e assumed.
 The optional select statement can be used to insert values from
another table. But here it is to be ensured that both tables
possess compatible data types.
update: The attributes values are updated using the update command. The
simplified for m of update command is
update table_name | view_name
set A = v1
w here conditions;

 update, set and w here are key words


 A is attribute whose new value will be v1.
 The attribute values f or the all rows satisfying the conditions
are updated.
 If where condition is not gi ven, the attribute values for the all
rows are updated.
drop table: Table can be dropped using drop table. The syntax of the
command is
drop table [owner.] table_name;

 drop table is a key word.


Dropping a table in Oracle frees the space used by the table and
commits any pending changes to the dat abase. All indexes and grants
associated with the table are lost. Obj ects, such as views, stored procedures,
and synonyms built upon the table, are mar ke d invalid and cease to function.
Delete: Table contents can be deleted using delete command. The syntax of
delete command is

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 7

delete f rom [owner.] table_name [ w here clause];

 Delete, f rom & w here are key words


 The attribute values f or the all rows sati sfying the conditions
are deleted.
 If where condition is not gi ven, the attribute values for the all
rows are deleted.
Alter table: Table structure can be altered using alter table command. The
syntax of alter table command is
alter table [owner_name.] t able_name
add A D
| modif y A D
| drop column A ;

 alter table, add , modif y, drop, column are key words


 add , modif y, drop are used to append an attribute, to change
the data type of an exi sting attribute, and to delete an attribute
respectivel y.
 A is attribute and D is domain t ype.
Aggregate f unctions :
Aggregate functions are functions that take a collection of values as
input and return a single value. SQL offers fi ve built -in aggregate f unctions.
 MIN (A ) :returns mini mum of column values
 MAX ( A ) :returns maxi mum of column values
 AVG ( [ distinct ] A ) :returns average of uni que column values
 SUM ( [ distinct ] A ) :returns total of unique column values
 COUNT( [ distinct ] A):returns number of unique column values

The input to SUM and AVG must be a coll ection of numbers but the
other operators can operate on collection of non -numeric data types li ke
strings.
For example,
select sum(sal) f rom emp; displays total salaries of all the employees.
select count(com) f rom emp; displays no. of employees with
commission.
select count (*) f rom emp; displays no. of records in emp.

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 8

All the functions except COUNT (*) i gnore null values in their input
collection.
For SQL null value means unknown or inappl icable.
group by & having Clauses :
The select statement syntax including optional group by and Having
clauses is as under :
select [distinct ] select -list f rom from-list
[w here qualification ]
[group by gr oup -list ]
[having group -qualif ication];
The result of the GROUP BY clause is a grouped table i.e., a set of
groups of rows deri ved from the table by conceptually rearranging it into the
mi ni mum number o f groups such that within any one group all rows have the
same value for the combination of columns identified by GROUP BY clause.
Ex : select sum(sal) from emp group by j ob;
Using this statement we get total salar y for each desi gnation of the
employees.
There is a restriction on the select clause while using group by. Select
item in the select clause must be single valued per group as for the other
aggregate functions. T herefore a statement li ke
select empno, sum(sal ) f rom emp group by j ob;
select * f rom emp group by j ob; are invalid.
But we can gi ve
select j ob f rom emp group by j ob;
and
select j ob, avg(sal) f rom emp group by j ob;
are valid.
HAV ING clause wor ks ver y much like a where clause except that its
logic is related only to the result of group functions i.e., having clause is
used to eliminate groups where as where clause is used to elimi nate rows
from the whole table.
For example,
select deptno, avg(sal) from emp group by deptno having max(sal) > 1500;
Displays average salaries depart wi se for depart ments which have
average salary greater than 1500.

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 9

Procedure: -
1. Go to SQL prompt
a. Click start
b. Click all programs
c. Click Oracle
d. Click Application development
e. Click SQL plus
2. At Logon window enter the following data.
f. User name : user001
g. Password : password001
h. Host string : oracle9
3. Go to File menu, click spool and then spool file.
4. Gi ve the spool file name li ke atoz
5. Click save
6. Set the line si ze using the following command.
set linesize 100;
7. Create the tables with create table command.
8. Type the foll owing command after creation or modification of each
table to view the structure of the table.
desc table_name;
9. In insert statement we can use substitution variables like
insert into table1 val ues(&a, &b, &c);
10. Then it asks for the values of a, b, and c. I f we gi ve proper values, the
values are inserted int o the table.
11. For inserting more rows of data we can repeat the command by
typing ‘ /’.
12. In bet ween insertions and after all the data i s inserted, we can t ype the
following command to save the data.
commit;
13. To cancel the changes to the database up to t he last save point use
rollback;
14. After inserting all the data or after modificat ion to data, we can view
the data by t yping
Select * f rom table_name;
15. Use the following commands after all the task is co mpleted.
commit;
exit;

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 10

16. Open the spool file at oz with notepad and note down the contents in
the obser vation.

Questions: -
1. Create emp1 table and insert appropriate val ues.
2. Create dept1 table and insert appropriate val ues.
3. Create suppliers table with the following schema
suppliers(sid:integer,sname:string,address:st ring).
4. Create parts table with the following schema
parts( pid:integer, pname:string, color:string).
5. Create catalog table with the following schema
catalog( sid:integer , pid:integer , cost:real ).

6. Insert the following values into suppliers table

SID SNAME ADDRESS


1001 smith london
1002 j ones paris
1003 blake paris
1004 clark london
1005 adams Athens

7. Insert the following values into catalog tabl e

SID PID COST


1001 5001 10.5
1002 5003 50
1002 5005 550.99
1003 5004 49.55
1004 5006 600
1005 5002 200
1005 5005 545
1005 5006 605
1005 5001 10
1005 5003 49
1005 5004 50

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 11

8. Insert the following values into parts table

PID PNAME COLOR


5001 nut red
5002 bolt green
5003 screw blue
5004 screw red
5005 cam blue
5006 cog red

9. Increment the salaries of all employees by 500 except scott for whom
increment the salar y by 1000.
10. Add one row of your own choice and delete t hat row in parts table.
11. Alter the ename field of emp1 table to accommodate more charact ers.
12. Find the maxi mum sal ary.
13. Display maxi mum salary along with name of the employee who gets it.
14. Display total salar y.
15. Display total salar y for each depart ment .
16. Display the maxi mum salary of employees in each depart ment along
with the depart ment number
17. Count number of recor ds in the emp1 table.
18. Count number of empl oyees who get a commission.
19. Count the number of employees wh o get no commission.
20. Create a table dummy with the fields serial number, name and inser t 5
rows.
21. Delete all the rows in dummy table.
22. Delete the field “name” from dummy table.
23. Create table emp2 wit h same data as in emp.
24. Drop table dummy.

Note: the schema f or t ables emp1 and emp2 i s same as the emp.dept tables
of scott. So before creating these tables , we have to note down the schema
of emp and dept tables by the desc command.

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 12

Expno: 03 Date:
Set Operations
Aim:-
To Practice set operations, nested queries and j oins in SQL
Theory: -

A nested quer y is query that has another query embedded within it,
the embedded quer y is called sub quer y.

Example:

select dname from dept where deptno

= (select deptno from emp where ename=’scott’);

This query displays depart ment name of the employee whose name is
‘scott’. If a single query is used on emp tabl e then we can obtain deptno but
not dname. So we used the result of the sub query in the nested query.

There are some points to be remembered while using nested quer ies.
They are

 Use single -row oper ators with single -row sub queries and use
multiple -row operator s with multiple -row sub queries.

 In Single row sub query, operators used are <, >, <= , >=, <>

 In multiple row sub query, operators used are all, some and in. whose
meanings are ever y value returned by the sub query, at least one value
returned by the sub query , any value in the list respectivel y.

SQL supports the set operations union, intersection and minus with
the key words union, intersect, and except ( mi nus in oracle). It al so supports
exists and not exists. exists operator returns true if the set is not empt y and
not exists returns true if the set is empt y.

The UNION operator returns records from the result of both que ries
after eliminating the duplicate records whi ch are common in bot h. There is
another option of uni on, the UNION ALL operator, which returns records
from the result of both queries, including duplicate records which are
common in both. The INTERSECT oper ator returns the records which are
common in the result of both queries. The EXCEPT operator returns the
records which are in the result of the first query but not in the result of the
second one.

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 13

We can use the j oin capability in SQL to bring together dat a


that is stored in different tables by creating a link between them.

When data from more than one table in the database is required, a j oin
condition is used. Rows in one table can be j oined to rows in another table
according to common values existing in corresponding columns, that is,
usually pri mar y and f oreign key columns. A j oin with a j oin condition is
known as conditional j oin.
When a j oin condition is invalid or omitted completel y, the result is a
Cartesian product, in which all combinations of row s are displayed. All rows
in the first table are j oined to all rows in the second table.

Equi -Join is a special case of condition join where the condition


contains only equalities. A natural j oin is an Equi -Join on all common fields
of the related tables.

If there are any values in one table that do not have correspondi ng
values in the other, in an Equi -j oin that row will not be selected. Such rows
can be forcefull y selected by using outer j oin. The left outer j oin takes all
the rows in the left table (fi rst table in the j oin) and pads the rows which
don’t have a matching row with null values for all other attributes in the
right table. The right outer j oin takes all the rows in the right table( first
table in the j oin) and pads the rows which doesn’t have a matching row with
null values for all other attributes in the left table. The full outer j oin
includes all the rows from both tables and pads the rows which doesn’t have
a matching row with null values f or all other attributes in the other table.

In SQL there are four j oin types namel y i nner j oin, left outer join,
right outer j oin and full outer j oin. And there are three j oin conditions
natural, on <condition> , using (field1,field2,..).Here on <conditi on> is for
conditional j oin and using (field1,field2 ,..) is like natural j oin but the j oin
fields are fields specified in the using class.

Examples:

Cartesian product :

The following statement displays combinati ons of all records in dept


and emp tables.

select * f rom dept,emp;

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 14

conditional joins:

The following statement applies Cartesian product on dept and emp


tables and displays the records which satisfy the condition i.e. the details of
depart ment no 10 empl oyees’ details who doesn’t belong to the department.

select * f rom dept,emp w here dept.deptno<>emp.deptno and


dept.deptno=10;

Equi-join:

The following statement applies Cartesian product on dept and emp


tables and displays the records which satisfy the condition i.e. the details of
depart ments which have some employees along with employees’ detail s who
belong to the depart ment. The condition her e is equalit y condition. So, it is
also known as Equi -j oin.

select * f rom dept,emp w here dept.deptno=emp.deptno;

inner join:

An alternative way of using the above quer y is

select * f rom dept inner join emp on dept.deptno=emp.deptno;

lef t outer join:

The following statements display all the dept records which have the
matching emp records along with the matching emp records and i n addition
displays dept records which does not have any employees.

select * f rom dept left outer join emp on dept.deptno=emp.deptno;

OR

select * f rom dept, emp w here dept.deptno =emp.deptno(+);

right outer join:

The following statements display all the dept records which have t he
matching emp records along with the matching emp r ecords and i n addition
displays emp records which does not have any depart ment .

select * f rom dept right outer join emp on dept.deptno=emp.dept no;

OR

select * f rom dept, emp w here dept.deptno(+) =emp.deptno;

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 15

f ull outer join:

The following statements display all the dept records which have t he
matching emp records along with the matching emp records and i n addition
displays emp records which does not have any depart ment and dept records
which does not have any employees.

select * f rom dept f ull outer join emp on dept.deptno=emp.deptno;

OR

select * f rom dept, emp w here dept.deptno(+) =emp.deptno(+);

natural inner join:

The following statement inner j oins the two tables by equating all the
common fields i.e. in this case it is de ptno. So the result is same as the
above inner j oin but in the display the common column deptno is displayed
only once.

select * f rom dept natural inner join emp;

natural lef t outer join:

The following statement left outer j oins the two tables by equating all
the common fields i.e. in this case it is deptno. So the result is same as the
above left outer j oin but in the display the common column deptno is
displayed onl y once.

select * f rom dept natural lef t outer join emp;

natural right outer join:

The following statement left outer j oins the two tables by equating all
the common fields i.e. in this case it is deptno. So the result is same as the
above right outer j oin but in the display the common column deptno is
displayed onl y once.

select * f rom dept natural right outer join emp;

natural f ull outer join:

The following statement full outer j oins the two tables by equating all
the common fields i.e. in this case it is deptno. So the result is same as the
previous full outer j oin but in the display the comm on column deptno is
displayed onl y once

select * f rom dept natural f ull outer join emp;

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 16

Procedure: -
Same as that in expno.2
Questions: -
1. Create three tables wit h the following schema
Sailors(sid:integer, sname:string, rating:integer, age:real)
Boats(bid:integer, bname:string, color:string)
Reser ves(sid:integer, bid:integer, day:date)
Gi ve the appropriate integrit y constraints.
2. Insert the following values into the above tables.
sid sname rating age
22 Dustin 7 45.0
29 Brutus 1 33.0
31 Lubber 8 55.5
32 Andy 8 25.5
58 Rust y 10 35.0
64 Horatio 7 35.0
71 Zorba 10 16.0
74 Horatio 9 40
85 Art 3 25.5
95 Bob 3 63.5

bid bname color


101 Interlake blue
102 Interlake red
103 Clipper green
104 Marine red

sid bid day


22 101 10/10/98
22 102 10/10/98
22 103 10/8/98
22 104 10/7/98
31 102 11/10/98
31 103 11/6/98
31 104 11/12/98
64 101 9/5/98
64 102 9/8/98
74 103 9/8/98

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 17

3. Find the names of sail ors who have reser ved at least one boat.
4. Find the ids of sailors who reser ved a red boat and a green boat.
5. Find the ids of sailors who reser ved a red boat or a green boat.
6. Find the ids of sailors who reser ved a red boat but not a green boat.
7. Find the names of sail ors who reser ved ever y boat.
8. Find the names of sail ors who reser ved ever y red boat.
9. Find the ids of sailors whose rating is more t han the average rating of
all sailors.
10. Find the names of parts for which there is some supplier .
11. Find the ids of suppliers who suppl y a red part and a green part.
12. Find the ids of suppliers who suppl y a red part or a green part.
13. Find the ids of suppliers who suppl y a red part but not a green par t.
14. Find the names of suppliers who suppl y ever y part.
15. Find the names of suppliers who suppl y ever y red part .
16. Find the names of parts supplied by Adams and by no one else .
17. Find the ids of suppliers who char ge more for some part than the
average cost of that part.
18. For each part find the name of the supplier who char ges the most for
that part.
19. Find the ids of suppliers who suppl y onl y red parts .
20. Find the sids of sailors whose rating is better than some sailors called
horatio.
21. Find the sailors whose rating is better than ever y sailor called horatio.
22. Find the names of boats reserved by dustin and by no one else .

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 18

Expno: 04 Date:
Functions and Procedures
Aim: -
To create and execute functions and procedures.
Theory: -
PL/SQL stands for Procedural Language/Structured Query
Language.PL/SQL is the procedural extension to SQL with desi gn features
of programming languages. Data manipulation and quer y statements of SQL
are included within procedural units of code. PL/SQL Block Structure is as
follows.
<header>
IS | AS
Declaration section
BEGIN
Executable section
EXCEPTION (optional)
Exception section
END;

Section Description
Header Required for named blocks. Specifies the way the program is
called by other PL/SQL blocks. Anonymous blocks do not have
a header. They start with the DECLARE keyword if there is a
declaration section, or with the BEGIN keyword i f there are no
declarations.
Declaration It is optional. Declares variables, cursors, T YPEs, and local
programs that are used in the block's execution and exception
sections.
Execution Optional in package and TYPE specifications; contains
statements that are executed when the block is run.
Exception Optional; describes er ror -handling behavior for exceptions
raised in the executabl e section.

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 19

An example of an anonymous block:

The following code declares today as date data type and the default
value is system date which can be obtained f rom the environment variable
SYSDATE. Display the date after concatenat ing it with the string.
DECLARE
today DATE DEFAULT SYSDATE;
BEGIN
DBMS_ OUTPUT.PUT_LINE ( 'Today is ' || today);
END;

Syntax of the named blocks (procedures and f unctions):

CREATE [OR REPLACE] PROCEDURE [owner_name.]procedure_name


[(parameter1 [ IN | OUT | IN O UT] datat ype] [,...n)]]
{IS | AS} PL/SQL block ;

CREATE [OR REPLACE] FUNCTION [owner_name.]function_name


[(parameter1 [ IN | OUT | IN O UT] datat ype] [,...n)]]
RETURN datatype
{IS | AS} PL/SQL block;

In Oracle, user -defined functions and stored procedures are very


similar in composition and structure. The primar y difference is that stored
procedures cannot ret urn a value to the invoking process, while a function
may return a single value to the invoking process. In an Oracle stored
procedure, the specified ar guments and parameters include IN, OUT, or IN
OUT. The IN qualifier is provided when invoking the function and passes a
value in to the funct ion, while OUT ar guments pass a value back to the
invoking process. In other words, the IN qualifier is supplied by t he user or
process that calls the function, while the O UT argument is returned by the
function. IN OUT ar guments perfor m both IN and OUT functionality.
Example:
Procedure that comput es and displays tax to be paid if income is
passed as parameter

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 20

CREATE OR REPLACE PROCEDURE tax1(p_value IN NUMBER)


IS
BEGIN
DBMS_OUTPUT.PUT_LINE ( p_value * 0.08);
END;

Example:
Function that returns t ax to be paid if income is passed as paramet er
CREATE OR REPLACE FUNCTION tax2( p_value IN NUMBER)
RETURN NUMBER
IS
BEGIN
RETURN (p_value * 0.08);
END;

Control statements in P L/SQL


If Statement:
IF condition THEN
executable statement(s)
END IF;
If – else Statement
IF condition THEN
TRUE sequence_of_executable_statement( s)
ELSE
FALSE/NULL sequence_of_executable_statement(s)
END IF;
elsif Statement:
IF condition-1 THEN
statements-1
ELSIF condition- N THEN
statements -N
[ELSE
ELSE statements ]
END IF;

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 21

loop Statement:
LOOP
executable_statement(s)
END LOOP;
exit Statement:
EXIT [WHEN condition];
--
FOR loop_index IN [ REVERSE]
lowest_number..hi ghest_number
LOOP
executable_statement(s)
END LOOP;
The REVERSE keywor d causes PL/SQL to st art with the
highest_number and decrement down to the lowest_number
w hile Statement:
WHILE condition
LOOP
executable_statement(s)
END LOOP;
case Statement:
CASE selector
WHEN expression1 THEN result1
WHEN expression2 THEN result2
...
WHEN expressionN THEN resultN
[ELSE result N+1;]
END;
Data types:
• CHAR [(maximum_length)]
• VARCHAR2 ( maximum_length)
• NUMBER [(precision, scale )]
• DATE
• %TYPE Attribute
Declares a variable according to a database column definition or
previousl y declared variable

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 22

Example:
Procedure that displays name of an employee if his empno is gi ven. It uses
the %type.
CREATE OR REPLACE PROCEDURE pemp1(no emp.empno%type)
IS
empname emp.ename%type;
BEGIN
SELECT ename
INTO empname
FROM emp
WHERE empno = no;
DBMS_OUTPUT.PUT_LINE (empname);
END;
/
Cursors:
the syntax of cursor declaration is
DECLARE CURSOR cursor_name
IS select_statement
[FOR UPDATE [OF column_name [,...n]]}]
The DECLARE CURSOR command enables the retrieval and
manipulation of recor ds from a table one r ow at a ti me. This pr ovides row -
by-row processing, rat her than the traditional set processing offered by SQL.
To use this procedure properly, you should:
1. DECLARE the cursor
2. OPEN the cursor
3. FETCH rows from the cursor
4. When finished, CLOSE the cursor
The DECLARE CURSOR command wor ks by specif ying a SELECT
statement . Each row r eturned by the SELECT statement may be individuall y
retrieved and manipulated. In Or acle, var iables are not allowed in the
WHERE clause of the SELECT statement unless they are first declared as
variables. The parameters are not assi gned at the DECLARE. Instead, they
are assigned values at the OPEN command.
Example:
The following code cr ea tes procedure to display empno and ename of
all employees in emp t able using cursors.

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 23

CREATE OR REPLACE PROCEDURE pemp2


IS
CURSOR c IS
SELECT empno, ename
FROM emp;
no emp.empno %type;
name emp.ename %type;
BEGIN
OPEN c;
LOOP
FETCH c into no, name;
EXIT WHEN c%notfound;
DBMS_OUTPUT.PUT_LINE (TO_CHAR(no) ||’ -->’ || name);
END LOOP;
CLOSE c;
END;
/

Example:
The following code cr eates procedure to update salaries of
employees using cursors
CREATE OR REPLACE PROCEDURE p2
IS
CURSOR c1 IS
SELECT deptno,empno,ename,sal
FROM emp FOR UPDATE OF sal;
BEGIN
FOR emp_record I N c1
LOOP
IF emp_record.sal> 2000 THEN
UPDATE emp
SET sal=emp_recor d.sal* 1.10
WHERE CURRENT OF c1;
END IF;
END LOOP;
END;

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 24

Procedure: -
1. Go to SQL prompt
2. Execute the following commands.
set autocommit on;
set serveroutput on;
3. Type edit file1.sql (Then the default editor i.e. notepad is invoked.)
4. Type the procedure or function definition.
5. Save it and exit notepad.
6. Compile the procedure or fu nction by t yping the following command.
@file1
7. If there are any errors type the following command to show the errors.
Show errors;
8. Type the following command to edit the file and introduce the
corrections.
edit file1.sql
9. Save the file and exit the editor.
10. Compile the procedure by t yping the followi ng command again.
@file1
11. If there are any errors type the following command to show the errors.
show errors;
12. Continue the process of reediting and recompilation until the
procedure or function is successfully created.
13. After successful creation of procedure type t he following command to
execute the procedure.
exec procedurename(parameter);
example1 exec pemp1;
example2 exec tax1(1000);
14. If it is a function type the following command to execute the
function.
a. select tax2(1000) f rom dual;
Or
b. Execute Following sequence of statements for getting the value
returned by the functi on into bind variable and print it.
1. variable v1 number;
2. exec : v1:=tax2(1000) ;
3. print v1;

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 25

15. We can view the function names and pr ocedure names using the
command.
select obj ect_name, obj ect_type
f rom user_obj ects
w here obj ect_type in ( ‘PROCEDURE’,’FUNCT ION’)
order by obj ect_name;
16. We can view the funct ion or procedure body using the command.
select text
f rom user_source
w here name =’TAX1’ ;
17. Exit SQL after saving the wor k.
commit;
exit;

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 26

Expno: 05 Date:
Triggers
Aim:-
The aim of the experiment is to create views and triggers and to study
the behavior of views and triggers.
Theory:-
A trigger is a special kind of stored procedure that fires automatically
(hence, the term trigger) when a data -modification statement is executed.
Triggers are associ ated with a specific data -modification statement
( INSERT, UPDATE, or DELETE) on a specific table.
Syntax and Descripti on:

CREATE [OR REPLACE] TRIGGER tri gger_name


{BEFORE | AFTER | INSTEAD OF}
{[DELETE] [OR] [INSERT] [OR] [UPDATE [OF column [,...n] ] ] ON
{table_name | view_name}
[FOR EACH { ROW | STATEMENT }]
[WHEN (conditions)]
code block

Triggers, by default, f ire once at the statement level. That is, a single
INSERT statement mi ght insert 500 rows i nto a table, but an insert trigger
on that table fires only one ti me. Some vendors allow a trigger to fire for
each row of the data -modification operation. So, a statement that i nserts 500
rows into a table that has a row -level insert trigger fires 500
In addition to being associated with a specific data -modification
statement ( INSERT, UPDATE, or DELETE) on a gi ven table, triggers are
associated with a specific time of firing. In general, trig gers can fire
BEFORE the data -modification statement is processed, AFTER it is
processed, or (when supported by the vendor) INSTEAD OF processing the
statement .
Triggers that fire before or instead of the data -modification statement
do not see the changes that the statement renders, while those that fire
afterwards can see and act upon the changes that the data -modification
statement renders. It may be noted that Oracle allows INSTEAD OF tri ggers
to process onl y against views, not /tables.

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 27

Examples:
The first trigger is invoked whenever there is an update operation on
the emp table rows and if salar y is changed. It records these changes in
another table to know the changes made to the table. The second trigger is
invoked whenever there is an insert, delete o r update operation on the emp1
table rows and the changes are recorded in the empl and empl1 tables.
CREATE OR REPLACE TRIGGER EMPT 1
BEFORE UPDATE ON EMP
FOR EACH ROW
WHEN ( NEW.SAL <> OLD.SAL)
BEGIN
INSERT INTO EMPLOG VALUES ( 'UPDATED', :OLD.EMP NO,
:OLD.SAL, :NEW.EMPNO ,: NEW.SAL);
END;

CREATE OR REPLACE TRIGGER EMPT2


AFTER DELETE OR UPDATE O R INSERT ON EMP1
FOR EACH ROW
BEGIN
IF DELET ING THEN
INSERT INTO EMPL VALUES ( 'DELETED', :OLD.EMP NO, : OLD.SAL);
ELSIF INSERT ING THEN
INSERT INTO EMPL VALUES ( 'ISERTED',:NEW.EMPN O,: NEW.SAL);
ELSE
INSERT INTO EMPL1 VALUES
( 'UPDATED',:OLD.EMPN O,: OLD.SAL,: NEW.EMPN O,:NEW.SAL);
END IF;
END;

View s:
A view is a table whose rows are not explicitly stored in the
database, but are computed as needed from the view definition.
The syntax of creating a view is

CREATE [OR REPLACE] VIEW view_name

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 28

[(column [,...n])]
AS
SELECT_statement
[WITH CHECK OPTION]

Example:
This command creates a view for dbms teacher to view student name
and mar ks in dbms. But the original table contains sno, sname and all
subj ect mar ks.
CREATE VIEW dbms (name, dbmar ks)
AS SELECT sname,s1
FROM Students;

The syntax of deleting view is


DROP VIEW view_name;
.
In SQL view is said to be updatable (i.e. insert, update or
delete) if the following conditions are all satisfied.
 The from clause has only one relation.
 The select clause contains only attributes of the relation and does not
have any expressions, aggregate functions, or distinct specification.
 Any attribute not in the select clause can be set to null.
Another point we can note is that if we insert a row which does
not satisfy condition in the where clause of create view then it is allowed
and that row doesn't appear in the view. To avoid such insertions we have to
use with check option in the create view.

Sequence:

The following command creates a sequence.


CREATE SEQUENCE sample_sequence
START WITH 0
MAXVALUE 20
INCREMENT BY 5;

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 29

A sequence has two at tributes, NEXTVAL and CURRVAL.

Sequence Attribute Description


sequence_name.NEXTVAL This evaluates to the next highest value.
sequence_name.CURRVAL This evaluates to the value that was returned
from the most recent NEXTVAL call.

Questions: -

1) Create a sequence ‘seq1’ which creates the sequence roll numbers of your
class students.

2) Using the above sequence insert values in the dbms table which has the
fields sno, name, smar ks (at least ten records).

3) Create a trigger on ‘dbms’ table whenever there is an insertion of a row.


If the mar ks are <0 insert 0 and insert 100 when mar ks is >100.

4) Create a tri gger which inserts the changes made into a dbms_change table
on dbms table before t here is a deletion or modification of a row.

5) Create a tri gger on account table which is i nvoked whenever an account


is created or an amount is withdrawn such that the balance should be
always greater than or equal to 500.

6) Create a trigger on account table which is invoked after an amount is


deposited to display the amount of balance in the account with account
number.

7) Create a view for a subj ect teacher (name,s1) from student table which
has the fields roll number, name, all subj ect mar ks i.e.s1,s2.. students.
Try to insert a row in to the view.

8) Create a view for head of dept table which contains roll number and all
subj ects’ mar ks of students from student t able. Insert a row in to the
view.

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 30

Exp no:6 Date:


Creation of Database in MS-Access

Aim: - To familiarize with MS Access, open an existing database and create


new data base .
Theory: -
MS Access is a relational database that facilit ates the storage and
retrieval of structured infor mation. Access databases are, ideall y, a set of
tables that are related in one way or another . Along with tables,
Access allows us to cr eate:
•Quer y - or gani zing or collecting a particular set of data
•For m - interfaces that allow you to maintain or edit records/data
•Report - printable results
•Macros - extended functionality for the database, an advanced function
All of these obj ects are stored in a single fil e with “.mdb” file ext ension.
Procedure: -
PartI Opening an Existing database :
1) Click on the Windows Start button, select Al l Programs, and then
click Microsoft Access .
2) Click on the FILE menu, then open and select the .mdb file to be
opened and then click open.Then the followi ng screen appears.

Title bar Tool bar Menu bar

Database
window

Object bar Objects wizards


(tables)

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 31

3) Double click the table to open the table.


4) The table contents are displayed as shown below.
5) Then we navi gate to the required record using the record navi gation
buttons.
6) To add a record of dat a move to the first empty recor d and t ype in the
data values and press TAB to move to the next field.
7) To save a record of data move to the first empt y field below t hese
records. We do not r equire to do anything else to save your data.
When we leave a record, either by moving to another record or by
closing a table, Microsoft access automatically saves the data.
8) Edit a record afte r moving to the required record and use TAB and
SHIFT + TAB to move to next field and previous field.
9) Go to FILE menu and click exit to exit from Access.
Data Sheet View

Column heading or field name

Row or a record of data

Record navigation buttons Column or field

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 32

PartII Creating a new database:


1) Click on the Windows Start button, select Al l Programs, and then
click Microsof t Access .
2) Click on the FILE menu, then new .
3) Click blank database option.
4) Name and save the dat abase.
5) Create table by double -clicking the create table in design view
option. Then the following window appears.
6) Enter the field names and data t ypes.
7) Enter the field width i n the field propert y window.
8) Right click the field w hich uniquel y identifies a record in the table
and click pri mar y key option.
9) Set the other properties like
a) Required yes or no depending on whether the field value can be
set to null or not null.
b) Validation rule like <=100 for ensuring value in the mar ks f ield to
be not greater than 100.
10) Now save it with a new table name for example table1.
11) Close the desi gn view and double click the table1 obj ect to enter the
data.
12) After editing is completed close the data sheet view and exit from MS
Access.
Note: -we can also create table using create table by wi zard or creat e table
by entering data.
Design view of table

Data types
Field names
Field properties,
like field size

Design view of the table

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 33

Data Type Property of a table f ield

You can use the Data Type propert y to speci fy the t ype of data stored
in a table field. Each field can store data consisting of onl y a singl e data
type.

The Data Type proper ty uses the following settings.

Setting Type of data Size


Text (Default) Text or combinations of Up to 255 characters or
text and numbers, as well as the length set by the
numbers that don't require Field Size property,
calculations, such as phone whichever is less.
numbers. Microsoft Access does
not reserve space for
unused portions of a t ext
field.
Memo Len gthy text or combinations of Up to 65,535 characters.
text and numbers. ( If the Memo field is
manipulated through
DAO and onl y text and
numbers [not binary
data] will be stored in it,
then the size of the
Memo field is limited by
the size of the database.)
Number Numeric data used in 1, 2, 4, or 8 bytes ( 16
mathematical calculati ons bytes if the Field Size
property is set to
Replication ID).
Date/Time Date and ti me values f or the years 8 bytes.
100 through 9999.
Currency Currency values and numeric data 8 bytes.
used in mathematical calculations
invol ving data with one to four
deci mal places. Accurate to 15
digits on the left side of the

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 34

deci mal separator and to 4 digits


on the ri ght side.
AutoNumber A unique sequential ( incremented 4 bytes (16 bytes if the
by 1) number or random number FieldSize propert y is se t
assigned by Microsoft Access to Replication ID).
whenever a new recor d is added to
a table. AutoNumber fields can't
be updated. For more infor mation,
see the New Values propert y
topic.
Yes/No Yes and No values and fields that 1 bit.
contain onl y one of two values
(Yes/No, True/False, or On/Off).
OLE Obj ect An obj ect (such as a Microsoft Up to 1 gigabyte
Excel spreadsheet, a Microsoft (limited by available
Word document , graphics, sounds, disk space)
or other binary data) linked to or
embedded in a Microsoft Access
table.
Hyperlink Text or combinations of text and Each part of the three
numbers stored as text and used parts of a Hyperlink data
as a hyperlink address. A type can contain up to
hyperlink address can have up to 2048 characters.
three parts: text to display — the
text that appears in a field or
control.
address — the path to a file (UNC
path) or page ( URL) .

subaddress — a location within


the file or page.

screentip — the text displayed as


a tooltip.

The easiest way to insert a


hyperlink address in a field or

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 35

control is to click Hyperlink on


the Insert menu.
Lookup Creates a field that allows you to The same size as the
Wizard choose a value from another table primar y key field used
or from a list of values by using a to perform the lookup,
list box or combo box. Clicking typicall y 4 bytes.
this option starts the Lookup
Wizard, which creates a Lookup
field. After you complete the
wizard, Microsoft Access sets the
data type based on the values
selected in the wi zard.

Questions: -
1. Create a table student with roll number, name, father name as fields
with appropriate data t ypes.
2. Create a table mar ks with roll number and marks in different subj ects
as fields with appropri ate data types.
3. Add address field to st udent table, increase t he size allocated to one
of the fields.
4. Enter the appropriate data in the tables.

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 36

Exp no:7 Date:


Creation of Forms & Reports in MS -Access
Aim: - To create for ms, reports, queries and macros in MS -Access.
Theory: - The for m is a for matted display where data is entered, displayed
and edited. It provides greater flexibility than a table. A report is a like a
query but is for matted for pr inting. As the data is entered data into a form
simultaneousl y data is adding to the table. In many cases the tables can
become quite lar ge and difficult to read, especially when we only want
infor mation from indi vidual records. An easier way to view the infor mation
in a table is to use a form which is easily created in Access. Microsoft
Access di vides a for m into five sections in the Desi gn view.
 The f orm header prints at the top of the first page .
 When we are viewing data, the for m header appears once at the top of
the window.
 The page header print s at the top of ever y page .
 The page header onl y appears when printed or in print preview.
 The detail section contains the fields from t he table. When we are
viewing data, the detai l section is repeated f or each record. When we
print the for m, the det ail section shows as many records as will fit on
a page.
 The page f ooter prints at the bottom of ever y page .
 The page footer onl y appears when printed or in print preview.
 The f orm f ooter prints at the bottom of ever y page .
 When we are viewing data, the footer appear s once at the bottom of
the window.
Design view of Form:

Tool Box

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 37

We can use a report to present data in print. With a report, we have


greater flexibility to present summar y infor mation than with a for m. For
instance, we can include totals across an ent ire set of records in a report.

Tool Box: -
The tool box is special kind of tool bar. Control is a graphical user
interface obj ect, such as a text box, check box, scroll bar, or command
button, that lets users control the program. We us e controls to display data
or choices, perform an action, or make the user interface easier to read Open
a for m, report, or data access page in Desi gn view. Toolbox is a set of tools
that are available in Desi gn view to add controls to a form, report, or data
access page. To create a control using the tool box click the tool for the
control we want to create and then drag i t and drop it.

Text boxes
We use text boxes on a form, report, or data access to display data
from a record source . This type of text box is called a bound text box
because it 's bound to data in a field. Text boxes can also be unbound. For
example, we can create an unbound text box to display the results of a
calculation or to accept input from a user. Data in an unbound text box isn't
stored anywhere.
Labels
We use labels on a form, report, to display descriptive text such as
titles, captions, or bri ef in structions.
List boxes
The list in a list box consists of rows of data. In a for m, a list box can
have one or more columns, which can appear with or without headings. If a
multiple -column list box is bound .Bound control is a control used on a
for m, report, or data access page to enter or display the contents of a field in
the underlying table, query, or SQL statement. The control's Cont rol Source
property stores the field name to which the control is bound. Access stores
the values from one of the co lumns. In a dat a access page, a list box has one
column without a heading.
Combo boxes
A combo box is li ke a text box and a list box combined, so it requir es
less room. We can t ype new values in it, as well as select values f rom a list.

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 38

Command button s
Command buttons provide us with a way of perfor ming action(s) by
simpl y clicking them. When we choose the button, it not onl y carri es out the
appropriate action, it also looks as if it's being pushed in and released. We
use a command button on a form to start an action or a set of actions. For
example, we can creat e a command button t hat opens another for m. To make
a command button do something on a for m, we write an event procedure and
attach it to the button's On Click propert y.
Check boxes
We can use a check box on a for m, repor t, or as a stand -alone to
display a Yes/ No value from an underl ying t able, quer y, or SQL st atement.
Option buttons
We can use an option button on a form, report, or data access page as
a stand -alone control to display a Yes/ No value from an underl ying record
source. We can also use option buttons in an option group to display values
to choose from.
The option group is t he frame that surrounds the controls inside it.
Onl y one option in an option group can be selected at a time. I f an option
group is bound to a field, only the group frame itself is bound not the check
boxes, toggle buttons, or option buttons inside the frame. Because the
Control Source property of the group frame is set to the field that the option
group is bound t o, we don't set the Control Source propert y for each in the
option group. Instead, we set the Option Val ue (for m or report) or the Value
(data access page) pr operty of each check box, toggle button, or option
button. In a for m or report, set the contr ol pr opert y to a number that 's
meaningful for the field the group frame is bound to. In a data access page,
set the control propert y to either a number or any text that 's meani ngful for
the field the group frame is bound to. When we select an option in an optio n
group, Access sets the value of the field to which the option group is bound
to the value of the sel ected option's Option Value or Value property.
Toggle buttons
We can use a toggle button on a for m as a stand -alone to display a
Yes/No value from an unde rlying record sour ce .

Tabbed pages on f orms


We can use a tab control to present several pages of infor mation as a
single set. This is especially useful when we're wor king with many controls

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 39

that can be sorted into two or more categori es. For example, we m ight use a
tab control on an Employees for m to separate employment hi story and
personal infor mation. Infor mation about employment histor y is di splayed on
this page. Personal infor mation, such as home address and phone number, is
displayed on this page.
Procedure:-
PartI Creation of f orms:
1) Click on Forms in the Obj ects column and select either the wi zard or
design view
2) The wizard asks which table the form is to come from, and then which
fields you want. Gi ve the table name and select the fields and move to
the selected field list by clicking ri ght arrow button.
3) Select a layout, st yle, and a title to compl ete your for m. This t hen
opens in for m view for you to begi n entering or viewing infor mation.
4) Change to desi gn view to customi ze.
PartII Creation of reports :
1. Click Report in the Obj ect column and select the wizard or design
view. The wi zard asks which table or quer y you want to print.
2. Gi ve the table name and then select the fiel ds to print.
3. Select grouping levels Grouping brings entries together in the same
categor y, say all people living in Dallas.
4. Select fields to sort and whether to sort ascending or descending
order. Up to four fields can be sorted.
5. Then select the layout i.e. columnar, tabular, or j ustified.
6. Finally, select a st yle and a title.
7. The report open s in pr int preview.
8. Switch to desi gn view to change the for matting.
DESIGN VIEW OF A REPORT
When we print the report, sections are repeated, as appr opriate, until
all the data in the report is printed. The controls in each section tell
Microsoft Access what data to print in the section. The Report Header prints
at the beginning of the report. The Page Header and Footer prints on ever y
page. The Categor y Header and Footer prints for each category. The Details
section prints for each record in the category Controls that we can use to
display, enter, filter, or organize data in Access.

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 40

Questions: -
1. Create a for m for entering the data into student table which is already
created in the expno.7.
2. Create a for m for each subj ect teacher to enter mar ks in the
concerned subj ect.
3. Create a report to head of the depart ment to view all subj ect mar ks of
the students.
4. Create a report displaying roll list (roll number and name of the
students) from student table.

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 41

Exp no:8 Date:


Importing Tables

Aim: - To create queries, macros and i mport a wor k sheet and a table in
oracle to MS Access.
Theory:-Questions including data stored in a Database are called queries.
By using queries it is possible to:

 Extract the records that satisfy the search cr iteria into a record set
 Select which fields ar e to be displayed

 Perfor m more complicated searches using logical operators


 Carry out searches on more than one table li nked together
 Produce summar y statistics
 Calculate new values based on existing fields.
In Microsoft Access, i t is easy to automate t asks li ke changing values
in one field when the value in another changes or printing reports by
creating macros or wr iting Visual Basic procedures. A macro aut omat ically
carries out a task or a series of tasks for us. Each task that we want
Microsoft Access to perform is called an action. Microsoft Access provides
a list of actions for us to select from to create a macro. When we run the
macro, Microsoft Access carr ies out the actions in the sequence they are
listed, using the obj ects or data we have specified.

Procedure:-

Part I Creation of query:


1. Open Microsoft Access
2. Click on the Open Fi le button located at t he top left of the Access
application.
3. Select the file to be opened, then click Open
4. Click on the Queries obj ect option that is located on the left side of
the Access
5. Click on the Queries obj ect option that is located on the left side of
the Access database window, and then doubl e click the Create query
in Design view option.
6. Select a table, hi ghli ght the table name and then click the “Add”
button.
7. Then go to view and click SQL view.

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 42

8. Type an SQL quer y, click save and gi ve query name close select
query window.
9. Double click the newl y created quer y to see the r esult.
10. In stead of going to SQL view we can as well add the fields of a table
to SQL desi gn view and can enter the criteria.
11. We attach the query t o any push button in the forms to display the
result whenever the button is pressed or we can as well create a report
for the quer y

Part II Creation of Macro:


1. Click reports option in the database window and click new.
2. Select an Action for example Run SQL.
3. Write SQL statement, for example Create table t1(attribute1 number);
4. Click save and gi ve name of the macro.
5. Now double click the newl y created macro to execute it so that the
new table created.

Part II Import EXEL w orksheet:


1. Open Microsoft Excel.
2. In sheet1 t ype RollNumber in the first cell and Name in the second
cell of first row.
3. Type the roll numbers of studen ts and names of your class mates in
the first two columns of consequent rows.
4. Save the wor k book with the name as Pinlist.
5. Close Microsoft Excel .
6. Open Microsoft Access.
7. Open a new database.
8. Click get external data in f ile menu and then click import.
9. Select the work sheet which is already created after selecting file type
as MS excel and click import. Then the following window appears.

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 43

10. Select wor k sheet sheet1 and click next.


11. Then the following wi ndow appears.

12. Check the option First row contains columns to make the first column
of wor k sheet as column names of the converted table.
13. And then select new table in the next displayed window.
14. Click next and next and choose my ow n primary key and select roll
number.
15. Click next and gi ve the table name and click finish.
16. Double click the newl y created table to check whether the conversion
is completed.

Part IV Import an Oracle table:


1. Open Microsoft Access and open a new database.
2. Click get external data in f ile menu and then click import.
3. Select file type as ODBC databases.
4. Click Machine database source tab and then click new.
5. Select User data source in the next windo w and click next.
6. Select Microsof t odbc drivers f or oracle and Click finish.
7. Gi ve any new name f or data source name like ds1 and description as
ds1.
8. User name as scott and server as oracle9.
9. Click ok and then it asks for password. Gi ve the password as ti ger and
the click ok.

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 44

10. After few minutes all the tables of scott are displayed. Then select
one or more tables and click ok to i mport the tables to Access.

Questions::
1. Create a quer y to displ ay total mar ks of each student and execute it
2. Create a quer y to displ ay average mar ks in each subj ect. and execut e
it
3. Create a macro to run an SQL statement.
4. Import an Excel wor k sheet into MS access as a table.
5. Import dept and emp t ables from oracle.

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 45

Exp no: 9 Date:


MINI PROJECT

Aim: To develop a database application using DBMS concepts


Procedure:
1. Requirements Analysis:- This step includes obtaining the problem statement from
user requirements
2. Conceptual Database Design:- This step includes the following tasks
a. Identifying entities by noun phrase approach
b. Indentifying attributes
c. Identifying relationships
d. Drawing ER Diagrams
e. Refining ER diagrams
3. Logical Database Design:- This step includes mapping of ER diagrams to tables
4. Schema Refinement:- This step includes normalization
5. Creation Of Tables:- This step includes creation of tables in Oracle
6. Insertion Of Data:- This step includes insertion of proper data for the project.
7. Prepare SQL quires that are necessary for different users of the mini project.
8. Create triggers, procedures and functions for the mini project.

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 46

Exp no: 10 Date:


MySQL

Aim: To practice simple MySQL commands for retrieving data.


Description:
MySQL is pri marily an RDBMS and ships with no GUI tools to
administer MySQL dat abases or manage data contained within the databases.
Users may use the incl uded command line tools,
MySQL uses all the standard ANSI SQL numeric data types, so if
you're coming to MySQL from a different database system, these definitions
will look familiar to you. The followin g list shows the common numeric data
types and their descriptions.
Features:
Numeric Data Types:
 INT - A normal-sized integer that can be signed or unsigned. If signed, the allowable
range is from -2147483648 to 2147483647. If unsigned, the allowable range is from 0
to 4294967295. You can specify a width of up to 11 digits.
 TINYINT - A very small integer that can be signed or unsigned. If signed, the
allowable range is from -128 to 127. If unsigned, the allowable range is from 0 to
255. You can specify a width of up to 4 digits.
 SMALLINT - A small integer that can be signed or unsigned. If signed, the allowable
range is from -32768 to 32767. If unsigned, the allowable range is from 0 to 65535.
You can specify a width of up to 5 digits.
 MEDIUMINT - A medium-sized integer that can be signed or unsigned. If signed, the
allowable range is from -8388608 to 8388607. If unsigned, the allowable range is
from 0 to 16777215. You can specify a width of up to 9 digits.
 BIGINT - A large integer that can be signed or unsigned. If signed, the allowable
range is from -9223372036854775808 to 9223372036854775807. If unsigned, the
allowable range is from 0 to 18446744073709551615. You can specify a width of up
to 11 digits.
 FLOAT(M,D) - A floating-point number that cannot be unsigned. You can define the
display length (M) and the number of decimals (D). This is not required and will
default to 10,2, where 2 is the number of decimals and 10 is the total number of digits
(including decimals). Decimal precision can go to 24 places for a FLOAT.
 DOUBLE(M,D) - A double precision floating-point number that cannot be unsigned.
You can define the display length (M) and the number of decimals (D). This is not

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 47

required and will default to 16,4, where 4 is the number of decimals. Decimal
precision can go to 53 places for a DOUBLE. REAL is a synonym for DOUBLE.
 DECIMAL(M,D) - An unpacked floating-point number that cannot be unsigned. In
unpacked decimals, each decimal corresponds to one byte. Defining the display
length (M) and the number of decimals (D) is required. NUMERIC is a synonym for
DECIMAL.
Date and Time Types:
 DATE - A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31. For
example, December 30th, 1973 would be stored as 1973-12-30.
 DATETIME - A date and time combination in YYYY-MM-DD HH:MM:SS format,
between 1000-01-01 00:00:00 and 9999-12-31 23:59:59. For example, 3:30 in the
afternoon on December 30th, 1973 would be stored as 1973-12-30 15:30:00.
 TIMESTAMP - A timestamp between midnight, January 1, 1970 and sometime in
2037. This looks like the previous DATETIME format, only without the hyphens
between numbers; 3:30 in the afternoon on December 30th, 1973 would be stored as
19731230153000 ( YYYYMMDDHHMMSS ).
 TIME - Stores the time in HH:MM:SS format.
 YEAR(M) - Stores a year in 2-digit or 4-digit format. If the length is specified as 2
(for example YEAR(2)), YEAR can be 1970 to 2069 (70 to 69). If the length is
specified as 4, YEAR can be 1901 to 2155. The default length is 4.
String Types:
Although numeric and date types are fun, most data you'll store will be in string format.
This list describes the common string datatypes in MySQL.
 CHAR(M)- A fixed-length string between 1 and 255 characters in length (for
example CHAR(5)), right-padded with spaces to the specified length when stored.
Defining a length is not required, but the default is 1.
 VARCHAR(M) - A variable-length string between 1 and 255 characters in length; for
example VARCHAR(25). You must define a length when creating a VARCHAR
field.
 BLOB or TEXT - A field with a maximum length of 65535 characters. BLOBs are
"Binary Large Objects" and are used to store large amounts of binary data, such as
images or other types of files. Fields defined as TEXT also hold large amounts of
data; the difference between the two is that sorts and comparisons on stored data are
case sensitive on BLOBs and are not case sensitive in TEXT fields. You do not
specify a length with BLOB or TEXT.

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 48

 TINYBLOB or TINYTEXT - A BLOB or TEXT column with a maximum length of


255 characters. You do not specify a length with TINYBLOB or TINYTEXT.
 MEDIUMBLOB or MEDIUMTEXT - A BLOB or TEXT column with a maximum
length of 16777215 characters. You do not specify a length with MEDIUMBLOB or
MEDIUMTEXT.
 LONGBLOB or LONGTEXT - A BLOB or TEXT column with a maximum length
of 4294967295 characters. You do not specify a length with LONGBLOB or
LONGTEXT.
ENUM - An enumerat ion, which is a fancy term f or list. When defining an
ENUM, you are creating a list of items from which the value must be
selected (or it can be NULL). For example, if you wanted your field to
contain "A" or "B" or "C", you would define your ENUM as ENUM ('A', 'B',
'C') and onl y those val ues (or NULL) could ever populate that field.

SYNTAX FOR PROCEDURE AND FUNCTION MySQL


CREATE
[DEFINER = { user | CURRENT_USER }]
PROCEDURE sp_name ([proc_parameter[,...]])
[characteristic ...] routine_body

CREATE
[DEFINER = { user | CURRENT_USER }]
FUNCTION sp_name ([func_parameter[,...]])
RETURNS type
[characteristic ...] routine_body
func_parameter:
param_name type
type:
Any valid MySQL data type
Characteristic:
COMMENT 'string'
| LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 49

routine_body:
Valid SQL routine statement

PARAMETERS OF PROCEDURE
The real benefit of a stored procedure is of course when you can pass
values to it, as well as receive values back. The concept of parameters
should be familiar to anyone who has had experience with any procedural
programmi ng experience.
There are three types of parameter:
 IN: The default. This parameter is passed to the procedure, and can
change inside the pr ocedure, but remains unchanged outside.
 OUT: No value is supplied to the pr ocedure (it is assumed to be
NULL), but it can be modified inside the procedure, and is available
outside the procedure.
 INOUT: The characteristics of both IN and OUT parameters. A value
can be passed to the procedure, modified there as well as passed bac k
again.

Example of database creation in MySQL:


Creating a new user and gi ving all pri vileges to that user to access database.
C:\xampp \mysql>cd bin
C:\xampp \mysql \bin>mysql –u root
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL conn ecti on id is 1
Server version:5.1.41 Source distribution
Type ‘help;’ or ‘ \h’ fr o help. T ype ‘ \c’ to cl ear the current input statement
mysql>show databases;
The contents of the databases will be displayed on the screen as fol lows:
Database
infor mation_schema
cdcol
mysql
phpmyadmin
test
5 rows in set (0.03 sec)

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 50

Mysql>use mysql;
Database changed
mysql>show tables;
Tables in mysql
columns_pri v
db
event
tables_priv
time_zone
time_zone_leap_second
time_zone_name
time_zone_tranition
time_zone_transition_type
user
23 rows in set(0.05 sec)

To create a user in mysql :


mysql>insert into user (host,user,passwor k,select_priv)
values(‘’,’raj u’,password(‘raj u’),’Y’);
Quer y OK, 1 row affected, 3 war nings(0.01 sec)
mysql>select user,password from user ;
user password
root
pma
raj u *B8AEE0A5B33E3547A7D9D016522A18DFCAC6E2AC
3 rows in set (0.00 sec)

mysql>flush pri vileges;


Quer y OK, 0 rows affected(0.00 sec)

Mysql>create database db;


Quer y OK, 1 row affected (0.00 sec)

mysql>show databases;
Database
infor mation_schema
cdcol

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 51

mysql
phpmyadmin
test
db
6 rows in set (0.00 sec)

mysql>grant usage on db.* to raj u@localhost identified by ‘raj u’;


Quer y OK, 0 rows affected (0.00 sec)

mysql>grant all on sam.* to raj u@localhost;


Quer y OK,0 rows affected (0.00 sec)

C:\xampp \mysql \bin>mysql –u raj u –p


Enter password:****
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connecti on id is 2
Server version:5.1.41 Source distribution
Type ‘help;’ or ‘ \h’ for help. Type ‘ \c’ to clear the current inpu t st atement.
mysql>show databases;
Database
infor mation_schema
db
2 rows in set (0.00 sec)

Example of CREATION AND USING PROCEDURES AND FUNCTIONS in MySQL:


I. Creating a procedure.
mysql>CREATE PROCEDURE sp_in(p VARCHAR(10)) SET @x=P;
Quer y OK, 0 rows affec ted (0.00 sec)

mysql>CALL sp_in(‘CSE_BTECH’)
Quer y OK, 0 rows affected (0.00 sec)

mysql>SELECT @X;
@X
CSE_BTECH
1 row in set (0.00 sec)

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 52

An OUT using example


mysql>CREATE PROCEDURE sp_out(OUT p VARCHAR(10)) SET
p=’5th sem’;
Quer y OK, o rows affected (0.00 sec)

mysql>CALL sp_out( @X);


Quer y OK, 0 rows affected(0.00 sec)

mMysql>select @X;
@X
5th sem
1 row in set (0.00 sec)
(or)
mysql>SET @X=’5th sem’;
Quer y OK, 0 rows affected (0.00 sec)

Mysql>select @X;
@X
5th sem
1 row in set (0.00 sec)

II. Creating a Function


mysql>CREATE FUNCT ION hello (s CHAR(20))
RETURNS CHAR(50) DETERMINIST IC
RETURN CONCAT(s);
Quer y OK, 0 rows affected (0.00 sec)

mysql>SELECT HELLO(‘CSE”);
HELLO(‘CST’)
CST
1 row in set (0.00 sec)

C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 53

Practice Questions:

I. Practice the questions in Experi ment No.1 SQL queries in the MYSQL
environment.
II. Practice the questions in Experi ment No. 2 f or creation of tables,
modification of table structure and inserting values into the tables i n
the MYSQL environment also.
III. Practice the questions in Experi ment No 3 for practicing SQL set
operations, j oins and nested queries in the MYSQL environment also.

C.S.E.DEPARTMENT, S.R.K.R.E.C.

You might also like