DBMS Lab Manual 2017
DBMS Lab Manual 2017
DBMS Lab Manual 2017
AND TECHNOLOGY
Name: …………………………………………………….
Year: ….…… Semester: ………. Branch: …………….
University Register No
Date: ………………….
5. Implementation of functions in
RDBMS
6. Study of PL/SQL
7. Creation of Procedures
8. Creation of Functions
9. Implementation Of Triggers In
RDBMS
Database Design Using ER
10.
Modeling, Normalization
2
Exp.No:1
STUDY OF DDL AND DML COMMANDS
Date:
AIM:
To execute the Data Definition Language (DDL) commands and Data
Manipulation Language (DML) Commands.
3
Syntax:
truncate table tablename;
5. DROPPING A TABLE
This command is used to remove a table from the database.
Syntax: drop table tablename;
2. SELECT COMMANDS
1. Select all rows from a table.
This select command is used to retrieve all the values stored in the table.
Syntax: select * from tablename;
Select column name(s) from tablename;
Select distinct column name from tablename;
2. Select using where command:
This select command is used to retrieve the particular field values, stored
in the table, which satisfy a required condition.
Syntax: select column name(s) from tablename where search condition;
select * from tablename where search condition;
4
3. UPDATE COMMAND
This command is used to update (changing values in) one or two columns
of a row in a table. Specific rows can be updated based on some condition.
Syntax:
update tablename set column1=expression, column 2=expression, ……,
column n=expression;
update tablename set column1=expression, column 2=expression, ……,
column n=expression where search condition;
4. DELETE COMMAND
A delete query is expressed in much the same way as Query. We can delete whole
tuple (rows) we can delete values on only particulars attributes.
1.Deletion of all rows:
Syntax delete from tablename ;
5
RENAME COMMAND
OUTPUT
1. Create EMP table.
SQL>create table emp(empno number(4), ename varchar2(10), job varchar2(9), mgr
number(4), hiredate date, sal number(7,2), comm Number(7,2), deptno number(3), age
number(3), esal number(10));
6
6. List all employee details.
SQL>select * from emp;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO AGE ESAL
----------- ---------- ------ -------- ---------------- ------ ---------- ------------- ------ ----
7369 SMITH CLERK 7902 17-DEC-80 800 0 20 25 0
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30 25 0
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30 25 0
7566 JONES MANAGER 7839 02-APR-81 2975 500 20 25 0
7698 BLAKE MANAGER 7839 01-MAY-81 2850 1400 30 25 0
7. List all dept details
SQL>select * from dept;
DEPTNO DNAME LOC
------------ ------------ --------
10 accounting New york
20 research Dallas
30 Sales Chicago
40 operations Boston
7
CLERK
MANAGER
SALESMAN
3 rows selected.
12. Alter emp table to add city column which is of string data type.
SQL>Alter table emp add city varchar2(20);
Table altered
14. Update the salary of the employee as 2500 whose job as manager.
SQL>update emp set esal=2500 where job =‘manager’;
RESULT:
Thus the DDL and DML commands are executed successfully.
8
Exp.No:1a
STUDY OF DCL & TCL COMMANDS IN RDBMS
Date:
AIM:
To study Data Control Language statements and Transactional Control Language
statements.
9
DATA CONTROL LANGUAGE:
Data control language, the previous user with privileges commands the database
object (table, view, etc) of a user can’t be accessed by another user without the
permission of a user. The owner can allow other user to access his object as per his
diversion the permission given by a user to another is called privilege.
The Data Control Commands are:
i. GRANT Privilege
ii. REVOKE Privilege
Types of Privilege:
A permission granted to execute the various data definition command like Create
Table, Create Sequence, create session are called System Privilege.
Granting System Privilege:
Grant Command is used to give System Privilege to an oracle user.
Syntax:
GRANT system privilege TO user;
Object Privilege:
An Object Privilege enables a user to execute some commands on the database
object like table view sequence etc.
• Object privileges vary from object to object.
• An owner has all the privileges on the object.
• An owner can give specific privileges on that owner’s object.
Some of the object privileges are
i. Alter
ii. Insert
iii. Update
iv. Delete
v. Select
Syntax:
GRANT object_priv [(columns)]
ON object
TO {user|role|PUBLIC}
[WITH GRANT OPTION];
10
object_priv -- is an object privilege to be granted
ALL --specifies all object privileges
columns --specifies the column from a table or view on which privileges are
granted
ON object -- is the object on which the privileges are granted
TO --identifies to whom the privilege is granted
PUBLIC --grants object privileges to all users
WITH GRANT OPTION --allows the grantee to grant the object privileges to other users and
roles.
Example:
• Grant query privileges on the EMPLOYEES table.
GRANT select ON employees TO itc20,itc30;
Grant succeeded.
Syntax:
REVOKE {privilege [, privilege...]|ALL}
ON object
FROM {user[, user...]|role|PUBLIC}
[CASCADE CONSTRAINTS];
Example:
REVOKE select, insert ON departments FROM itc20;
Revoke succeeded.
11
OUTPUT :
TCL
SQL> desc stud;
Name Null? Type
----------------------------------------- -------- ----------------------------
SNO NUMBER(3)
SNAME VARCHAR2(10)
BRANCH VARCHAR2(4)
12
SQL> select * from stud;
SNO SNAME BRAN
---------- ---------- ----
1 Arun cse
2 babu IT
SQL> savepoint s1;
Savepoint created.
SQL> insert into stud values(04,'Devi','CSE');
1 row created.
SQL> select * from stud;
SNO SNAME BRAN
---------- ---------- ----
1 Arun cse
2 babu IT
4 Devi CSE
DCL
User it2a40:
SQL> grant all on student to it2a36;
Grant succeeded.
User it2a36:
SQL> select * from it2a40.student;
13
ROLL_NO NAME DEPT SEM1 SEM2 SEM3
---------- ------------ ---------- ---------- ---------- ----------
1 alex ece 92.3 90.5 89.3
2 bala ece 88.2 85 89.3
3 booba it 91.1 85 93
insert into it2a40.student values(&roll_no,'&name','&dept',&sem2,&sem2,&sem3);
Enter value for roll_no: 4
Enter value for name: chitra
Enter value for dept: it
Enter value for sem2: 88.5
Enter value for sem2: 90
Enter value for sem3: 92
old 1: insert into it2a40.student
values(&roll_no,'&name','&dept',&sem2,&sem2,&sem3)
new 1: insert into it2a40.student values(4,'chitra','it',88.5,90,92)
1 row created.
SQL> select * from it2a40.student;
ROLL_NO NAME DEPT SEM1 SEM2 SEM3
---------- --------------- ---------- ---------- ---------- ----------
4 chitra it 88.5 90 92
1 alex ece 92.3 90.5 89.3
2 bala ece 88.2 85 89.3
3 booba it 91.1 85 93
SQL> alter table it2a40.student add(avg number(10,3));
Table altered.
SQL> update it2a40.student set avg=91.2 where roll_no=1;
1 row updated.
SQL> update it2a40.student set avg=88.5 where roll_no=2;
1 row updated.
SQL> update it2a40.student set avg=89.9 where roll_no=3;
1 row updated.
14
SQL> update it2a40.student set avg=90.2 where roll_no=4;
1 row updated.
User it2a40:
SQL> revoke delete on student from it2a36;
Revoke succeeded.
User it2a36:
SQL> delete from it2a40.student where roll_no=2;
delete from it2a40.student where roll_no=2
*
ERROR at line 1:
ORA-00942: table or view does not exist
User it2a40:
SQL> revoke all on student from it2a36;
15
Revoke succeeded.
User it2a36:
SQL> select * from it2a40.student;
select * from it2a40.student
User it2a40:
SQL> grant select on student to it2a36;
Grant succeeded.
User - it2a36:
SQL> select * from it2a40.student;
ROLL_NO NAME DEPT SEM1 SEM2 SEM3 AVG
---------- --------------- ---------- ---------- ---------- ----------------------------------------
1 alex ece 92.3 90.5 89.3 91.2
2 bala ece 88.2 85 89.3 88.5
3 booba it 91.1 85 93 89.9
User it2a40:
SQL> revoke select on student from it2a36;
Revoke succeeded.
RESULT:
Thus the study of DCL commands and TCL commands was performed
successfully.
16
Exp.No:2 DATABASE QUERYING-SIMPLE QUERIES, NESTED
Date: QUERIES, SUB QUERIES AND JOINS
AIM:
To query simple, nested, sub queries and joins
SET OPERATIONS:
The SET operators combine the results of two or more component queries into
one result. Queries containing SET operators are called compound queries. Some of set
operators are,
UNION - Rows of first query plus rows of second query
UNION ALL - Rows of first query plus rows of second query, including all duplicates
INTERSECT – common rows from all queries
MINUS - All distinct rows that are selected by the first SELECT statement and not
selected in the second SELECT statement
Syntax:
select query set operator select query
JOINS:
An SQL join clause combines records from two or more tables in a database. It
creates a set that can be saved as a table or used as is. A JOIN is a means for combining
fields from two tables by using values common to each. ANSI standard SQL specifies
four types of Joins: INNER, OUTER, LEFT, and RIGHT. As a special case, a table (base
table, view, or joined table) can JOIN to itself in a self-join.
A programmer writes a JOIN predicate to identify the records for joining. If the
evaluated predicate is true, the combined record is then produced in the expected format,
a record set or a temporary table.
SQL specifies two different syntactical ways to express joins: "explicit join
notation" and "implicit join notation".
The "explicit join notation" uses the JOIN keyword to specify the table to join,
and the ON keyword to specify the predicates for the join.
17
The "implicit join notation" simply lists the tables for joining (in the FROM
clause of the SELECT statement), using commas to separate them
Inner Join
Inner join creates a new result table by combining column values of two tables (A
and B) based upon the join-predicate. The query compares each row of A with each row
of B to find all pairs of rows which satisfy the join-predicate. When the join-predicate is
satisfied, column values for each matched pair of rows of A and B are combined into a
result row. The result of the join can be defined as the outcome of first taking the
Cartesian product (or Cross join) of all records in the tables (combining every record in
table A with every record in table B)—then return all records which satisfy the join
predicate. Inner join is further classified as equi-joins, as natural joins, or as cross-joins
Syntax:
Explicit Notation:
Select * from table name1 inner join table name2 on table1.fieldname=table2.fieldname;
Select * from table1 inner join table2 using(fieldname);
Implicit Notation
Select * from table1, table2 where table1.fieldname=table2.fieldname;
Equi Join
Syntax:
Explicit Notation:
18
names in the joined tables. The resulting joined table contains only one column for each
pair of equally-named columns
Explicit Notation:
Select * from table1 natural join table2 on table1.fieldname=table2.fieldname;
Cross join
Cross Join returns the Cartesian product of rows from tables in the join. In other
words, it will produce rows which combine each row from the first table with each row
from the second table.
Explicit Notation:
Select * from table1 cross join table2 ;
Implicit Notation
Select * from table1,table2;
Outer joins
An outer join does not require each record in the two joined tables to have a
matching record. The joined table retains each record—even if no other matching record
exists. Outer joins subdivide further into left outer joins, right outer joins, and full outer
joins, depending on which table(s) one retains the rows from (left, right, or both).
The result of a left outer join (or simply left join) for table A and B always
contains all records of the "left" table (A), even if the join-condition does not find any
matching record in the "right" table (B). This means that a left outer join returns all the
values from the left table, plus matched values from the right table (or NULL in case of
no matching join predicate).
Explicit Notation:
Select * from table1 left outer join table2 on table1.fieldname=table2.fieldname
19
Implicit Notation
A right outer join (or right join) closely resembles a left outer join, except with the
treatment of the tables reversed. Every row from the "right" table (B) will appear in the
joined table at least once. If no matching row from the "left" table (A) exists, NULL will
appear in columns from A for those records that have no match in B.
Explicit Notation:
Select * from table1 right outer join table2 on table1.fieldname=table2.fieldname
Implicit Notation
Conceptually, a full outer join combines the effect of applying both left and right
outer joins. Where records in the FULL OUTER JOINed tables do not match, the result
set will have NULL values for every column of the table that lacks a matching row.
Explicit Notation:
Select * from table1 full outer join table2 on table1.fieldname=table2.fieldname
Self-join
A self-join is joining a table to itself means each row of the table is combined
with itself and with every other row of the table. The self join is viewed as join of two
copies of the same table.
20
SET OPERATIONS
1. Display the different designation in department 20 and 30.
SQL> select designation from emp where deptno=20
union
select designation from emp where deptno=30;
SQL> select designation from emp where deptno=20 union all select designation from
emp where deptno=30;
(Or)
SQL> select designation from emp where deptno=20 minus select designation from emp
where deptno in (10,30);
JOINS:
Tables:
SQL> create table two(deptno number(4) primary key,deptname varchar(10));
Table created.
3 rows selected.
21
Inner join
i.SQL> select * from one, two where one.deptno=two.deptno;
Equi join
i.SQL> select * from one join two on one.deptno=two.deptno;
Natural join
i.SQL> select * from one natural join two;
Cross Join
i.SQL> select * from one cross join two;
Self join
SQL> create table selfj(empno number(5),ename varchar(7),mgr number(5));
Table created.
22
List out the names of manager with the employee record.
SQL> select worker.ename,manager.ename from selfj worker,selfj manager where
worker.mgr=manager.empno;
SUBQUERIES
A subquery is a SELECT statement that is embedded in a clause of another
SELECT statement. You can build powerful statements out of simple ones by using
subqueries. A Common use of subquery is to perform tests for
1.set memberships,
2.setcomparisons
3.set cardinality.
The subquery (inner query) executes once before the main query.
The result of the subquery is used by the main query (outer query).
A subquery must be enclosed in parentheses.
Place the subquery on the right side of the comparison condition for readability.
Subquery Syntax
SELECT select_list FROM table WHERE expr operator (SELECT select_list FROM
table);
Types of Subqueries
• Single-row subqueries: Queries that return only one row from the inner SELECT
statement
• Multiple-row subqueries: Queries that return more than one row from the inner
SELECT Statement.
23
A single-row subquery
Subqueries that returns one row from the inner SELECT statement. This type of
subquery uses a single-row operator.
Multiple-Row Subqueries
Subqueries that return more than one row are called multiple-row subqueries. You
use a multiple-row operator, instead of a single-row operator, with a multiple-row
subquery. The multiple-row operator expects one or more values.
QUERIES:
1.Select loanno, branchname, amount from loan where amount=(select min(amount) from
loan)
2. Select sname, rollno, dept, marks from student where marks=(select min(marks) from
student group by dept;
3. Select sname, rollno, dept, marks from student where marks IN (select min(marks)
from student group by dept)
4. Select sname, rollno, dept, marks from student where marks NOT IN (select
min(marks) from student)
24
5. select * from loan where amount > ANY (select amount from loan where
branchname=’chennai’)
6. select * from loan where amount > ALL (select amount from loan where
branchname=’chennai’)
8. select * from loan where NOT EXISTS (select * from borrower where
loan.loanno=borrower.loanno)
10. Find all customers who have both an account and a loan at the bank.
Select distinct cusname from customer where cusname IN (select cusname from
depositor)
11. Find all customers who have a loan at the bank but do not have an account at
the bank.
Select distinct cusname from customer where cusname NOT IN (select cusname from
depositor)
12. Find the loanno,amount,branchname who have get second maximum loan
amount at the bank.
Select loanno, branchname, max(amount) from loan where amount<=(select
max(amount) from loan )
13. Write a query that displays the roll numbers and student names of all student
who studied in a department with any student whose name contains a S.
SELECT rollno, sname FROM student WHERE dept IN (SELECT dept FROM student
WHERE sname like ’%s%’);
14. List the employee names whose salary is greater than the lowest salary of an
employee belonging to department number 30.
SQL> select ename from emp
where sal>any
(select sal from emp where deptno=30);
15. List the employee details of those employees whose salary is greater than any of
the salesman.
SQL> select empno, ename, sal from emp where sal>any(
select sal from emp where job='asstprof');
25
16. List the employee names whose salary is greater than the highest salary of an
employee belonging to department number 20.
SQL> select ename from emp
where sal>all(select sal from emp where deptno=20);
RESULT:
Thus the database querying for simple, nested, sub queries and joins were
performed successfully.
26
Exp.No:3
VIEWS, SEQUENCES, SYNONYMS
Date:
AIM:
To study about views, sequences, synonyms and execute them.
Views
(i) Logically represents subsets of data from one or more tables.
(ii) You can present logical subsets or combinations of data by creating views of tables. A
view is a logical table based on a table or another view. A view contains no data of its
own but is like a window through which data from tables can be viewed or changed. The
tables on which a view is based are called base tables. The view is stored as a SELECT
statement in the data dictionary.
Why Use Views?
• To restrict data access
• To make complex queries easy
• To provide data independence
• To present different views of the same data.
Advantages of Views
1. Data security
2. Simplicity
3. Structural Simplicity
Simple Views versus Complex Views
There are two classifications for views: simple and complex. The basic difference is
related to the DML (INSERT, UPDATE, and DELETE) operations.
• Simple view
– Derives data from only one table
– Contains no functions or groups of data
– Can perform DML operations through the view
• Complex view
– Derives data from many tables
– Contains functions or groups of data
27
– Does not always allow DML operations through the view
Creation of Views:
Syntax
CREATE VIEW viewname AS
SELECT columnname1, columnname2
FROM tablename
WHERE columnname=expression_list;
Example:
CREATE VIEW empvu80
AS SELECT employee_id, last_name, salary
FROM employees
WHERE department_id = 80;
View created.
Example:
* Create a view by using column aliases in the
subquery.
Modifying a View
QUERIES:
1. Create view on emp table whose sal is less than 2000.
SQL>create view salamt_view as select * from emp where sal<2000;
2. Create a view dept_view on dept table and rename the columns as dno,
deptname,location respectively.
SQL>create view dept_view as select deptno, dname, loc from dept;
3. Select the employee names from salamt_view whose job is assistant prof.
SQL>select name from salamt_view where trim(job)='Asstprof';
4. Drop the view salamt_view.
SQL>drop view salamt_view;
29
SEQUENCES
Oracle provides the capability to generate sequences of unique numbers, and they
are called sequences.
Just like tables, views, indexes, and synonyms a sequence is a type of database
object.
Sequences are used to generate unique, sequential integer values that are used as
primary key values in database tables.
The sequences of numbers can be generated in either ascending or descending
order.
QUERIES:
Creation of table
SQL>create table class(name varchar(10),id number(10));
Table created.
Inserting values
SQL>insert into class values(‘&name’,&id);
Enter value for name: anu
Enter value for id:1
Old 1:insert into class values(‘&name’,’&id)
New 1:insert into class values(‘anu’,1)
1 row created.
SQL>/
Enter value for name: brindha
Enter value for id:2
Old 1: insert into class values(‘&name’,’&id)
New 1: insert into class values(‘brindha’,2)
1 row created.
SQL>/
Enter value for name: chinna
Enter value for id:3
Old 1: insert into class values(‘&name’,’&id)
New 1: insert into class values(‘chinna’,3)
1 row created.
30
Create sequence
SQL> create sequence S
starts with 4
increment by 1
maxvalue 100
cycle;
sequence created.
SQL>insert into class values(‘diya’,s.nextval);
1 row created.
SQL> select * from class;
Name id
--------------------
Anu 1
Brindha 2
China 3
Diya 4
Alter sequence
SQL> alter sequence s
increment by 2;
sequence altered.
SQL>insert into class values(‘www’,s.nextval);
1 row created.
SQL> select * from class;
Name id
--------------------
Anu 1
Brindha 2
China 3
Diya 4
www 6
DROP SEQUENCE
SQL> drop sequence s;
Sequence dropped.
SYNONYMS
A synonym is an alias, that is, a form of shorthand used to simplify the task of
referencing a database object.
There are two categories of synonyms, public and private.
A synonym is an alternative name for objects such as tables, views, sequences,
stored procedures, and other database objects.
You generally use synonyms when you are granting access to an object from
another schema and you don't want the users to have to worry about knowing which
schema owns the object.
31
Queries:
Name id
--------------------
Anu 1
Brindha 2
China 3
Diya 4
www 6
kalai 20
8 rows selected.
Drop synonym
SQL> drop synonym c1;
Synonym dropped.
RESULT:
Thus the SQL commands for views, sequences, and synonyms were executed and
the outputs were verified.
32
Exp.No:4 DATABASE PROGRAMMING:IMPLICIT AND EXPLICIT
Date: CURSORS
AIM:
To study about implicit and explicit cursors and execute them.
INTRODUCTION
A cursor is a pointer to this context area. PL/SQL controls the context area
through a cursor. A cursor holds the rows (one or more) returned by a SQL statement.
The set of rows the cursor holds is referred to as the active set.
You can name a cursor so that it could be referred to in a program to fetch and process
the rows returned by the SQL statement, one at a time. There are two types of cursors
Implicit cursors
Explicit cursors
Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement
is executed, when there is no explicit cursor for the statement. Programmers cannot
control the implicit cursors and the information in it.
PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor,
which always has attributes such as %FOUND, %ISOPEN, %NOTFOUND,
and %ROWCOUNT. The SQL cursor has additional
attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed for use
with the FORALL statement.
The following table provides the description of the most used attributes –
33
S.NO ATTRIBUTE & DESCRIPTION
1.
%FOUND
Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one
or more rows or a SELECT INTO statement returned one or more rows.
Otherwise, it returns FALSE.
2.
%NOTFOUND
The logical opposite of %FOUND. It returns TRUE if an INSERT,
UPDATE, or DELETE statement affected no rows, or a SELECT INTO
statement returned no rows. Otherwise, it returns FALSE.
3.
%ISOPEN
Always returns FALSE for implicit cursors, because Oracle closes the SQL
cursor automatically after executing its associated SQL statement.
4.
%ROWCOUNT
Returns the number of rows affected by an INSERT, UPDATE, or DELETE
statement, or returned by a SELECT INTO statement.
Example
We will be using the CUSTOMERS table we had created and used in the
previous chapters.
QUERIES
Creating table:
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
6 customers selected
PL/SQL procedure successfully completed.
If you check the records in customers table, you will find that the rows have been updated
−
Select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |
Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over the
context area. An explicit cursor should be defined in the declaration section of the
PL/SQL Block. It is created on a SELECT Statement which returns more than one row.
Syntax
CURSOR cursor_name IS select_statement;
35
Working with an explicit cursor
includes the following steps −
Declaring the cursor for initializing the memory
Opening the cursor for allocating the memory
Fetching the cursor for retrieving the data
Closing the cursor to release the allocated memory
CURSOR c_customers IS
SELECT id, name, address FROM customers;
OPEN c_customers;
Fetching the Cursor
Fetching the cursor involves accessing one row at a time. For example, we will fetch
rows from the above-opened cursor as follows −
FETCH c_customers INTO c_id, c_name, c_addr;
PROGRAM
DECLARE
c_id customers.id%type;
c_name customerS.No.ame%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
36
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
Output
1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP
PL/SQL procedure successfully completed.
RESULT:
Thus the database programming for implicit cursors and explicit cursors were
executed successfully.
37
Exp.No:5
STUDY OF FUNCTIONS IN RDBMS
Date:
AIM:
To Study single row functions (character, numeric, date functions), group
functions and operators in RDBMS.
String Functions:
Function Description
CONCAT(string1, string2) Concatenates two strings
INITCAP(string) Returns strings with first letter in upper case
LENGTH (string) Returns an integer representing the string length
LTRIM(string,serachSrting) Remove character from left/ right of char
RTRIM(string,serachSrting)
UPPER(string) Returns string with all upper/ lower case characters
Lower(string)
SUBSTR(string,start,length) Returns substring starting at start &of specified length
REPLACE(string,searchstring,replacement) REPLACE returns char with every
occurrence of search String replacement String
DateFunctions:
Function Description
SYSDATE Returns current date
ADD_MONTHS Returns date retrieved date added to specified month
LAST_DAY (Date) Returns date that is last day of the month
MONTHS_BETWEEN( Date1,Date2) Returns months between two dates specified months
38
DATE FUNCTIONS
CHARACTER FUNCTIONS
39
NUMERIC FUNCTIONS
40
GROUP FUNCTIONS & OPERATORS
1. List all employee names and their salaries, whose salary lies between
1500/- and 3500/- both inclusive.
SQL>select ename from emp where salary between 1500 and 3500;
4. List all employee names and jobs, whose job title includes M or P.
SQL>select ename, designation from emp where designation like ‘M%’ or job
like ‘P%’;
41
7. List all employee names , salary and 15% rise in salary.
SQL>select ename , salary , salary+0.15* salary from emp;
10. What is the difference between maximum and minimum salaries of employees in
the organization?
SQL>select max(salary)-min(salary) from emp;
11. Find how much amount the company is spending towards salaries.
SQL>select sum (salary) from emp;
42
SQL> select dname, count (ename) from emp, dept where
emp.deptno=dept.deptno
group by dname;
19. List the employee name and hiredate in descending order of hiredate.
SQL> select ename, hiredate as doj from emp order by 2 desc;
20.List the job and salary of employees job wise for department number 30 and
display only those rows having salary greater than 1500 .
SQL> select designation, salary from emp where deptno=30 group by designation
having salary >1500;
RESULT:
Thus the study of single row functions, group functions were performed
successfully.
43
Exp.No:6
STUDY OF PL/SQL
Date:
Aim:
To study the basics of PL/SQL.
Every unit of PL/SQL comprises one or more blocks. These blocks can be entirely
separate or nested one within another. The basic units (procedures, functions, and
anonymous blocks) that make up a PL/SQL program are logical blocks which can contain
any number of nested sub-blocks. Therefore one block can represent a small part of
another block, which in turn can be part of the whole unit of code.
Identifiers/Variables:
44
Declare variables belonging to scalar, reference, composite and large object
(LOB) data types.
Declare variables dynamically based on the data structure of tables and columns
in the database.
DECLARE [Optional]
Variables, cursors, user defined exceptions
BEGIN [Mandatory]
- SQL Statements –
- PL/SQL Statements –
Exception [Optional]
-- Actions to be performed when errors occur ----
END [Mandatory];
Anonymous:
- No name.
- Starts with DECLARE statement.
Procedure:
- No return.
- PROCEDURE name IS
Function:
- Returns a value
- FUNCTION name RETURN data-type IS
Programming Constructs:
Declaring Variables:
Assignment:
Identifier := expr;
IF Statement:
IF condition THEN
Statements;
45
[ELSE IF condition THEN
Statements;]
[ELSE
Statements;]
END IF;
CASE Statement:
CASE selector
WHEN expression1 THEN result1
WHEN expression2 THEN result2
....
....
WHEN expression THEN resultn
[ELSE resultn1;]
END;
BASIC Loops:
LOOP
Statement 1;
....
....
EXIT [WHEN condition];
END LOOP;
WHILE Statement:
WHILE condition LOOP
Statement1;
....
....
END LOOP;
FOR Statement:
FOR counter IN [REVERSE]
Lower_bound..upper_bound LOOP
Statement1;
....
....
END LOOP;
RESULT:
Thus the basics of PL/SQL was studied
46
Exp.No:6a
IMPLEMENTATION OF PL/SQL
Date:
AIM:
To implement the PL/SQL block that satisfy some conditions by accepting input
from the user.
47
iii.)Write a program in PL/SQL for Reverse of a Number
declare
n number;
rev number:=0;
r number;
begin
n:=&n;
while n>0
loop
r:=mod(n,10);
rev:=(rev*10)+r;
n:=trunc(n/10);
end loop;
dbms_output.put_line('reverse is '||rev);
end;
/
Enter value for n: 1235
old 8: n:=&n;
new 8: n:=1235;
reverse is 5321
RESULT:
Thus the PL/SQL programs were written and executed to accept the input from
the users.
48
Exp.no:7
CREATION OF PROCEDURES
Date:
Aim:
To create and implement the PL/SQL procedures.
QUERIES:
i.)Create a stored procedure which takes empno as parameter, and display the name
and job of the employee.
SQL>create or replace procedure emppro(eno in number)is
begin
for v in (select * from emp where empno=eno)
loop
dbms_output.put_line('Name: '||v.ename||' Designation: '||v.designation);
end loop;
end;
/
Procedure created.
OUTPUT:
SQL> exec emppro('7369');
Name: Smith Designation:Clerk
ii.)Create a stored procedure which takes employee’s job as parameter, and display
the details of the all employees with salary greater than max salary.
create or replace procedure max(s in varchar2)is
begin
for v in (select * from emp where sal>
all(select sal from emp where job=s))
loop
dbms_output.put_line('Name: '||v.ename||' Salary: '||v.sal);
end loop;
end;
/
Procedure created.
OUTPUT:
SQL> exec max('Salesman');
Name: jones Salary: 2975
Name: blake Salary: 2850
PL/SQL procedure successfully completed.
49
iii.)Create a procedure that location for the given department number.
create or replace procedure loc(no in number)is
begin
for v in (select * from dept where deptno=no)
loop
dbms_output.put_line('Department Number: '||v.deptno||'Location: '||v.loc);
end loop;
end;/
Procedure created.
declare
no number;
begin
no:=&a;
loc(no);
end;/
Enter value for a: 10
old 4: no:=&a;
new 4: no:=10;
Department Number:10 Location: New york
PL/SQL procedure successfully completed.
Result:
50
Exp.no:8
CREATION OF FUNCTIONS
Date:
Aim:
To create and implement the PL/SQL functions.
QUERIES:
declare
n number(2);
begin
n:=&a;
dbms_output.put_line('Number is '||nochk(n));
end;
/
Enter value for a: 19
old 4: n:=&a;
new 4: n:=19;
Number is Odd
PL/SQL procedure successfully completed.
51
end;
/
OUTPUT:
function created.
F1 (3)
300
iii.)
SQL> create or replace function F2 (a number)
return char is
o varchar 2(25):= ‘The number is odd’;
e varchar 2(25):= ‘The number is even’;
r number;
begin
r: = mod (a, 2);
if r=0 then return e;
else
return o;
endif;
end;
/
OUTPUT:
function created.
F2 (9)
The number is odd.
iv.) Create a procedure to update the salary for the employee based on their job. The
main procedure should contain update statement. The main procedure should call
second procedure that contain rate of employee.
SQL>create or replace function rate_sub(s in varchar2)return number is
rate number(2);
begin
if(trim(s)='clerk') then
rate:=0.2;
else
rate:=0.1;
52
end if;
return rate;
end;/
Function created.
Main Procedure:
create or replace procedure rate_main(s in varchar2) is
rate number(2);
begin
for a in(select * from emp where job=s)
loop
rate:=rate_sub(s);
update emp set sal=sal+(sal*rate) where job=s;
dbms_output.put_line('Name: '||a.ename||' Salary: '||a.sal);
end loop;
end;
/
Procedure created.
OUTPUT:
SQL> exec rate_main('salesman');
Name: Allen Salary: 1600
Name: Ward Salary: 1250
Result:
Thus the above given queries were solved using functions.
53
Exp.No:9
IMPLEMENTATION OF TRIGGERS IN RDBMS
Date:
AIM:
To implement the concept of Trigger.
Database Triggers:
Database triggers are procedures that are stored in the database and are implicitly
executed (fired) when the contents of a table are changed.
Types of Triggers:
54
2. Before Row Trigger:
Before modifying the each row affected by the triggering statement and before appropriate
integrity constraints, the trigger is executed if the trigger restriction either evaluated to
TRUE or was not included.
3. After Statement Trigger:
After executing the triggering statement and applying any deferred integrity constraints,
the trigger action is executed.
4. After row Trigger:
After modifying each row affected by the triggering statement and possibly applying
appropriate integrity constraints, the trigger action is executed for the current row if the
trigger restriction either evaluates to TRUE or was not included.
Elements in a Trigger:
Trigger timing
o For table: BEFORE, AFTER
o For view: INSTEAD OF
Trigger event: INSERT, UPDATE, OR DELETE
Table name: On table, view
Trigger Type: Row or statement
When clause: Restricting condition
Trigger body: PL/SQL block
“Before triggers” execute the trigger body before the triggering DML event on a
table. These are frequently used to determine whether that triggering statement should be
allowed to complete. This situation enables you to eliminate unnecessary processing of the
triggering statement and it eventual rollback in cases where an exception is raised in the
triggering action.
“After triggers” are used when the triggering statement is to be completed before
the triggering action and to perform a different action on the same triggering statement if a
BEFORE trigger is already present.
“Instead of Triggers” are used to provide a transparent way of modifying views
that cannot be modified directly through SQL DML statements because the view is not
inherently modifiable. You can write INSERT, UPDATE, and DELETE statements
55
against the view. The INSTEAD OF trigger works invisibly in the background performing
the action coded in the trigger body directly on the underlying tables.
Triggering user events:
o INSERT
o UPDATE
o DELETE
Trigger Components:
o Statement: The trigger body executes once for the triggering event. This is the
default. A statement trigger fires once, even if no rows are affected at all.
o Row: The trigger body executes once for each row affected by the triggering
event. A row trigger is not executed if the triggering event affects no rows.
Trigger Body:
PROGRAM (A):
Create a trigger which displays an error message when the employee records with
salary greater than 2000 are deleted.
56
before delete on emp
referencing old as nrow
for each row
when(nrow.salary >2000)
begin
raise_application_error(-20001,'Salary greater than 2000');
end;
/
Trigger created.
PROGRAM (B):
Create a trigger which displays message whenever anyone attempts to change dept
table.
1 row updated.
PROGRAM (C):
INPUT:
EMP
EMPNO SALARY
10 0
11 1000
12 1200
SALDET
57
EMPNO DEPT TOTAL
10 11 900
EMPNO SALARY
10 1000
11 1000
12 1200
SALDET
RESULT:
Thus triggers were implemented successfully.
58
Exp.No:10 DATABASE DESIGN USING ER MODELING,
Date: NORMALIZATION
AIM:
To implement any application using ER model and normalization.
ER diagram:
Chen Notation
Chen Notation
Representing Relationships
1:1 Relationships. The key of one relation is stored in the second relation. Look at
example queries to determine which key is queried most often.
1:N Relationships.
Parent - Relation on the "1" side.
Child - Relation on the "Many" side.
Represent each Entity as a relation.
59
Copy the key of the parent into the child relation.
CUSTOMER (CustomerID (key), Name, Address, ...)
ORDER (OrderNum (key), OrderDate, SalesPerson, CustomerID (fk))
Chen Notation
RESULT:
Thus the ER Database design using E-R model and Normalization was
implemented successfully.
60
Exp.No:11
DESIGN AND IMPLEMENTATION OF BANKING SYSTEM.
Date:
AIM:
To design and implement banking system using visual basic 6.0.
Connectivity:
i. Open the VB 6.0 in standard exe form and right circle in the tool box select components.
ii. Select MS ADO data control 6.0 (SP4) OLEDB in component list.
iii. Right click over ADODC control and select the properties.
iv. Select MSOLE DB provides for ODBC drivers in provider..
Algorithm:
1. Place all the controls in the form as shown.
2. To place the ADO controls do the following procedure.
3. Go to project Component.
4. Select the checkbox showing “MICROSOFT ADO DATA CONTROL”and Press
apply close.
5. Place the ADO control on the form.
6. Create a table in SQL plus and insert some values in it.
7. Now type the command ‘commit;’ and return back to VB.
8. Select the ADO control and click the right mouse select ADODC properties.
9. A dialog box will appear, press the build button. Select ‘Microsoft OLEDB
provider for oracle” press next button”.
10. In the connection tab, give the server name, user name and password.
11. Press the” TEST CONNECTION” button. A message box will appear if the steps
were followed correctly. Press OK button.
12. Select authentication tab. Give the username and password again. Select record
source tab. In the table or stored procedure name control box, select the name and give
OK.
13. Now select the text buttons one by one and in the properties window set the data
sources combo box to point to ADODC1.select the corresponding fields of the text box in
the data fields combo box
14. Write the coding for command buttons and run the form.
61
Data report :
1. Go to Project->Components->Designers->Data Report,Data Environment and click
Apply,then OK.
4. In Data Environment1,
Right Click on Connection1->Add Command-> Command1
6. Drag Command1 into Detail Section of Data Report1 and Make Alignments
Database Schema:
FORM DESIGN:
Form1
62
Dim con As New ADODB.Connection
Dim rec As New ADODB.Recordset
Private Sub Command1_Click()
Form3.Show
End Sub
63
Form2
64
Form4.Show
Else
If Val(Label10.Caption) >= 501 Then
If Val(Label10.Caption) - Val(Text6.Text) >= 500 Then
Label10.Caption = Val(Label10.Caption) - Val(Text6.Text)
con.Execute "update det1 set amt='" & Label10.Caption & "' where accno='" &
Combo1.Text & "'"
MsgBox ("sucessfully debited")
Else
MsgBox "min amt is 500", vbCritical, "below 500"
End If
Else
MsgBox "min amt is 500", vbCritical, "below 500"
End If
End If
End If
accept.Enabled = False
End Sub
65
Text2.Text = rec.Fields(2)
Text3.Text = rec.Fields(4)
Text4.Text = rec.Fields(3)
Text5.Text = rec.Fields(5)
End Sub
66
rec.MoveLast
End If
showrec
End Sub
Form3
67
con.Execute "insert into det1 values('" & Text1.Text & "','" & Text2.Text & "','" &
Val(Text3.Text) & "','" & Text4.Text & "','" & Text5.Text & "','" & Val(Text6.Text) &
"')"
MsgBox "record updated", vbInformation, "ok"
Unload Me
End Sub
68
DataReport
RESULT:
Thus the Banking system was successfully designed using VB6.0 and ORACLE.
69