MCSL-045 Lab Manual
MCSL-045 Lab Manual
UNIX Lab
Session 1 :
Ex 1: Explore all the UNIX commands given in this manual.
Ans:
1>
Files
Ex 2: Create a directory.
Ans: To create a directory, use the mkdir command.
For example : mkdir Student
Ex 3: Create a subdirectory in the directory created.
Ans: To display Calender for the current month use the CAL command.
% CAL
Ans: To see all the other users that are currently connected to system simply use
% who command.
Ans: The banner Command displays a large ASCII art version of input text. There are two common
varieties: one, which prints text horizontally for display to a terminal, and another which prints text in
much larger letters for output to a line printer.
% banner Student
% banner w80 a
Ans: To display the device name of the terminal, use the tty command:
Ex 10: Move to the root directory.
Ans:
MV mydirectory exercise
Step-1: cat example1
Step-2: type the text
Step-3: Press ctrl+D for save
Ex 12: Use the man command to obtain further information on the finger command.
Ans: The man command displays information from the reference manuals. It displays complete manual pages that you select
by name, or one-line summaries selected either by keyword (-k), or by the name of an associated file (-f). If no manual
page is located, man prints an error message.
% man command name
% man finger
Finger - display information about local and remote users
Ans: To copy any text file to another text file use the cp command:
cp file1 file2 is the command which makes a copy of file1 in the current working directory and calls
it file2.
First CD to your current directory:
% cd ~/Student
Then, copy the text file,
% cp /unix/examples/copy.txt.
(Note: Don't forget the dot (.) at the end. Remember, in UNIX, the dot means the current
directory.)
ELSE
% cp file1 file2.
Session 3 :
Ex 21: When you receive a message, save it to a file other than your mailbox.
Ans: We can open all received message by
$mail
Then we save a mail message to a file by
$sx
UNIX uses two mailboxes to hold mail messages
system mailbox (/usr/spool/mail/)
user mail box (..../.../mbox)
Ex 23: Try to move to the home directory of someone else in your group. There are several ways to do this, and
you may find that you are not permitted to enter certain directories. See what files they have, and what the file
permissions are.
Ans: To move to the home directory of someone else in the group:
% cd ~ user1
To list the files in the directory and their permissions:
% ls ldg
Ex 24: Try to copy a file from another users directory to your own.
Ans: @pwd
User/mca11
$cd abhishek
$ cp xyz.txt/user2/mca4
Ex 25: Set permissions on all of your files and directories to those that you want. You may want to give read
permission on some of your files and directories to members of your group.
Ans: - $mkdir/user/mca11/helpme
$cd user/mca11/helpme
Ans:
1. This command will display the listing of all files having extension .txt.
$ls *.txt
2. Lists only the files Lit and bit. The file snit was not listed because it has two characters before "it".
ls ?it
Ex 28: Put a listing of the files in your directory into a file called filelist. (Then delete it!)
Ans:
Ex 29: Create a text file containing a short story, and then use the spell program to check the spelling of the
words in the file.
$cat> story.txt
Type the text
Press ctrl+D to save.
Ans:
$spell story.txt
Ex 30: Redirect the output of the spell program to a file called errors.
Ans: $spell story.txt > error
Session 4 :
Ex 31: Type the command ls -l and examine the format of the output. Pipe the output of the command ls -l to the
word count program WC to obtain a count of the number of files in your directory.
Ans: The WC command is used to print the number of lines, words, and characters in a file.
Ex 32: Use cut to strip away the reference material and leave just the text field.
Ans: Cut command is typically used to extract a certain range of characters from a line, usually
from a file.
Syntax: % cut [-b] [-c] [-f list] [-n] [-d delim] [-s] [file]
input to its standard output, while replacing the first character specified on the command line with
the second character specified.
Lets consider the text file to be example1.txt,
$ echo <B></B> this is the tag for bold text
Cat example1.txt | tr <a-z> a-z
Output: B/B this is the tag for bold text
Ex 34: Set a file to be read-only with the chmod (from change mode) command. Interpret the file permissions
displayed by the ls -l command.
Ans: To set the file to be read-only to all,
Ex 35: Delete one or more directories with the rmdir (from remove directory) command. See what happens if the
directory is not empty. Experiment (carefully!) with the rm -r command to delete a directory and its content.
$rmdir
$rm r
$rm r abc
Ans:
Ex 36: Experiment with redirecting command output (e.g., ls -l >file1). Try ">> instead of >" with an existing
text file as the output.
Ex 37: See whether upper-case versions of any of these commands work as well as the lower-case versions.
Ex 38: Use the who command to see users logged into the system.
$who
Mca1 ttyp7
Mca2 ttyp5
Mca2 ttyp6
Mca3 ttyp7
Ans:
mar20
mar19
mar16
mar11
15:14
11:11
11:10
13:11
Ex 39: Pipe the output of the who command to the sort command.
Ans: -
$who | sort -4
To pipe the output of the who command to the input of the sort command:
%who | sort >file1
Ex 40: Search for your login name in whofile using the grep command.
Ans: . The grep command displays the name of the file containing the matched line if you specify
more than one name in the File parameter.
$who >who file
$grep student whofile
Or
$who |grep student
Session 5 :
Ex 41: Compare two text files with the diff command.
Ans: The diff command is used to display two files and prints the lines that are different.
Ex 42: Count lines, words, and characters in a file with the wc command.
Ans: - $wc c for characters
$wc l for lines
$wc w for wordss
Ex 43: Display your current environment variables with the following command: set or env.
Ans:
Ex 44: Concatenate all files in a directory redirected to /dev/null and redirecting standard error to errorFile?
Ans:
Ex 45: Display information on yourself or another user with the finger command.
Ans:
The finger displays the user's login name, real name, terminal name and write status.
Login
Mca1
Mca2
Mca3
Mca4
$finger
name tty
*P20 15:49
*P21 12:22
*P23 14:49
*P26 11:49
idle
22:11
21:11
12:11
22:11
Ex 46: If you wish, experiment with sending and receiving mail using the pine email program.
Ans: Pine is an easy to use, character based mail client. It supports full screen editing of messages,
binary attachments (such as GIF or ZIP files), and other advanced message system features that
were not possible using older electronic mail clients.
Features of pine:
Full Screen Capabilities
Safety for New Users confirmation of actions.
On-Line Help
Sending Attachments with Your Message MIME encoding
Name Recognition (Address Books)
Message Browsing
Message Printing
Saving Messages
Pine is a menu based screen and you should look at the bottom of the screen where valid
menu commands are shown
Using PINE:
1.
Type pine at the UNIX prompt and you will see the pine screen.
2.
Enter user name and password.
3.
To compose mail, Use the compose command C - COMPOSE MESSAGE to compose a
message. After composing, to send the mail, use Ctrl+X to send your message. Can you
see the choice ^X Send in the menu bar at the bottom of the screen.
4.
To see the mails you have received use the L - LIST FOLDERS command from the main
menu to see your folders and choose the INBOX folder. Use N - NextMsg to read the next
message or P - PrevMsg to read previous message.
5.
To reply use the R - Reply command, and to forward mail use the F - Forward
command.
6.
You can use the D - Delete command to delete your unwanted mails.
7.
If you want to print (or read the message you want to print, then choose the command O
- OTHER CMDS, then choose command % - Print. At the bottom you will see the message
Print message n using "attached-to-ansi" ? , where n is the message number. Answer
it with Y [Yes] . A pop-up print setup screen will appear, and click OK button. Your mail
content will then be printed from your local printer.
8.
You can exit pine by using Q - QUIT command when you are in the main menu.
Ex 47: Delete all the files in the current directory whose name ends in .bak.
Ans: $cat>a.back
Sss
Ctrl+D
$ls l *.back
$rm *.back
Ex 48: Display lines 10 to 14 of any file which contains 25 lines.
Ans:
Ex 49: Count how many lines contain the word science in a word file science.txt.
Ans: First find the word using the grep command and then pie it using the wc command.
% grep science science.txt | wc l
Ex 50: List the statistics of the largest file (and only the largest file) in the current directory.
Ans:
Session 6 :
Ex 51: Kill any process with the help of the PID and run any process at the background.
Ans: $pwd
$kill 22556
$vi abc.txt
$date &
Ex 52: Select a text file and double space the lines.
Ans: Use the SED command to double space the lines in a text file.
% sed filename
Ex 53: List all the users from /etc/passwd in the alphabetically sorted order.
Ans:
$cat /etc/password|sort
Ex 54: Create a file with duplicate records and delete duplicate records for that file..
Ex 55: Use the grep command to search the file example1 for occurrences of the string water.
Ans: $cat>prog.sh
Ans: $grep n1
To select the lines in a file and direct them to another file which has digits as one of the characters in that
line.
$vi nv
Echo Enter any no.
Read a
Echo Number is 4a
Ex 59: Write a shell script that searches for a single word pattern recursively in the current directory and displays
the no. of times it occurred.
Ans:
$grep r ABC
Session 7 :
Ex 61: Write a shell script that accepts a string from the terminal and echo a suitable message if it doesnt have at
least 5 characters including the other symbols.
Ans: $vi abc
Echo Enter the string
Read s
C=`expr $s |wc c`
C=`expr $c -1`
If Test $c ge 5
Then
Echo String is valid
Else
Echo String is invalid
Fi
:wq
Ex 62: Write a shell script to echo the string length of the given string as argument.
Ans: $Vi xyz
Echo enter the String
Read a
C=echo $a |wc c
C=`expr $c -1`
Echo $c
:wq
Ex 63: Write a shell script that accepts two directory names as arguments and deletes those files in the first
directory which are similarly named in the second directly. Note: Contents should also match inside the files.
Ans:
$Vi abc
Echo enter the fist Dir
Read a
Echo Enter the second Dir
Read b
Ls $a >> aa
Ls $b >> bb
For in comm. -1-2 aabb
Do
Q=emp s/usrer/bca/hour/s1/user1/bca1/abhi/$i
Echo $q
If Test $q eq 0
Sun/user1/bca1/hour/$ls
Sun/user1/bca1/abhi/&i
Else
fi
Done
:wq
Ex 64: Write a shell script to display the processes running on the system for every 30 seconds, but only for 3
times.
Ans: Vi process
I=0
While Test $i le 3
Do sleep 5
Ps
i=`expr $i +1`
done
Ex 65: Write a shell script that displays the last modification time of any file.
Ans:
$ crypt -puu2 < file9
This will encrypt the file using the puu2 key.
Or
$ crypt file9
Enter the key: puu2
This will encrypt the file.
Ex 68: Combine the above commands in a shell script so that you have a small program for extracting a wordlist.
Ans:
Ex 69: Write a shell script which reads the contents in a text file and removes all the blank spaces in them and
redirects the output to a file.
Ans:
W=`wc w Test`
Echo No of word $w
C=1
Set cat jay
While test $c le $w
Do
Echo n $i>>jay
C=`expr $c +1`
Done
Cut jay
Or
Vi xyz
For I in cat jay
Do
Echo n 4i
done
Ex 70: Write a shell script that changes the name of the files passed as arguments to lowercase.
Ans:
Echo $i>temp
Tr [:uppr:] [:lowe:] [temp]
Mv /user/mca2/$i/user/mca2/$a
Session 8 :
Ex 71: Write a shell script to translate all the characters to lower case in a given text file.
Ans: Echo enter a text file
Read file
If [1 $file]
Then
Echo 4file not a file
Exit
Fi
Cat $file |tr [A-Z] [a-z]
Ex 72: Write a shell script to combine any three text files into a single file (append them in the order as they
appear in the arguments) and display the word count.
Ans: # //bin/bash
File1=$1
File2=$2
File3=$3 out- output $1
Count=0
If [$# -ne 3]
Then
Echo $(base name $o) file1 file 2file3
Exit1
Fi
If [!=$file]
Then
Echo $file! Not a file
Exit2
Fi
If[! f $file2]
Then
Echo $file2 not file!
Exit 3
Fi
If [1- f $file]
Then
Echo $file3 not a file!
Exit2
Fi
$file1 $file 2$file3?? $out
Count=4(cat $out|wc w)
Echo count words written to out!
Ex 73: Write a shell script that, given a file name as the argument will write the even numbered line to a file with
name evenfile and odd numbered lines to a file called oddfile.
Ans:
Ex 74: Write a shell script which deletes all the even numbered lines in a text file.
Ans:
Ex 75: Write a script called hello which outputs the following:
your username
the time and date
who is logged on
also output a line of asterices (*********) after each section.
Ans:
Ex 76: Put the command hello into your .login file so that the script is executed every time that you log on.
Ans:
Ex 77: Write a script that will count the number of files in each of your subdirectories.
Ans:
Ex 78: Write a shell script like a more command. It asks the user name, the name of the file on command prompt
and displays only the 15 lines of the file at a time on the screen. Further, next 15 lines will be displayed only when
the user presses the enter key / any other key.
Ans:
Ex 79: Write a shell script that counts English language articles (a, an, the) in a given text file.
Ans:
Ex 80: Write the shell script which will replace each occurrence of character c with the characters chr in a string
s. It should also display the number of replacements.
Ans:
Session 9 :
Ex 81: Write the shell program unique, which discards all but one of successive identical lines from standard
input and writes the unique lines to standard output. By default, unique checks the whole line for uniqueness.
For example, assuming the following input:
List 1 List 2 List 2 List 3 List 4 List 4 List 2
unique should produce the following output as follows:
List 1 List 2 List 3 List 4 List 2
Ans:
Ex 82: Rewrite the unique program so that it can optionally accept a file name on the command line and redirect
the output to that file.
Ans:
Ex 83: Write the shell program which produces a report from the output of ls -l in the following form:
Only regular files, directories and symbolic links are printed.
The file type and permissions are removed.
A / character is appended to each directory name and the word DIR is printed at the beginning of the
line.
A @ character is appended to each symbolic link name and the word LINK is printed at the beginning
of the line.
At the end of the listing, the number of directories, symbolic links, regular files and the total size of regular files
should be reported.
Ans:
Ex 84: Write the shell program which removes all the comments from a simple C program stored in your current
directory. You can assume that the C source code contains only syntactically correct comments:
starting with //, ending with a newline
starting with /*, ending with */ (can be multi-line)
nesting of comments is not allowed.
Make sure that C source code is not changed.
Ans:
Ex 85: Write a shell program that outputs all integers up to the command line parameter starting from 1 and also
should output the same numbers in the reverse order.
Ans:
Session 10 :
Ex 86: Write a shell program to concatenate to two strings given as input and display the resultant string along
with its string length.
Ans:
Ex 87: Write a shell program to find the largest integer among the three integers given as arguments.
Ans:
Ex 88: Write a shell program to sort a given file which consists of a list of numbers, in ascending order.
Ans:
SECTION 2
DBMS Lab
Session 1 : Sub Queries and Joins
Ex 1: Please attempt the following problems for the teacher, class and pay scale relations given in this section.
Ans:
Table Creation:
-- Create table
create table TEACHER
(
T_NO
VARCHAR2(3) not null,
F_NAME
VARCHAR2(50),
L_NAME
VARCHAR2(25),
SALARY
NUMBER,
SUPERVISIOR VARCHAR2(3),
JOININGDATE DATE,
BIRTHDATE DATE,
TITLE
VARCHAR2(3),
INC
NUMBER
)
tablespace SYSTEM
pctfree 10
pctused 40
initrans 1
maxtrans 255
storage
(
initial 64K
minextents 1
maxextents unlimited
);
-- Create/Recreate primary, unique and foreign key constraints
alter table TEACHER
add constraint TEACHER_PK primary key (T_NO)
using index
tablespace SYSTEM
pctfree 10
initrans 2
maxtrans 255
storage
(
initial 64K
minextents 1
maxextents unlimited
);
-- Create table
create table CLASS
(
CLASS_NO VARCHAR2(3) not null,
T_NO
VARCHAR2(3),
ROOM_NO VARCHAR2(3)
)
tablespace SYSTEM
pctfree 10
pctused 40
initrans 1
maxtrans 255
storage
(
initial 64K
minextents 1
maxextents unlimited
);
-- Create/Recreate primary, unique and foreign key constraints
alter table CLASS
add constraint CLASS_PK primary key (CLASS_NO)
using index
tablespace SYSTEM
pctfree 10
initrans 2
maxtrans 255
storage
(
initial 64K
minextents 1
maxextents unlimited
);
alter table CLASS
add constraint CLASS_FK foreign key (T_NO)
references TEACHER (T_NO);
-- Create table
create table PAYSCALE
(
MIN_LIMIT NUMBER,
MAX_LIMIT NUMBER,
GRADE
VARCHAR2(5) not null
)
tablespace SYSTEM
pctfree 10
pctused 40
initrans 1
maxtrans 255
storage
(
initial 64K
minextents 1
maxextents unlimited
);
-- Create/Recreate primary, unique and foreign key constraints
alter table PAYSCALE
add constraint PAYSCALE_PK primary key (GRADE)
using index
tablespace SYSTEM
pctfree 10
initrans 2
maxtrans 255
storage
(
initial 64K
minextents 1
maxextents unlimited
);
Table: Teacher
t_no, f_name, l_name, salary, supervisor, joiningdate, birthdate, title
Table: Class
class_no, t_no, room_no
Table: Payscale
min_limit, max_limit, grade
(a) Display the name of the teacher(s) who is (are) the youngest among all the teachers.
Ans: SELECT f_name, l_name
FROM teacher
WHERE birthdate=(SELECT MIN(birthdate) FROM teacher);
(b) Display details of all the teachers who have the same job title as that of Jaideep
Ans: SELECT * FROM teacher
WHERE title = (SELECT title FROM teacher WHERE LOWER(f_name)=jaideep);
(c) Display the list of all the teachers who have joined after 10-Jul-95 and whose salary is equal to that of any of
the teachers who joined before 10-Jul-95.
Ans:
(d) Use a correlated query to determine the teachers who are not class teachers.
(i) Display details of all those teachers who are class teachers of classes 1 to 5.
Ans: Select t.t_no, t.f_name, t.l_name, t.salary, t.supervisor, t.joiningdate, t.birthdate, t.title
From teacher t, class c
where c.T_NO = t.T_NO and c.CLASS_NO between '1' and '5'
(j) Display the names of all teachers along with their dates of birth whose birthday is in the current month.
Ans: select F_name,L_name
from teacher
where to_char (birthdate,'MON') = (select to_char(sysdate,'MON') from dual);
Ex 2: In an Open University a students data is to be maintained using relations. The university maintains
data of all the students, their batches, Regional Centres and study centre details. Each batch of students
has one or more representative students. The batches are taught by same or different faculty.
(a) Design and implement the suitable relations for the University. Make and state suitable assumptions.
The following tables were created and the data inserted as under.
SQL> SELECT * FROM STUDENT;
STDID
NAME
ADDRESS
COURSEID BATCHID
---------------------------NILADRI VIHAR
NILADRI VIHAR
SAHID NAGAR
KALPANA SQURE
BILAS PUR
MANCHESWAR
SAILESHRI VIHAR
CHENNAI
MUMBAI
DELHI
-------------M001
M001
MB001
MB001
BB001
BB001
CO001
CO001
SC001
SC001
-------------B001
B001
B002
B002
B003
B003
B004
B004
B004
B005
Ex.2 (b) Write at least 15 queries (they must include at least one query of each type given in this section 2.2)
for the database. Implement these queries using SQL. Also explain the purpose of each query.
Ans:
I.
Display the details of study centre where a student named Sanzaya reads;
SQL>
III. Display the list of all teachers who take classes for batch B004
SQL>
IV. Display the name of teachers who were working in regional centre BBSR
SQL>
VI. Display the name of teachers who teach in delhi and have atleast two a in their name.
SELECT TNAME FROM TEACHERS WHERE
UPPER(TNAME) LIKE '%A%A%'
AND
BATCHID IN(SELECT BATCHID FROM BATCH WHERE
RCID=(SELECT RCID FROM REGCENT WHERE
UPPER(RCNAME)='NDLS'));
VII. Display the name of student whose teachers name starts with S.
SELECT NAME FROM STUDENT WHERE
BATCHID IN (SELECT BATCHID FROM BATCH WHERE
BATCHID IN (SELECT BATCHID FROM TEACHERS WHERE
UPPER(TNAME) LIKE 'S%'));
VIII. Display the name of the teachers with the batch details.
SELECT TNAME,B.BATCHID,RCID,SDYID,COURSEID,REPSTDID
* FROM TEACHERS T,BATCH B WHERE B.BATCHID=T.BATCHID
X. Display the teachers name along with the students they teach.
SQL>
XII. Display students name who read under teacher whose last name is sehgal.
SELECT NAME FROM STUDENT WHERE BATCHID IN(
SELECT BATCHID FROM TEACHERS WHERE
* UPPER(TNAME) LIKE '%SEHGAL%');
Ex 3: Design a suitable database system for a bank along with 20 possible queries to the database (the
queries should be such that their solution involves sub queries or joins or both). Implement the database
and the queries in a commercial DBMS using SQL.
Ans:
(c) Modify the view created in (a) and add details like salary, job title, joining date, birth date etc. of all
supervisors.
Ans:
(d) Using the view created in (c) display details of all supervisors who have worked for more than 15 years.
View created.
SQL> select * from teacher_info;
Granting permissions
SQL> grant select
on teacher_info
to system;
Grant succeeded.
(j) Create a view that displays details of all teachers who are in grade B and are more than 40 years old.
Ans:
CREATE OR REPLACE VIEW SCOTT.TECHER_DETAIL1
AS
SELECT t_no ,f_name||' '||l_name as name,title,salary,
trunc(months_between(sysdate,birthdate)/12,0) age , grade from teacher, payscale
WHERE salary between min_limit and max_limit ;
select * from TECHER_DETAIL1 where age>40
Ex 2 : Design suitable views for the University database system (Exercise 1, question 2). For example, you
can create a view for the faculty giving him/her details of his/her students. Create at least 5 suitable queries
on each of the views created by you. Also create indexes for the University database system. For example,
you can create an index on student name, thus, allowing faster access to student information in the order of
student names. You must explain how the indexes created by you would enhance the performance of the
database system. Implement the above in a commercial DBMS using SQL.
Ans:
Ex 3 : Design suitable views and indexes for the Bank database system (Exercise 1, question 3). Create at
least 5 suitable queries on each of the views. Explain how the indexes created by you would enhance the
performance of the database system. Implement the above in a commercial DBMS using SQL.
Ans:
Session 3 : PL/SQL Control Loops and Procedures
Ex 1: Please perform the following using the following relations:
Teacher(t_no, f_name, l_name, salary, supervisor, joiningdate, birthdate, title)
Class(class_no, t_no, room_no)
Payscale(Min_limit, Max_limit, grade)
(a) Calculate the bonus amount to be given to a teacher depending on the following conditions:
I. if salary > 10000 then bonus is 10% of the salary.
II. if salary is between 10000 and 20000 then bonus is 20% of the salary.
III. if salary is between 20000 and 25000 then bonus is 25% of the salary.
IV. if salary exceeds 25000 then bonus is 30% of the salary.
Ans:
CREATE OR REPLACE PROCEDURE Calculate_Bonus(t_no in int) IS
Vbonus int;
Vtno int :=0;
Vsal int :=0;
BEGIN
Vbonus :=0;
Vtno :=t_no;
select salary into Vsal from teacher1 where t_no=Vtno;
if(Vsal<10000) then
Vbonus :=Vsal*(10/100);
elsif(Vsal between 10000 and 20000) then
Vbonus :=Vsal*(20/100);
elsif(Vsal between 20000 and 25000) then
Vbonus :=Vsal*(25/100);
elsif(Vsal >25000) then
Vbonus :=Vsal*(30/100);
end if;
dbms_output.put_line(Vbonus);
-- bonus :=Vbonus;
END Calculate_Bonus;
(b) Using a simple LOOP structure, list the first 10 records of the teachers table.
Ans: declare
fetchten teacher%rowtype;
cnt number :=0;
cursor curr
is
select * from teacher;
begin
open curr;
loop
exit when curr%notfound or cnt=10;
fetch curr into fetchten;
Ans:
(e) Using FOR loop, display name and id of all those teachers who are more than 58 years old.
Ans:
(f) Using while loop, display details of all those teachers who are in grade A.
Ans:
(g) Create a procedure that displays the names of all those teachers whose supervisor is Suman.
Ans:
begin
open curr;
loop
fetch curr into temphold;
exit when curr%notfound;
dbms_output.put_line(temphold.F_name);
end loop;
close curr;
end;
(h) Calculate the tax to be paid by all teachers depending on following conditions:
I. if annual salary > 1,00,000 then no tax.
II. if annual salary is between 1,00,001 and 1,50,000 then tax is 20% of the annual salary.
III. if annual salary is between 1,50,001 and 2,50,000 then tax is 30% of the annual salary.
IV. if salary exceeds 2,50,000 then tax is 40% of the annual salary.
Ans: create or replace procedure TaxCalc
is
t_F_Name teacher.F_Name%type;
t_Salary teacher.Salary%type;
tax teacher.Salary%type;
cursor curr is
select F_name,Salary*12 from teacher;
begin
open curr;
loop
fetch Curr into t_F_name,t_Salary ;
exit when curr%notfound;
if t_Salary<100000 then
tax:=0;
elsif t_Salary<150000 then
tax:=(t_Salary-100000)*0.20;
elsif t_Salary<250000 then
tax:=(t_Salary-150000)*0.30+50000*0.20;
else
tax:=(t_Salary-250000)*0.40+100000*0.30+50000*0.20;
end if;
DBMS_OUTPUT.PUT_LINE(t_F_NAME||' OWES '||tax||' as Tax ');
end loop;
close curr;
end;
(i) Create a procedure that finds the names of all teachers with the job title PRT and if the number of
teachers returned is more than 10 than change the job title to TGT for the top 3 PRT teachers based on
their hiredate.
Ans: CREATE OR REPLACE PROCEDURE CheckTGTExceed IS
Vcount int ;
Vmaxdate date ;
BEGIN
loop
select count(*) into Vcount from teacher1 where title='TGT' ;
select max(joiningdate) into Vmaxdate from teacher1 where title='TGT';
if(Vcount>2) then
update teacher1 set title='PRT' where joiningdate=Vmaxdate and title='TGT';
else
exit;
end if;
end loop;
END CheckTGTExceed;
Ex 2: Identify the need of procedures for the University database system; for example, you can create a
procedure that awards 2% grace marks for those students who have got 48% marks. Design at least 5 such
procedures. Implement these procedures using an embedded SQL.
Ans:
Ex 3: Implement at least five procedures for the Bank Database system using embedded SQL.
open c_bank;
loop
fetch c_bank into v_bank;
exit when c_bank%notfound;
if v_bank.process='no' then
update acco_trans set process='yes' where
accno=v_bank.accno;
if v_bank .deb_cre='credit' then
update acco_master set balance=balance+v_bank.amount
where v_bank.accno=acco_master.accno;
elsif v_bank.deb_cre='debit' then
update acco_master set balance=balance-v_bank.amount
where v_bank.accno=acco_master.accno;
elsif balance<=0 then
dbms_output.put_line('Transaction not possible');
end if;
end if;
end loop;
close c_bank;
end;
SQL>select * from acco_trans;
AccNo Trans_Date
Deb_Cre
Amt Pro
---------- -------------- ------------ --------- -------------1012
12-Jan-08 debit
5000 yes
1024
14-Feb-08 credit
100
yes
1987
04-Dec-07 credit
1000
yes
2345
17-Mar-08 credit
20000 yes
Cursor for BANK DATABASE
SQL > create table depositor (accno primary key , cname char(10))
Table created.
SQL > create table borrower (loanno number , cname char(10))
Table created.
SQL > create table loan( loanno number , brname char(10),amt number)
Table created.
SQL > create table acct-t( acctno number , bal number, brname char(10), foreign key (acctno)
references depositor (acctno)
Table created.
SQL > insert into depositor values (&accno , &cname );
Enter value for accno
: 101
Enter the value for cname : Alan
SQL > insert into acct-t values( &acctno , &bal , '&brname ');
Enter value for accno
: 101
Enter the value for bal
: 20000
Enter the value for brname : tvm
SQL > select * from depositor;
ACCNO
CNAME
101
Alan
102
Ann
103
Ben
SQL > select * from acct-t;
ACCNO
BAL
BRNAME
------------- ------------------- ---------------101
20000
tvm
102
10500
ekm
103
5000
tcr
SQL > create or replace trigger
declare
c varchar2 (20)
begin
if (:new.bal < :old.bal) then
insert into loan values (:new.accno, :new.brname , :old.bal-:new.bal);
select cname into c from depositor where accno = new.accno;
insert into borrower values (:new.accno,c);
endif;
end;
Trigger created.
SQL > update acct-t set bal = bal-5000 where acctno=101
1 row updated.
SQL >select * from borrower;
LOANNO
CNAME
---------------------------------
101
Alan
SQL >select * from loan;
LOANNO
BR NAME
101
tvm
AMT
15000
Session 4 : Cursors
Ex 1: Please perform the following using the following relations:
Teacher(t_no, f_name, l_name, salary, supervisor, joiningdate, birthdate, title)
Class(class_no, t_no, room_no)
Payscale(Min_limit, Max_limit, grade)
(a) Create a host language block to declare a cursor for displaying teacher numbers and their names for all
teachers having title PGT.
Ans: ed
Wrote file afiedt.buf
CREATE OR REPLACE PROCEDURE E4a IS
vno int ;
Vname varchar2(30);
Vrec varchar2(100);
cursor c1 is select T_NO,F_NAME from teacher where TITLE='TGT';
BEGIN
--vno :=0;
--Vname :='';
Vrec :='';
open c1;
loop
exit when c1%notfound;
fetch c1 into vno,Vname;
Vrec :=vno ||' '|| Vname;
dbms_output.put_line(Vrec);
end loop;
close c1;
END E4a * ;
Procedure created.
SQL> exec e4a
6 Jatin
6 BBB
6 BBB
PL/SQL procedure successfully completed.
(b) Create a host language block using a cursor to calculate bonus for teachers as 5% of their salary.
Display on screen the teacher details along with the bonus given.
Ans: declare
vno int ;
Vname varchar2(30);
bonus int ;
cursor c1 is select F_NAME,salary from teacher;
begin
vno :=0;
Vname :='';
open c1;
dbms_output.put_line('Name Bonus');
dbms_output.put_line('-------------');
loop
exit when c1%notfound;
fetch c1 into Vname,vno;
bonus :=vno*(5/100);
-- dbms_output.put_line(vno||Vname);
dbms_output.put_line(Vname||', bonus: '||bonus);
end loop;
close c1;
* end;
(c) Write a host language block to delete all the rows from the teacher table where the salary is less than
Rs.5000.
Ans:
DECLARE
c_t_no teacher.t_no%TYPE;
c_f_name teacher.f_name%TYPE;
c_l_name teacher.l_name%TYPE;
c_salary teacher.salary%TYPE;
CURSOR c1 IS
Ans:
DECLARE
CURSOR c2 IS
SELECT t_no,f_name, l_name, salary
FROM teacher ;
teacher_rec c2%ROWTYPE;
BEGIN
OPEN c2;
FOR teacher_rec IN c2
LOOP
I F teacher_rec.salary > 20000
Teacher_rec.title = SUPERVISOR;
ENDIF;
END LOOP;
CLOSE c2;
END;
(e) Write a block in host language that deletes all the rows from teacher table if the teacher was hired for
more than 10 years.
Ans:
declare
vno int ;
Vname varchar2(30);
bonus int ;
cursor c1 is select T_NO,F_NAME from teacher
where trunc(months_between(sysdate,JOININGDATE) /12,0)>10;
begin
vno :=0;
Vname :='';
open c1;
loop
exit when c1%notfound;
fetch c1 into vno,Vname;
delete from teacher where T_NO =vno;
dbms_output.put_line('Delete'||vno);
end loop;
close c1;
end;
(f) Write a block in host language using cursor that displays the names of all teachers who will attain the
age of 60 years in the current year.
Ans:
declare
vno int ;
Vname varchar2(30);
bonus int ;
cursor c1 is select T_NO,F_NAME from teacher
where runc(months_between(sysdate,BIRTHDATE)/12,0)>45;
begin
vno :=0;
Vname :='';
open c1;
loop
exit when c1%notfound;
fetch c1 into vno,Vname;
-- delete from teacher1 where T_NO =vno;
dbms_output.put_line('name :'||Vname);
end loop;
close c1;
end;
(g) Write a block in host language using cursors that display teacher details along with the tax to be paid by
that teacher. The tax is calculated depending on following conditions:
I. if annual salary 1,00,000 then no tax.
II. if annual salary is between 1,00,001 and 1,50,000 then tax is 20% of the annual salary.
III. if annual salary is between 1,50,001 and 2,50,000 then tax is 30% of the annual salary.
IV. if salary exceeds 2,50,000 then tax is 40% of the annual salary.
Ans:
CREATE OR REPLACE PROCEDURE E4g(tid in int) IS
Vid int ;
Vmsal int ;
Vysal int;
tax int ;
Vtsal int ;
cursor c1 is select salary from teacher where t_no=tid;
BEGIN
open c1 ;
loop
exit when c1%notfound;
fetch c1 into Vtsal;
Vysal :=Vtsal*12;
if(Vysal<100000) then
dbms_output.put_line('no tax');
elsif(Vysal between 100001 and 150000) then
tax := Vysal*(20/100);
elsif(Vysal between 150001 and 250000) then
tax := Vysal*(30/100);
elsif(Vysal>250000) then
tax := Vysal*(40/100);
end if;
end loop;
dbms_output.put_line(tax);
close c1;
END E4g;
(h) Write a block in host language that displays the details of all those teachers who have reached
maximum limit of their grade.
Ans:
CREATE OR REPLACE PROCEDURE E4h IS
vno int ;
Vfname varchar2(30);
Vlname varchar2(30);
Vsalary int;
Vsup varchar2(30);
Vjdate date;
Vbdate date ;
Vtitle varchar2(30);
cursor c1 is select
T_NO,F_NAME,L_NAME,SALARY,SUPERVISOR,JOININGDATE,BIRTHDATE,TITLE from
teacher1,payscale WHERE salary= max_limit ;
BEGIN
open c1;
loop
exit when c1%notfound;
fetch c1 into vno,Vfname,Vlname,Vsalary,Vsup,Vjdate,Vbdate,Vtitle;
dbms_output.put_line('T_no'||vno||' '
||Vfname||Vlname||Vsalary||Vsup||Vjdate||Vbdate||Vtitle);
end loop;
close c1;
END E4h;
----------------------------or--------------------------SELECT distinct( grade), max(salary),title
from teacher1,payscale
WHERE salary= max_limit
group by salary,title,grade
Ex 2: Write at least four embedded SQL blocks having cursors for the University database system; for
example, you can create a cursor to update the examination marks of a student that are given in a list to the
students database. Implement these procedures using an embedded SQL.
Ans:
Ex 3: Implement at least five embedded SQL blocks having cursors for the Bank Database system.
Ans:
Session 5 : Error Handling And Transaction Management
Ex 1: Write an embedded SQL block along with exceptions to select the name of the teacher with a given
salary. If more than one row is returned than display more than one row retrieved. If no row is returned
then display no teacher with this salary.
Ans: CREATE OR REPLACE PROCEDURE E5a(tid in int) IS
Vsal int;
Vfname varchar2(30);
Vrc int ;
BEGIN
select f_name, salary,count(*)as sasa into Vfname,Vsal,Vrc from teacher where t_no=tid group
by f_name,salary;
if(Vrc>=1) then
dbms_output.put_line('recoed found');
else
dbms_output.put_line('recoed not found');
end if;
EXCEPTION
when no_data_found then
raise_application_error(-20100,'not tid found enter the valid teacher id ') ;
dbms_output.put_line('envalid teacher id ');
WHEN NO_DATA_FOUND THEN
NULL;
WHEN OTHERS THEN
Consider logging the error and then re-raise
RAISE;
END E5a;
Ex 2: Create a program that updates a record into the teacher table. Trap and handle the exception if the
teacher id is not available in the teacher table.
Ans: create or replace procedure UpdateSal(TeacherName in VARCHAR2)
is
cnt Number:=0;
tF_name teacher.F_Name%Type;
NoTeacherFound Exception;
Cursor curr
is
select salary from teacher where f_name=TeacherName;
BEGIN
open curr;
loop
fetch curr into tF_Name;
exit when curr%notfound;
cnt:=cnt+1;
end loop;
close curr;
if cnt<1 then
RAISE NoTeacherFound;
else
update teacher set salary=1.05*salary where F_Name=TeacherName;
end if;
EXCEPTION
When NoTeacherFound then
RAISE_APPLICATION_ERROR('-20003','No Teacher with this Name');
end;
Ex 3: Write a program with exceptions that displays the details of all those teachers who have reached
maximum limit of their grade. If no row is retrieved then raise the exception no teacher reached max limit
of grade.
Ans:
Ex 4: Insert at least 5 new rows in the teacher table and then try to rollback last 3 rows inserted to the
table. (Here, you are required to use save points).
Ans:
Ex 5: Write a program with exceptions that displays the names of all teachers who will attain the age of 60
years in the current year. If no row is retrieved than display suitable exception.
Ans:
Ex 6: Write a PL/SQL block that displays all the rows from teacher table if the teacher was hired for
more than 10 years and still a PRT. If no result than display suitable message.
Ans:
Ex 7: In all the embedded SQL program segments that you have created so far for the University and
Bank database system, create suitable error handling features.
Ans:
Ex 8: Experiment with DDL and DML commands along with COMMIT and ROLLBACK for the
Teacher, University and Banking databases.
Ans:
Session 6 : Triggers And Functions
Ex 1: Write a trigger that is fired before the DML statements execution on the TEACHER table. The
trigger checks the school timings based on SYSDATE. Beyond the School working hours the trigger raises
an exception, which does not allow any work to be happened.
Ans:
create or replace trigger Q1
before insert or update or delete on teacher
for each row
when (to_char (SYSDATE,'HH24') between 9 and 23)
begin
dbms_output.put_line('Cant Do any job outside school timings');
end;
Ex 2: Write a trigger that is fired before an UPDATE statement is executed for the teacher table. The
trigger should write the name of teacher, user name and system date in an already created table called
UPDATE_TABLE.
Ans:
CREATE TABLE UPDATE_TABLE( TEACHER_NAME VARCHAR2(20),USER_NAME VARCHAR2(20)
DEFAULT 'STUDENT', SYS_DATE DATE);
CREATE OR REPLACE TRIGGER :
BEFORE UPDATE ON TEACHER
FOR EACH ROW
DECLARE
BEGIN
INSERT INTO UPDATE_TABLE VALUES(:OLD.F_NAME,USER,SYSDATE);
END;
RESULTANT TABLE:
Jaideep
ANONYMOUS
07-JAN-08
Parag
ANONYMOUS
07-JAN-08
ON EXECUTING:
UPDATE TEACHER SET F_NAME=A WHERE F_NAME=Parag;
UPDATE TEACHER SET L_NAME=A WHERE L_NAME=Patel;
Ex 3: Write a trigger that is fired before any row is inserted in the teacher table.
Ans:
BEFORE UPDATE ON TEACHER
BEGIN
IF UPDATING THEN
DBMS_OUTPUT.PUT_LINE('YOU ARE GOING TO UPDATE THE TEACHER TABLE');
END IF;
END;
Ex 4: Write a function and pass a job title to it. If the TEACHER table does not contain any row
corresponding to that title then return false otherwise true.
Ans:
Ex 5: Write a trigger that verifies the joining date when a new row is inserted in the teacher table.
Joining date should be greater or equal to current date.
Ans:
ed
Wrote file afiedt.buf
create trigger e6_5
after insert on teacher
for each row
Declare
jdate teacher.joiningdate%TYPE;
cdate date;
begin
jdate:=new.joiningdate;
cdate:=sysdate;
if jdate>=cdate then
dbms_output.put_line('Joining date is fine');
commit;
else
rollback;
end if;
end;
Ex 6: Write a function that gets the teacher id as parameter and returns the class number associated with
that teacher. If the teacher is not a class teacher then give suitable message.
Ans:
DECLARE
C_id teacher.t_no%TYPE;
C_f_name teacher.f_name%TYPE;
want_id NUMBER := 110;
BEGIN
SELECT t_no, f_name INTO c_t_no, c_f_name from teacher
WHERE t_no = want_id;
DBMS_OUTPUT.PUTLINE ( teacher : || c_t_no || ||c_f_name)
EXCEPTION
WHEN INVALID_NUMBER THEN
DBMS_OUTPUT.PUTLINE(want_id || not a valid teacher id);
END;
CREATE OR REPLACE TRIGGER new_teacher _id
AFTER INSERT ON teacher
FOR EACH ROW
DECLARE
o_t_no teacher.t_no%TYPE;
o_joiningdate teacher.joiningdate%TYPE;
BEGIN
SELECT t_no_sequence.nextval
INTO o_t_no
FROM dual;
:NEW.t_no := o_t_no;
:NEW.joiningdate := SYSDATE;
END;
Ex 7: Write a function and pass a teacher id to it. If the TEACHER table does not contain that id then
return false otherwise true.
Ans:
Ex 8: Write a function that takes teacher id as parameter and returns back the name and joining date of
the teacher.
Ans:
Ex 9: Write appropriate triggers and functions for the University and Bank database systems.
Ans:
Table created.
SQL> Insert into teacher values(
(10101, MP, Joshi, 30000, Mohan, 10-dec-08, 10-feb-07, TGT,
Dependent(sita)
);
1 row created.
Ex 2: Create at least two object types in both the University and Bank database systems. Use these object
types in few relations and enter some data into these relations. Query these databases.
Ans:
SQL>
ed
Wrote file afiedt.buf
create type type4univ as object
(
name varchar(20),
phone number(10)
* );
Type created.
Ans:
Ans:
CREATE TYPE address_t AS OBJECT (
street VARCHAR2(30),
city VARCHAR2(20),
state CHAR(2),
zip CHAR(5) );
/
CREATE TYPE address_tab IS TABLE OF address_t;
/
CREATE TABLE customers (
custid NUMBER,
address address_tab )
NESTED TABLE address STORE AS customer_addresses;
INSERT INTO customers VALUES (1,
address_tab(
address_t('101 First', 'Redwood Shores', 'CA', '94065'),
address_t('123 Maple', 'Mill Valley', 'CA', '90952')
) );
Ans:
CREATE TABLE message (
msg_id NUMBER(8) NOT NULL PRIMARY KEY,
email_add
VARCHAR(200),
name
VARCHAR (200),
message
CLOB,
posting_time DATE,
sort_key
VARCHAR (600));
DECLARE
Image10
BLOB;
image_number INTEGER := 101;
BEGIN
SELECT item_blob INTO image10 FROM lob_table10
WHERE key_value = image_number;
DBMS_OUTPUT.PUT_LINE('Image size is:'||DBMS_LOB.GETLENGTH(image10));
END;
Ex 2: Create at least two large objects for both the University and Bank database systems. Enter some data
into these relations. Query these databases.
Ans:
SQL> ed
Wrote file afiedt.buf
declare
image10 blob;
image_no integer:=101;
begin
select item_blob into image10 from universities
where t_no=Image_no;
dbms_output.put_line('Image size is:'||dbms_lob.getLength(image10);
end;
SQL> ed
Wrote file afiedt.buf
declare
image11 blob;
image_num integer:=01;
begin
select item_blob into image11 from Bank
where b_no=Image_num;
Ans:
CREATE USER class
IDENTIFIED BY pass;
GRANT CREATE TABLE, DROP TABLE, CREATE VIEW, DROP VIEW
TO class;
Ex 2: Create a student account and give permission to this account for only viewing the information on the
relation Class (class_no, t_no, room_no).
Ans:
DENY UPDATE, DELETE, INSERT ON employee TO student
GO
CREATE USER student
@Eclass_no int,
@St_no money,
@room_no int
GRANT EXECUTE ON student TO Class
GO
Ex 3: Create at least 3 to 4 different types of users for each of the database systems:
University and Bank. Design suitable access privileges for the users. Grant these permissions to the users.
Ans:
SQL> create user Murali identified by mpjoshi;
User created.
SQL> create user biku identified by deepak;
User created.
SQL> create user samir identified by rajak;
User created.
SQL> create user prashant identified by jain;
User created.
Creating access privileges:
t select, insert, update to Murali
grant options;
Grant succeeded.
t select, insert, update to biku
grant options;
Grant succeeded.
t select, insert, update to samir
grant options;
Grant succeeded.
t select, insert, update to prashant
grant options;
Grant succeeded.
Ex 4: Consider when you have a large number of students and teachers in the University databases that
have different access rights. Is there any mechanism in DBMS that allows defining an account type to some
specific role? If yes, then define such types for the University database system.
Ans:
Ex 5: Define different types of users for the Bank database and provide them suitable access rights.
Ans:
User Creation:
create user Manager identified by mgr1;
User created.
create user cashier identified by cash1;
User created.
create user clerk identified by clrk1;
User created.
create user General_manager identified by gm;
User created.
User rights assignments:
grant create table, update table,
drop table, create view, update view,
drop view to General_manager;
Grant succeeded.
grant create table, update table,
drop table, create view, update view,
drop view to Manager;
Grant succeeded.
grant update table,
create view, update view, to class;
Grant succeeded.
grant , update table,
drop table, , update view,to Clerk;
Grant succeeded.