0% found this document useful (0 votes)
201 views107 pages

DBMS Record

The document appears to be a lab manual for a Database Management Systems course. It contains a list of 12 experiments covering topics like SQL commands, database design, stored procedures, triggers and database connectivity. The objectives of the course are to understand data definition, manipulation and queries, as well as functions, procedures and database applications.

Uploaded by

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

DBMS Record

The document appears to be a lab manual for a Database Management Systems course. It contains a list of 12 experiments covering topics like SQL commands, database design, stored procedures, triggers and database connectivity. The objectives of the course are to understand data definition, manipulation and queries, as well as functions, procedures and database applications.

Uploaded by

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

ARUNAI ENGINEERING COLLEGE

(Affiliated to Anna University)


Velu Nagar, Tiruvannamalai – 606 603
Phone: 04175-237419/236799/237739
www.arunai.org ISO 9001- 2000

DEPARTMENT OF INFORMATION
TECHNOLOGY

2018- 2019

FOURTH SEMESTER

CS8481 - DATABASE
MANAGEMENT SYSTEMS
LAB MANUAL

1
LIST OF EXPERIMENTS:

OBJECTIVES:

 To understand data definitions and data manipulation commands


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

1. Data Definition Commands, Data Manipulation Commands for inserting,


deleting, updating and retrieving Tables and Transaction Control statements
2. Database Querying – Simple queries, Nested queries, Sub queries and Joins
3. Views, Sequences, Synonyms
4. Database Programming: Implicit and Explicit Cursors
5. Procedures and Functions
6. Triggers
7. Exception Handling
8. Database Design using ER modeling, normalization and Implementation for
any application
9. Database Connectivity with Front End Tools
10. Case Study using real life database applications
CONTENTS

PAGE
EX.NO NAME OF THE EXPERIMENT
NO

1 STUDY OF BASIC SQL COMMANDS

2(a) STUDY OF SQL(DML&DCL) COMMANDS

2(b) STUDY OF SQL(TCL) COMMANADS AND OPERATORS

2( c) STUDY OF OTHER SPECIAL COMMANDS IN SQL

SQL COMMANDS FOR VIEWS, SYNONYMS, SEQUENCE,


3
INDEXES, SAVE POINT.

4
STUDY OF VARIOUS CONSTRAINTS IN SQL

CREATING THE RELATIONSHIP BETWEEN THE


5
DATABASES

6 STUDY OF PL/SQL BLOCKS

7 PL/SQL BLOCKS

8 PL/SQL BLOCK TO HANDLE THE EXCEPTION

9 PL/SQL PROCEDURES

10 TRIGGERS AND FUNCTIONS


PAGE
EX.NO NAME OF THE EXPERIMENT
NO
ODBC CONNECTIVITY USING ORACLE
11

12 HOSPITAL MANAGEMENT SYSTEM

INVENTORY CONTROL SYSTEM


13
SQL COMMANDS

TYPES OF COMMANDS

DDL (DATA DEFINITION LANGUAGE)

 CREATE

 ALTER

 DROP

 TRUNCATE

 COMMENT

 RENAME

1. COMMAND NAME: CREATE

COMMAND DESCRIPTION: CREATE command is used to create objects in database.

2. COMMAND NAME: ALTER

COMMAND DESCRIPTION: ALTER command is used to alter the structure of database.

3. COMMAND NAME: DROP

COMMAND DESCRIPTION: DROP command is used to delete the object from database.

4. COMMAND NAME: TRUNCATE

COMMAND DESCRIPTION: TRUNCATE command is used to remove all the records


in the table including the space allocated for the table.

5. COMMAND NAME: COMMENT

COMMAND DESCRIPTION: COMMENT command is used to add the comments to the table.

6. COMMAND NAME: RENAME

COMMAND DESCRIPTION: RENAME command is used to rename the objects.


COMMANDS EXECUTION

CREATION OF TABLE WITHOUT PRIMARY KEY


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

SQL> create table employee ( Employee_name varchar2(10),employee_no


number(8), dept_name varchar2(10),dept_no number (5),date_of_join date);

Table created.

TABLE DESCRIPTION
--------------------------------

SQL> desc employee;


Name Null? Type

EMPLOYEE_NAME VARCHAR2(10)
EMPLOYEE_NO NUMBER(8)
DEPT_NAME VARCHAR2(10)
DEPT_NO NUMBER(5)
DATE_OF_JOIN DATE

CREATION OF TABLE WITH PRIMARY KEY


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

SQL> create table employee1 (Employee_name varchar2(10),employee_no


number(8) primary key, dept_name varchar2(10), dept_no number (5),date_of_join
date);

Table created.

TABLE DESCRIPTION
--------------------------------

SQL> desc employee1;

Name Null? Type

EMPLOYEE_NAME VARCHAR2(10)
EMPLOYEE_NO NOT NULL NUMBER(8)
DEPT_NAME VARCHAR2(10)
DEPT_NO NUMBER(5)
DATE_OF_JOIN DATE
DROPPING PRIMARY KEY USING ALTER COMMAND
------------------------------------------------------------------------------
SQL> alter table employee1 drop primary key;
Table altered.

SQL> desc employee1;


Name Null? Type

EMPLOYEE_NAME VARCHAR2(10)
EMPLOYEE_NO NUMBER(8)
DEPT_NAME VARCHAR2(10)
DEPT_NO NUMBER(5)
DATE_OF_JOIN DATE

CREATING PRIMARY KEY USING ALTER COMMAND


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

SQL> alter table employee1 add primary key


(employee_no); Table altered.

SQL> desc employee1;


Name Null? Type

EMPLOYEE_NAME VARCHAR2(10)
EMPLOYEE_NO NOT NULL NUMBER(8)
DEPT_NAME VARCHAR2(10)
DEPT_NO NUMBER(5)
DATE_OF_JOIN DATE

SQL> alter table employee add primary key


(employee_no); Table altered.

SQL> desc employee;


Name Null? Type

EMPLOYEE_NAME VARCHAR2(10)
EMPLOYEE_NO NOT NULL NUMBER(8)
DEPT_NAME VARCHAR2(10)
DEPT_NO NUMBER(5)
DATE_OF_JOIN DATE
ASSIGNING COMMENTS FOR TABLE
-----------------------------------------------------
SQL> comment on table employee1 is 'EMPLOYEE DETAILS';
Comment created.

SQL> select comments from user_tab_comments;

COMMENTS

EMPLOYEE DETAILS

ASSIGNING COMMENTS FOR COLUMN


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

SQL> comment on column employee1.EMPLOYEE_NO is 'EMPLOYEE REGISTRATION


NUMBER';
Comment created.

SQL> select comments from USER_COL_COMMENTS;

COMMENTS

EMPLOYEE REGISTRATION NUMBER


3 rows selected.

RENAMING TABLE
----------------------------
SQL> Rename employee1 to emp;
Table renamed.

DROPPING OF TABLE
-------------------------------
SQL> drop table emp;
Table dropped.
SQL COMMANDS

DML (DATA MANIPULATION LANGUAGE)

 SELECT

 INSERT

 UPDATE

 DELETE

DCL (DATA CONTROL LANGUAGE)

 GRANT

 REVOKE

1. COMMAND NAME: INSERT

COMMAND DESCRIPTION: INSERT command is used to insert the values to the table.

2. COMMAND NAME: SELECT

COMMAND DESCRIPTION: SELECT command is used to display the table & table

values.

3. COMMAND NAME: UPDATE

COMMAND DESCRIPTION: UPDATE command is used to update the values

4. COMMAND NAME: DELETE


COMMAND DESCRIPTION: DELETE command is used to delete the constraint from the table

5. COMMAND NAME: GRANT

COMMAND DESCRIPTION: GRANT command is used to give user’s access privilege

to database.

6. COMMAND NAME: REVOKE

COMMAND DESCRIPTION: REVOKE command is used to withdraw access privilege given

with the grant.

7. COMMAND NAME: ALTER

COMMAND DESCRIPTION: ALTER command is used to alter the structure of database.


8. COMMAND NAME: MODIFY

COMMAND DESCRIPTION:MODIFY command is used to modify the values in the

Database.

COMMANDS EXECUTION

CREATION OF TABLE WITH PRIMARY KEY


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

SQL> create table employee1 (Employee_name varchar2(10),employee_no number(8)


primary key, dept_name varchar2(10), dept_no number (5),date_of_join date);

Table created.

INSERTION OF TABLE VALUES


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

SQL> insert into employee1 values ('Vijay',345,'CSE',21,'21-jun-2006');


1 row created.

SQL> insert into employee1 values ('Raj',98,'IT',22,'30-sep-2006');


1 row created.

SQL> insert into employee1 values ('Giri',100,'CSE',67,'14-nov-1981');


1 row created.

SQL> insert into employee1


(Employee_name,employee_no,dept_name,dept_no,date_of_join)values('Vishva',128,
'ECE',87,'25-dec-2006');

1 row created

SQL> insert into employee1 values ('Ravi',124,'ECE',89,'15-jun-2005');


1 row created.

SELECTION OR DISPLAY OF TABLE


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

SQL> select * from employee1;

EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_NO DATE_OF_J

Vijay 345 CSE 21 21-JUN-06


Raj 98 IT 22 30-SEP-06
Giri 100 CSE 67 14-NOV-81
Vishva 128 ECE 87 25-DEC-06
Ravi 124 ECE 89 15-JUN-05

UPDATE OF TABLE VALUES


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

SQL> update employee1 set employee_no=300 where


dept_no=67; 1 row updated.

SQL> select * from employee1;

EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_NO DATE_OF_J

Vijay 345 CSE 21 21-JUN-06


Raj 98 IT 22 30-SEP-06
Giri 300 CSE 67 14-NOV-81
Vishva 128 ECE 87 25-DEC-06
Ravi 124 ECE 89 15-JUN-05
ADDING CONSTRAINTS TO TABLE
---------------------------------------------------

SQL> alter table employee1 add ( salary number);


Table altered.

SQL> select * from employee1;

EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_NO DATE_OF_J SALARY

Raj 98 IT 22 30-SEP-06
Giri 100 CSE 67 14-NOV-81
Vishva 128 ECE 87 25-DEC-06

SQL> update employee1 set salary = 100 where


employee_no=98; 1 row updated.

SQL> update employee1 set salary = 90 where employee_no=100;


1 row updated.
SQL> update employee1 set salary = 134 where
employee_no=128; 1 row updated.

SQL> select * from employee1;

EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_NO DATE_OF_J SALARY

Raj 98 IT 22 30-SEP-06 100


Giri 100 CSE 67 14-NOV-81 90
Vishva 128 ECE 87 25-DEC-06 134

MODIFYING THE CHARACTERISTIC OF CONSTRAINTS IN A TABLE


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

Note: Before modifying the character of a column,first set the column values to null.The
feature of a column can be altered only if all its values become null or empty.

SQL> update employee1 set salary = ' 'where employee_no=100;


1 row updated.

SQL> update employee1 set salary = ' 'where employee_no=128;


1 row updated.

SQL> update employee1 set salary =' 'where employee_no=98;


1 row updated.

SQL> select * from employee1;

EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_NO DATE_OF_J SALARY

Raj 98 IT 22 30-SEP-06
Giri 100 CSE 67 14-NOV-81
Vishva 128 ECE 87 25-DEC-06

MODIFYING THE COLUMN OF EMPLOYEE1 TABLE


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

SQL> alter table employee1 modify ( salary varchar2(10));


Table altered.

SQL> select * from employee1;

EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_NO DATE_OF_J SALARY

Raj 98 IT 22 30-SEP-06
Giri 100 CSE 67 14-NOV-81
Vishva 128 ECE 87 25-DEC-06

SQL> update employee1 set salary ='90'where employee_no=100;


1 row updated.
SQL> update employee1 set salary ='134' where employee_no=128;
1 row updated.

SQL> update employee1 set salary ='100'where employee_no=98;


1 row updated.

EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_NO DATE_OF_J SALARY

Raj 98 IT 22 30-SEP-06 100


Giri 100 CSE 67 14-NOV-81 90
Vishva 128 ECE 87 25-DEC-06 134

DELETION OF TABLE VALUES


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

SQL> select * from employee1;

EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_NO DATE_OF_J

Vijay 345 CSE 21 21-JUN-06


Raj 98 IT 22 30-SEP-06
Giri 100 CSE 67 14-NOV-81
Vishva 128 ECE 87 25-DEC-06
Ravi 124 ECE 89 15-JUN-05

SQL> delete from employee1 where employee_no >344;


1 row deleted.

SQL> select * from employee1;

EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_NO DATE_OF_J

Raj 98 IT 22 30-SEP-06
Giri 100 CSE 67 14-NOV-81
Vishva 128 ECE 87 25-DEC-06
Ravi 124 ECE 89 15-JUN-05

SQL> delete from employee1 where employee_no =124;


1 row deleted.

SQL> select * from employee1;

EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_NO DATE_OF_J

Raj 98 IT 22 30-SEP-06
Giri 100 CSE 67 14-NOV-81
Vishva 128 ECE 87 25-DEC-06

GRANT COMMAND
------------------------------
SQL> grant insert,select,update,delete on employee1 to system;
Grant succeeded.
REVOKE COMMAND
------------------------------
SQL> revoke select,insert on employee1 from system;
Revoke succeeded.
SQL COMMANDS

TYPES OF COMMANDS

TCL (TRANSACTION CONTROL COMMANDS)

 COMMIT

 SAVEPOINT

 ROLLBACK

SET OPERATORS

 UNION

 UNIONALL

 INTERSECT

 MINUS

ARITHMETIC OPERATORS

 MAX

 MIN

 COUNT

 AVG

 SUM

1. COMMAND NAME: COMMIT


COMMAND DESCRIPTION: COMMIT command is used to save the work done.

2. COMMAND NAME: SAVE POINT

COMMAND DESCRIPTION: SAVE POINT command is used to identify a point in a

transaction in which it can be restored using Roll back command.

3. COMMAND NAME: ROLLBACK

COMMAND DESCRIPTION: ROLLBACK command is used to restore database to

original since last commit.

4. COMMAND NAME: MAX

COMMAND DESCRIPTION: MAX command is used to find the maximum among the

entities in a particular attribute.

5. COMMAND NAME: MIN

COMMAND DESCRIPTION: MIN command is used to find the manimum among the

entities in a particular attribute.

6. COMMAND NAME: COUNT

COMMAND DESCRIPTION: COUNT command is used to count the entire entities in a

particular attribute.

7. COMMAND NAME: SUM

COMMAND DESCRIPTION: SUM command is used to add all the entities with in the attribute.

8. COMMAND NAME: UNION

COMMAND DESCRIPTION: UNION command is used to compile all distinct rows and

display all entities in both rows.

9. COMMAND NAME: UNIONALL

COMMAND DESCRIPTION: UNIONALL command is used to return all entities in both rows.

10. COMMAND NAME: INTERSECT

COMMAND DESCRIPTION: INTERSECT command is used to display only similar entities in

both rows.

11. COMMAND NAME: MINUS


COMMAND DESCRIPTION: MINUS command is used to display only the rows that

don’t match in both queries.

12.COMMAND NAME: AVG

COMMAND DESCRIPTION: AVG command is used to find average of entity in

particular attribute.

COMMANDS EXECUTION

CREATION OF TABLE
--------------------------------
SQL> create table employee ( Employee_Name varchar2(10),Employee_no number primary
key, Dept_no number,Dept_name varchar2(10));
Table created.

SQL> create table employee1 ( Employee_Name varchar2(10),Employee_no number primary


key,Dept_no number,dept_name varchar2(10));
Table created.

SELECTION OF TABLE VALUES


-----------------------------------------------
SQL> select * from employee;

EMPLOYEE_N EMPLOYEE_NO DEPT_NO DEPT_NAME

Ganesh 234 45 CSE


Vijay 877 85 EEE
Vignesh 990 95 BME
SQL> select * from employee1;

EMPLOYEE_N EMPLOYEE_NO DEPT_NO DEPT_NAME

Ganesh 234 45 CSE


Vishnu 476 55 IT
Vikram 985 75 ECE

COMMIT & ROLLBACK COMMAND


----------------------------------------------------
SQL> select * from employee;

EMPLOYEE_N EMPLOYEE_NO DEPT_NO DEPT_NAME

Ganesh 234 45 CSE


Vijay 877 85 EEE
Vignesh 990 95 BME

SQL> commit;
Commit complete.

SQL> delete from employee where employee_no=990;


1 row deleted.

SQL> select * from employee;

EMPLOYEE_N EMPLOYEE_NO DEPT_NO DEPT_NAME

Ganesh 234 45 CSE


Vijay 877 85 EEE

SQL> rollback;
Rollback complete.
SQL> select * from employee;

EMPLOYEE_N EMPLOYEE_NO DEPT_NO DEPT_NAME

Ganesh 234 45 CSE


Vijay 877 85 EEE
Vignesh 990 95 BME

SAVEPOINT & ROLLBACK COMMAND


--------------------------------------------------------
SQL> select * from employee;

EMPLOYEE_N EMPLOYEE_NO DEPT_NO DEPT_NAME

Ganesh 234 45 CSE


Vijay 877 85 EEE
Vignesh 990 95 BME

SQL> savepoint s1;


Savepoint created

SQL> update employee set dept_no=75 where employee_no=234;


1 row updated

SQL> delete from employee where employee_no=990;


1 row deleted

SQL> select * from employee;

EMPLOYEE_N EMPLOYEE_NO DEPT_NO DEPT_NAME

Ganesh 234 75 CSE


Vijay 877 85 EEE

SQL> roll back s1;


Rollback complete.

SQL> select * from employee;

EMPLOYEE_N EMPLOYEE_NO DEPT_NO DEPT_NAME

Ganesh 234 45 CSE


Vijay 877 85 EEE
Vignesh 990 95 BME

ARITHMETIC OPERATORS
----------------------------------------
SQL> select * from employee;

EMPLOYEE_N EMPLOYEE_NO DEPT_NO DEPT_NAME

Ganesh 234 45 CSE


Vijay 877 85 EEE
Vignesh 990 95 ECE

SQL> select sum(employee_no) from employee;

SUM(EMPLOYEE_NO)

2101
SQL> select avg(employee_no) from employee;

AVG(EMPLOYEE_NO)

700.33333

SQL> select max(employee_no) from


employee; MAX(EMPLOYEE_NO)

990
SQL> select min(employee_no) from employee;

MIN(EMPLOYEE_NO)

234
SQL> select count(employee_no) from employee;

COUNT(EMPLOYEE_NO)

3
SET OPERATORS
-------------------------
SQL> select * from employee;

EMPLOYEE_N EMPLOYEE_NO DEPT_NO DEPT_NAME

Ganesh 234 45 CSE


Vijay 877 85 EEE
Vignesh 990 95 BME

SQL> select * from employee1;


EMPLOYEE_N EMPLOYEE_NO DEPT_NO DEPT_NAME

Ganesh 234 45 CSE


Vishnu 476 55 IT
Vikram 985 75 ECE

SQL> SQL> select employee_no from employee union select employee_no from employee1;
EMPLOYEE_NO

234
476
877
985
990
SQL> select employee_no from employee union all select employee_no from employee1;
EMPLOYEE_NO

234
877
990
234
476
985
6 rows selected.

SQL> select employee_no from employee intersect select employee_no from employee1;
EMPLOYEE_NO

234

SQL> select employee_no from employee minus select employee_no from employee1;
EMPLOYEE_NO

877
990

SQL>select employee_no from employee1 minus select employee_no from employee;


EMPLOYEE_NO

476
985
SQL COMMANDS

LOGICAL OPERATRORS:

 OR
 NOT
 AND
NUMERICAL FUNCTIONS:

 Abs
 Round
 Sqrt
 Power
STRING FUCNTIONS:

 Lower
 Upper
 Initcap
 Substr
 Lapd
 Rpad

creation of tables:
SQL> create table students(name varchar2(10),id number(5),age number(5),area
varchar2(10),dept varchar2(10));

Table created.

SQL> insert into students values('ashwin',101,19,'anna nagar','cse');


1 row created.

SQL> insert into students values('bhuvanesh',102,18,'tnagar','marine');


1 row created.

SQL> insert into students values('charith',104,19,'anna nagar','eee');


1 row created.

SQL> insert into students values('katharin',105,18,'kilpauk','mechanical');


1 row created.

SQL> select * from students;

NAME ID AGE AREA DEPT

ashwin 101 19 anna nagar cse


bhuvanesh 102 18 tnagar marine
charith 104 19 anna nagar eee
katharin 105 18 kilpauk mechanical

Arithmetic operations:

SQL> select name,id+200"sid" from students;


NAME sid

ashwin 301
bhuvanesh 302
charith 304
katharin 305
concatenation operator:

SQL> select name||'is a'|| dept||'engineer' "profession" from students;

profession

Ashwin is a cse engineer


Bhuvanesh is a marineengineer
Charith is a eee engineer
Katharin is a mechanical engineer

Using comparison operator:

SQL> select name,age from students where age<=20;

NAME AGE
ashwin 19
bhuvanesh 18
charith 19
katharin 18

Between operator:

SQL> select name,id from students where id between 102 and 105;

NAME ID

bhuvanesh 102
charith 104
katharin 105

in predicate:

SQL> select name,id from students where id in(102,104);

NAME ID

bhuvanesh 102
charith 104

pattern matching:

SQL> select name,area from students where area like'%g

%'; NAME AREA

ashwin anna nagar


bhuvanesh tnagar
charith anna nagar

SQL> select name,area from students where area like '%t%';

NAME AREA

bhuvanesh tnagar

Logical AND operator:


SQL> select name,id from students where id>102 and area='anna nagar';

NAME ID

charith 104

Logical OR Operator:
SQL> select name,id from students where id>102 or area='anna nagar';

NAME ID
ashwin 101
bhuvanesh 102
charith 104
katharin 105

NOT in predicate:

SQL> select name,id from students where id not in(102,104);

NAME ID

ashwin 101
katharin 105

Order by clause:

SQL> select * from students;

NAME ID AGE AREA DEPT

ashwin 101 19 anna nagar cse


bhuvanesh 102 18 tnagar marine
charith 104 19 anna nagar eee
katharin 105 18 kilpauk mechanical

SQL> select name, dept from students order by area;

NAME DEPT

ashwin cse
charith eee
katharin mechanical
bhuvanesh marine
SQL> select dept from students order by name

desc; DEPT

mechanical
eee
marine
cse
SQL> select dept from students order by name asc;

DEPT

cse
marine
eee
mechanical

Numeric Functions:
SQL> select abs(-20) result from dual;
RESULT

20

SQL> select power(2,3) result from dual;

RESULT

SQL> select round(15.389,2)result from dual;

RESULT

15.39

SQL> select sqrt(25)result from dual;

RESULT

5
String functions:

SQL> select lower('DBMS')result from dual;

RESULT

dbms

SQL> select upper('dbms')result from dual;

RESULT

DBMS

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

RESULT

Oracle

SQL> select substr('oracle',3,4)result from

dual; RESULT

acle

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

RESULT
$$$$oracle

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

RESULT

oraclennnn

Date Fucntions:
SQL> select sysdate from dual;

SYSDATE

22-JAN-14

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

SYSDATE RESULT

22-JAN-14 31-JAN-14
SQL> select sysdate, next_day(sysdate,'monday')result from dual;

SYSDATE RESULT

22-JAN-14 27-JAN-14

SQL> select months_between('01-march-2014','01-jan-2014') result from dual;

RESULT

2
INTEGRITY CONSTRAINTS:

Integrity constraints provide a menas of ensuring that changes made to the database by
authorized users donot result in a loss of data consistency.

Types are

 Domain constraints
 NOT NULL constraints
 Enity constraints
 Referential Integrity

Domain Constriants:

It specify the set of values that can be associated with an attribute. Thery are tested
easily by the system whenever a new data item is enterd into the database.

Referential Integrity:

A value that appears in one relation for a given set of attributes also appears for a certain
set of attributes in another realtion.

NOT NULL constraint:

Null represents a value for an attribute that is currently unknown or is not applicable for
the tuple. Not Null indicates that value for an attribute should not be null.

Entity Constraint:

In a relation no attribute of a primary key can be null.

Two types

1. Unique key constraints: It is used ot preven the duplication of data in


a column on a group of columns in a table.

2. Primary key constraint:It is used to represent entry of a datawhich

is already used for a primary key attribute of a table.

Check constraint:

It can be defined to allow only a particular range of values for an attribute. This
constraints assures the violation to the range value results in error.

Foreign Key:

It is an attribute or combination of attributes in realtion whose values must match the


primary key values in R1.

PROGRAM EXECUTION:

Not null and check constraint:


SQL> create table employeecse(empname varchar2(20),empid number(8)not
null,check(empid<1000));
Table created.

SQL> insert into employeecse values('abi',100);


1 row created.

SQL> insert into employeecse values('karthick',null);


insert into employeecse values('karthick',null)
*
ERROR at line 1:
ORA-01400: cannot insert NULL into ("SCOTT"."EMPLOYEECSE"."EMPID")

SQL> insert into employeecse values('gopal', 1001);


insert into employeecse values('gopal', 1001)
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.SYS_C005485) violated

SQL> insert into employeecse values('manju',509);


1 row created.

SQL> select * from employeecse;


EMPNAME EMPID

abi 100
manju 509

unique as column constraint:


SQL> create table employeeece(empname varchar2(10),id number(5)unique);
Table created.
SQL> insert into employeeece values('viji',209);
1 row created.
SQL> insert into employeeece values('suji',null);
1 row created.
SQL> insert into employeeece values('deepa',506);
1 row created.
SQL> insert into employeeece values('bala',209);
insert into employeeece values('bala',209)
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C005486) violated
SQL> select * from employeeece;
EMPNAME ID

viji 209
suji
deepa 506

Unique as a table constraint:


SQL> create table employee1(name varchar2(10),id number(5),unique(name,id));
Table created.

SQL> insert into employee1 values('X',190);


1 row created.
SQL> insert into employee1 values(‘Y',456);
1 row created.
SQL> insert into employee1 values ( ' Z',890);
1 row created.
SQL> insert into employee1 values( 'G',190);
1 row created.

SQL> insert into employee1 values('G',190);


insert into employee1 values('G',190)
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C003019) violated SQL>

select * from employee1;


NAME ID

X 190
Y 456
Z 890
G 190
Primary key as a column constriant:

SQL> create table emp1(name varchar2(10), id number(10)primary key);


Table created.

SQL> insert into emp1 values('Balu',17890);


1 row created.
SQL> insert into emp1 values('prince',12345);
1 row created.

SQL> insert into emp1 values('Jack',17890);


insert into emp1 values('Jack',17890)
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C003021) violated

SQL> select * from emp1;

NAME ID

Balu 17890
prince 12345

primary key as table constraint:

SQL> create table emp2(name varchar2(10),id number(5),primary key(name,id));


Table created.

SQL> insert into emp2 values('anna',2314);


1 row created.

SQL> insert into emp2 values('raja',2345);


1 row created.
SQL> insert into emp2 values('karthick',2345);
1 row created.
SQL> insert into emp2 values('anna',2314);
insert into emp2 values('anna',2314)
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C003022) violated

SQL> select * from emp2;

NAME ID
anna 2314
raja 2345
karthick 2345

Referential Integrity Constraints:


SQL> create table depart(name varchar2(10),dno number(5)primary key);
Table created.

SQL> insert into depart values('cse',1256);


1 row created.
SQL> insert into depart values('eee',5678);
1 row created.

SQL> create table employe1(ename varchar2(10),dno number(5)references depart(dno));


Table created.

SQL> insert into employe1 values('viji',1256);


1 row created.
SQL> insert into employe1 values('kala',5678);
1 row created.
SQL> insert into employe1
values('chandra',234); insert into employe1
values('chandra',234)
*
ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.SYS_C003024) violated - parent key not
Found
SQL> select * from depart;
NAME DNO

cse 1256
eee 5678
SQL> select * from employe1;
ENAME DNO

viji 1256
kala 5678
SQL> select ename, name from employe1,depart where
employe1.dno=depart.dno; ENAME NAME

viji cse
kala eee
Foreign Key:

It is an attribute or combination of attributes in realtion whose values must match the


primary key values in R1.

SQL COMMANDS

1. COMMAND NAME: INNER JOIN


COMMAND DESCRIPTION: INNER JOIN command returns the matching rows from
the tables that are being joined.
2. COMMAND NAME: LEFT OUTER JOIN
COMMAND DESCRIPTION: LEFT OUTER JOIN command returns matching rows
from the tables being joined and also non-matching row from the left table in the result
and places null values in the attributes that come from the right side table.
3. COMMAND NAME: RIGHT OUTER JOIN
COMMAND DESCRIPTION: RIGHT OUTER JOIN command returns matching rows
from the tables being joined and also non-matching row from the right table in the result
and places null values in the attributes that come from the left side table.
4. COMMAND NAME: NESTED QUERY
COMMAND DESCRIPTION: NESTED QUERY command have query within another
query.
COMMANDS EXECUTION:

SQL> create table person(personid number(5)primary key, personname varchar2(10),address


varchar2(10));
Table created.

SQL> create table orders1(orderid number(5), orderno number(8),personid number(5));


Table created.

Adding foregin key to table:

SQL> alter table orders1 add foreign key(personid)references person(personid);


Table altered.

SQL> insert into person values(100, 'Ram','Tvmalai');


1 row created.

SQL> insert into person values(200,'Vijay','Chennai');


1 row created.

SQL> insert into person values(300,'bala','Mumabi');


1 row created.

SQL> insert into orders1 values(01,4567,200);


1 row created.

SQL> insert into orders1 values(02, 4329,300);


1 row created.

SQL> select * from person;


PERSONID PERSONNAME ADDRESS

100 Ram Tvmalai


200 Vijay Chennai
300 bala Mumabi

SQL> select * from orders1;


ORDERID ORDERNO PERSONID

1 4567 200
2 4329 300

INNER JOIN:

SQL> select p.personname from person p, orders1 o where p.personid=o.personid;

PERSONNAME

Vijay
bala
SQL> select p.personname,p.address,o.orderid,o.orderno from person p,orders1 o
where p.personid=o.personid;

PERSONNAME ADDRESS ORDERID ORDERNO

Vijay Chennai 1 4567


bala Mumabi 2 4329

SQL> create table customers(customername varchar2(10),customerid number(5)primary


key,address varchar2(10),country varchar2(10));
Table created.

SQL> create table orders2(orderid number(5),customerid number(5),orderdate date);


Table created.

SQL> alter table orders2 add foreign key(customerid) references customers(customerid);


Table altered.

SQL> insert into customers values('viji',101,'mumbai', 'India');


1 row created.

SQL> insert into customers values('Balu',201,'chennai','India');


1 row created.

SQL> insert into customers values('kala',301,'calicut','India');


1 row created.

SQL> select * from customers;

CUSTOMERNA CUSTOMERID ADDRESS COUNTRY

viji 101 mumbai India


Balu 201 chennai India
Kala 301 calicut India

SQL> insert into orders2 values(4589,201,'12-jan-2014');


1 row created.

SQL> insert into orders2 values(3490,101,'23-Dec-2013');


1 row created.
SQL> select * from orders2;

ORDERID CUSTOMERID ORDERDATE


=
4589 201 12-JAN-14
3490 101 23-DEC-13

SQL> select * from customers;


CUSTOMERNA CUSTOMERID ADDRESS COUNTRY

viji 101 mumbai India


Balu 201 chennai India
kala 301 calicut India

LEFT OUTER JOIN:

SQL> select c.customername, o.orderid from customers c left outer join orders2 o on
c.customerid= o.customerid;

CUSTOMERNA ORDERID

Balu 4589
viji 3490
kala

RIGHT OUTER JOIN:

SQL> select c.customername, o.orderid from customers c right outer join orders2 o on
c.customerid= o.customerid;

CUSTOMERNA ORDERID

viji 3490
Balu 4589

FULL OUTER JOIN:

SQL> select c.customername, o.orderid from customers c full outer join orders2 o on
c.customerid=o.customerid;

CUSTOMERNA ORDERID

Balu 4589
viji 3490
kala

SUBQUERIES:

SQL> create table sailor(sid number(5),sname varchar2(10),age number(5),primary key(sid));

Table created.
SQL> insert into sailor values(101,'john',25);
1 row created.

SQL> insert into sailor values(102,'peter',56);


1 row created.

SQL> insert into sailor values(502,'ramu',45);


1 row created.
SQL> select * from sailor;

SID SNAME AGE

101 john 25
102 peter 56
502 ramu 45

SQL> create table reserve(sid number(5), reserdate date,foreign key(sid)references sailor);


Table created.

SQL> insert into reserve values('&sid','&reserdate');


Enter value for sid: 101
Enter value for reserdate: 22-jan-2014
old 1: insert into reserve values('&sid','&reserdate')
new 1: insert into reserve values('101','22-jan-2014')
1 row created.

SQL> /
Enter value for sid: 102
Enter value for reserdate: 12-march-2014
old 1: insert into reserve values('&sid','&reserdate')
new 1: insert into reserve values('102','12-march-2014')
1 row created.

SQL> /
Enter value for sid: 504
Enter value for reserdate: 2-feb-2014
old 1: insert into reserve values('&sid','&reserdate')
new 1: insert into reserve values('504','2-feb-2014')
insert into reserve values('504','2-feb-2014')
*
ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.SYS_C003026) violated - parent key not
found
SQL> select * from sailor;

SID SNAME AGE

101 john 25
102 peter 56
502 ramu 45

SQL> select * from reserve;

SID RESERDATE

101 22-JAN-14
102 12-MAR-14

SQL> select sname from sailor where sid in(select sid from reserve where age<60);

SNAME
john
peter

SQL> update sailor set age=(select sum(sid)from sailor)where sname='peter';

1 row updated.

SQL> select * from sailor;

SID SNAME AGE

101 john 25
102 peter 705
502 ramu 45

Nested Queries in SQL

Query inside the query is nested query.

It is also called as sub query.

Correlated subquery runs once for each row selected by the outer query. It contains a reference
to a value from the row selected by the outer query.

Nested subquery runs only once for the entire nesting (outer) query. It does not contain any
reference to the outer query row.

In nested queries, a query is written inside a query. The result of inner query is used in
execution of outer query. We will use STUDENT, COURSE, STUDENT_COURSE tables
for understanding nested queries.

STUDENT
S_ID S_NAME S_ADDRESS S_PHONE S_AGE

S1 RAM DELHI 9455123451 18

S2 RAMESH GURGAON 9652431543 18

S3 SUJIT ROHTAK 9156253131 20

S4 SURESH DELHI 9156768971 18

COURSE
C_ID C_NAME

C1 DSA

C2 Programming

C3 DBMS

STUDENT_COURSE
S_ID C_ID

S1 C1

S1 C3

S2 C1

S3 C2

S4 C2

S4 C3

There are mainly two types of nested queries:


 Independent Nested Queries: In independent nested queries, query execution
starts from innermost query to outermost queries. The execution of inner query is
independent of outer query, but the result of inner query is used in execution of
outer query. Various operators like IN, NOT IN, ANY, ALL etc are used in writing
independent nested queries.

IN: If we want to find out S_ID who are enrolled in C_NAME ‘DSA’ or ‘DBMS’,
we can write it with the help of independent nested query and IN operator.
From COURSEtable, we can find out C_ID for C_NAME ‘DSA’ or DBMS’ and
we can use these C_IDs for finding S_IDs from STUDENT_COURSE TABLE.

STEP 1: Finding C_ID for C_NAME =’DSA’ or ‘DBMS’


Select C_ID from COURSE where C_NAME = ‘DSA’ or C_NAME = ‘DBMS’
 STEP 2: Using C_ID of step 1 for finding S_ID

Select S_ID from STUDENT_COURSE where C_ID IN


(SELECT C_ID from COURSE where C_NAME = ‘DSA’
or C_NAME=’DBMS’);
The inner query will return a set with members C1 and C3 and outer query will
return those S_IDs for which C_ID is equal to any member of set (C1 and C3 in
this case). So, it will return S1, S2 and S4.

Note: If we want to find out names of STUDENTs who have either enrolled in
‘DSA’ or ‘DBMS’, it can be done as:

Select S_NAME from STUDENT where S_ID IN


(Select S_ID from STUDENT_COURSE where C_ID IN
(SELECT C_ID from COURSE where C_NAME=’DSA’
or C_NAME=’DBMS’));

NOT IN: If we want to find out S_IDs of STUDENTs who have neither enrolled
in ‘DSA’ nor in ‘DBMS’, it can be done as:
Select S_ID from STUDENT where S_ID NOT IN
(Select S_ID from STUDENT_COURSE where C_ID IN
(SELECT C_ID from COURSE where C_NAME=’DSA’
or C_NAME=’DBMS’));

The innermost query will return a set with members C1 and C3. Second inner query
will return those S_IDs for which C_ID is equal to any member of set (C1 and C3
in this case) which are S1, S2 and S4. The outermost query will return those S_IDs
where S_ID is not a member of set (S1, S2 and S4). So it will return S3.

 Co-related Nested Queries: In co-related nested queries, the output of inner query
depends on the row which is being currently executed in outer query. e.g.; If we
want to find out S_NAME of STUDENTs who are enrolled in C_ID ‘C1’, it can
be done with the help of co-related nested query as:

Select S_NAME from STUDENT S where EXISTS


( select * from STUDENT_COURSE SC where S.S_ID=SC.S_ID and
SC.C_ID=’C1’);

For each row of STUDENT S, it will find the rows from STUDENT_COURSE
where S.S_ID = SC.S_ID and SC.C_ID=’C1’. If for a S_ID from STUDENT S, atleast a row exists in
STUDENT_COURSE SC with C_ID=’C1’, then inner query will return true and corresponding S_ID will be
returned as output.
SQL COMMANDS

1. COMMAND NAME: CREATE VIEW

COMMAND DESCRIPTION: CREATE VIEW command is used to define a view.

2. COMMAND NAME: INSERT IN VIEW

COMMAND DESCRIPTION: INSERT command is used to insert a new row into the

view.

3. COMMAND NAME: DELETE IN VIEW

COMMAND DESCRIPTION: DELETE command is used to delete a row from the view.

4. COMMAND NAME: UPDATE OF VIEW

COMMAND DESCRIPTION: UPDATE command is used to change a value in a tuple

without changing all values in the tuple.

5. COMMAND NAME: DROP OF VIEW

COMMAND DESCRIPTION: DROP command is used to drop the view table

COMMANDS EXECUTION

CREATION OF TABLE:
SQL> create table empl( Employee_name varchar2(10),employee_no number(8),
dept_name varchar2(10),dep
t_no number (5),date_of_join date);
Table created.

SQL> insert into empl values('Baskar',1001,'CSE',25,'21-jun-2013');


1 row created.

SQL> insert into empl values('Bala',1002,'ECE',30,'1-jul-2013');


1 row created.

SQL> insert into empl values('charu',2004,'EEE',35,'28-aug-2013');


1 row created.

SQL> insert into empl values('karthick',5004,'Civil',45,'3-aug-2013');


1 row created.

SQL> select * from empl;

EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_NO DATE_OF_J


- - -
Baskar 1001 CSE 25 21-JUN-13
Bala 1002 ECE 30 01-JUL-13
charu 2004 EEE 35 28-AUG-13
karthick 5004 Civil 45 03-AUG-13

CREATION OF VIEW:

SQL> create view emplview as select Employee_name,employee_no,dept_name


from empl;
View created.

SQL> desc emplview;


Name Null? Type
- - - -
EMPLOYEE_NAME VARCHAR2(10)
EMPLOYEE_NO NUMBER(8)
DEPT_NAME VARCHAR2(10)

SQL> insert into emplview values('sri',3005,'ECE');


1 row created.

SQL> insert into emplview values('sri',3005,'ECE');


1 row created.

SQL> insert into emplview values('saran',3098,'CSE');


1 row created.

SQL> select * from emplview;


EMPLOYEE_N EMPLOYEE_NO DEPT_NAME
- -
Baskar 1001 CSE
Bala 1002 ECE
charu 2004 EEE
karthick 5004 Civil
sri 3005 ECE
saran 3098 CSE
7 rows selected.

SQL> select * from empl;


EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_NO DATE_OF_J
- - - - -
Baskar 1001 CSE 25 21-JUN-13
Bala 1002 ECE 30 01-JUL-13
Charu 2004 EEE 35 28-AUG-13
karthick 5004 Civil 45 03-AUG-13
sri 3005 ECE
saran 3098 CSE
7 rows selected.
MODIFICATION:

SQL> update emplview set dept_name='Civil' where Employee_name='saran';


1 row updated.

SQL> select * from emplview;

EMPLOYEE_N EMPLOYEE_NO DEPT_NAME


- -
Baskar 1001 CSE
Bala 1002 ECE
charu 2004 EEE
karthick 5004 Civil
sri 3005 ECE
saran 3098 Civil
7 rows selected.

SQL> delete from emplview where Employee_name='sri';


1 rows deleted.

SQL> select * from emplview;

EMPLOYEE_N EMPLOYEE_NO DEPT_NAME


- -
Baskar 1001 CSE
Bala 1002 ECE
charu 2004 EEE
karthick 5004 Civil
saran 3098 Civil

SQL> drop view emplview;

View dropped.

SEQUENCE

 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 sequence of numbers can be generated in either ascending or descending order.

CREATION OF TABLE:

SQL> create table empc1( Employee_name varchar2(10),employee_no number(8),


dept_name varchar2(10),dept_no number (5),date_of_join date);

Table created.

SQL> insert into empc1 values('Baskar',1001,'CSE',25,'21-jun-2013');

1 row created.

SQL> insert into empc1 values('Bala',1002,'ECE',30,'1-jul-2013');

1 row created.

SQL> insert into empc1 values('charu',2004,'EEE',35,'28-aug-2013');

1 row created.

SQL> insert into empc1 values('karthick',5004,'Civil',45,'3-aug-2013');

1 row created.

SQL> select * from empc1;

EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_NO DATE_OF_J

Baskar 1001 CSE 25 21-JUN-13


Bala 1002 ECE 30 01-JUL-13
charu 2004 EEE 35 28-AUG-13
karthick 5004 Civil 45 03-AUG-13
CREATION OF SEQUENCE:

SQL> create sequence empcseq


2 minvalue 1
3 maxvalue 10
4 start with 1
5 cache 10;

Sequence created.

SQL> insert into empc1 values('diviya',3000,'cse',empcseq.nextval,'10-jul-2011');

1 row created.

SQL> select * from empc1;

EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_NO DATE_OF_J

Baskar 1001 CSE 25 21-JUN-13


Bala 1002 ECE 30 01-JUL-13
charu 2004 EEE 35 28-AUG-13
karthick 5004 CIVIL 45 03-AUG-13
diviya 3000 CSE 1 10-JUL-11

SQL> insert into empc1 values('latha',5000,'EEE',empcseq.nextval,'12-aug-2013');


1 row created.

SQL> select * from empc1;

EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_NO DATE_OF_J

Baskar 1001 CSE 25 21-JUN-13


Bala 1002 ECE 30 01-JUL-13
charu 2004 EEE 35 28-AUG-13
karthick 5004 CIVIL 45 03-AUG-13
Diviya 3000 CSE 1 10-JUL-11
Latha 5000 EEE 2 12-AUG-13
6 rows selected.

SQL> select empcseq.nextval from dual;

NEXTVAL

SQL> select empcseq.nextval from dual;

NEXTVAL

4
SQL> select empcseq.nextval from dual;
NEXTVAL

SQL> drop sequence empcseq;

Sequence dropped.

SYNONYM:

 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 public synonym can be accessed by any system user.

 The individual creating a public synonym does not own the synonym – rather, it will
belong to the PUBLIC user group that exists within Oracle.

 Private synonyms, on the other hand, belong to the system user that creates them and
reside in that user's schema.

 A system user can grant the privilege to use private synonyms that they own to other
system users.

 In order to create synonyms, we will need to have the CREATE SYNONYM privilege.

 This privilege will be granted to us by the DBA.

 We must have the CREATE PUBLIC SYNONYM privilege in order to create public
synonyms.

 If we own a synonym, we have the right to drop (delete) the synonym. The DROP
SYNONYM command is quite simple.

 DROP SYNONYM synonym_name;

 In order to drop a public synonym we must include the PUBLIC keyword in the DROP
SYNONYM command.

 In order to drop a public synonym, we must have the DROP PUBLIC SYNONYM
privilege.

 DROP PUBLIC SYNONYM synonym_name;


CREATION OF SYNONYM:

SQL> select * from class;

NAME ID

anu 1
brindha 2
chinthiya 3
divya 4
ezhil 5
fairoz 7
hema 9

7 rows selected.
Create synonym:
SQL> create synonym c1 for class;

Synonym created.
SQL> insert into c1 values('kalai',20);

1 row created.

SQL> select * from class;

NAME ID

anu 1
brindha 2
chinthiya 3
divya 4
ezhil 5
fairoz 7
hema 9
kalai 20

8 rows selected.

SQL> select * from c1;

NAME ID

anu 1
brindha 2
chinthiya 3
divya 4
ezhil 5
fairoz 7
hema 9
kalai 20

8 rows selected.
SQL> insert into class values('Manu',21);
1 row created.
SQL> select * from c1;

NAME ID

anu 1
brindha 2
chinthiya 3
divya 4
ezhil 5
fairoz 7
hema 9
kalai 20
Manu 21

9 rows selected.

Drop Synonym:

SQL> drop synonym c1;


Synonym dropped.
S.No Attribute & Description

%FOUND

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

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

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

%ROWCOUNT
4 Returns the number of rows affected by an INSERT, UPDATE, or
DELETE statement, or returned by a SELECT INTO statement.

Write a PL/ SQL code for calculating total mark, percentage, grade for all the students in a
student management system using implicit cursors.

SQL> create table student(id number, name varchar2(10), dept varchar2(10),


percent number,m1 number,m2 number, m3 number, tot number, g varchar2(1));

Table created.

SQL> select * from student;


ID NAME DEP PERCENT M1 M2 M3 TOT G

1 Anu it 0 90 89 80 0

2 Beena cse 0 98 91 95 0

3 Bindhu it 0 87 67 86 0

4 Varun it 0 67 46 50 0

5 Rahul cse 0 81 82 83 0

SQL> declare 2 cursor c is select * from student;

3 ctot number;

4 cgra varchar2(1);

5 cper number;

6 begin

7 for I in c

8 loop

9 ctot= i.m1+i.m2+i.m3;

10 cper :=ctot/3;

11 update student set tot = ctot where id =i.id;

12 update student set percent = cper where id

=i.id; 13 if(cper between 91 and 100)then

14 cgra:= ‘S’

15 elsif(cper between 81 and 90)then

16 cgra:= ‘A’

17 elsif(cper between 71 and 80)then

18 cgra:= ‘B’

19 elsif(cper between 61 and 70)then

20 cgra:= ‘C’

21 elsif(cper between 56 and 60)then

22 cgra:= ‘D’

23 elsif(cper between 50 and 55)then

24 cgra:= ‘E’
49
25 else

26 cgra:= ‘F’

27 end if;

28 update student set g = cgra where id

=i.id; 29 end loop;


30 end;
31 /

PL/ SQL procedure successfully completed.

SQL> select * from student;

ID NAME DEP PERCENT M1 M2 M3 TOT G


1 Anu it 86.3333333 90 89 80 259 A
2 Beena cse 94.6666667 98 91 95 284 S
3 Bindhu it 80 87 67 86 240 B
4 Tarun it 54.3333333 67 46 50 163 E
5 Rahul cse 82 81 82 83 246 A

SYNTAX: EXPLICIT

cursor cursor_name is select * from table name;

To open the cursor:


open cursor_name;

To close the cursor:


close cursor_name;

Exercise: Write PL/ SQL code for calculating hra , da, netsalary for all the employees in
the Payroll Processing using Explicit cursor(uses employee table).

SQL> select * from employee;


EMPNO NAME HRA DA PF NETSAL BASICPAY
101 AAA 0 0 0 0 15000
102 BBB 0 0 0 0 18000
103 CCC 0 0 0 0 20000
104 DDD 0 0 0 0 10000
105 EEE 0 0 0 0 25000

SQL> declare
2 cursor c is select * from employee;
3 i employee% rowtype;
4 hrasal number;
5 dasal number;
6 pfsal number;
7 netsalary number;
8 begin
9 open c;
10 loop;
50
11 fetch c into i;
12 if c% notfound ten exit;
13 endif;
14 hrasal:=i.basicpay*0.1;
15 dasal:=i.basicpay*0.08;
16 pfsal:=i.basicpay*0.12;
17 netsalaray:= i.basicpay + hrasal + dasal + pfsal;
18 update employee set hra = hrasal, da= dasal, pf= pfsal, netsal= netsalaray
where empno=i.empno;
19 end loop;
20 close c;
21 end;
22 /

PL/ SQL procedure successfully completed. SQL>

select * from employee;


EMPNO NAME HRA DA PF NETSAL BASICPAY
101 AAA 1500 1200 1800 15900 15000
102 BBB 1800 1440 2160 19080 18000
103 CCC 2000 1600 2400 21200 20000
104 DDD 1000 800 1200 10600 10000
105 EEE 2500 2000 3000 26500 25000
Definition:

52
PL/SQL stands for Procedural Language extension of SQL.PL/SQL is a combination
of SQL along with the procedural features of programming languages.It was developed
by Oracle Corporation in the early 90’s to enhance the capabilities of SQL.

The PL/SQL Engine:

Oracle uses a PL/SQL engine to processes the PL/SQL statements. A PL/SQL code can
be stored in the client system (client-side) or in the database (server-side).

A Simple PL/SQL Block:

Each PL/SQL program consists of SQL and PL/SQL statements which from a
PL/SQL block.

PL/SQL Block consists of three sections:

 The Declaration section (optional).


 The Execution section (mandatory).
 The Exception (or Error) Handling section (optional).

Declaration Section:

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

Execution Section:

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

Exception Section:

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

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

How a Sample PL/SQL Block Looks


DECLARE
Variable declaration BEGIN
Program Execution EXCEPTION
Exception handling END;

Advantages of PL/SQL

These are the Advantages of PL/SQL

 Block Structures: PL SQL consists of blocks of code, which can be nested within each
other. Each block forms a unit of a task or a logical module. PL/SQL Blocks can be
stored in the database and reused.
 Procedural Language Capability: PL SQL consists of procedural language constructs
such as conditional statements (if else statements) and loops like (FOR loops).
 Better Performance: PL SQL engine processes multiple SQL statements
simultaneously as a single block, thereby reducing network traffic.
 Error Handling: PL/SQL handles errors or exceptions effectively during the execution
of a PL/SQL program. Once an exception is caught, specific actions can be taken
depending upon the type of the exception or it can be displayed to the user with a
message.
ADDITION OF TWO NUMBERS

SQL> declare
2 a number;
3 b number;
4 c number;
5 begin
6 a:=&a;
7 b:=&b;
8 c:=a+b;
9 dbms_output.put_line('sum of'||a||'and'||b||'is'||c);
10 end;
11 /
INPUT:
Enter value for a: 23
old 6: a:=&a;
new 6: a:=23;
Enter value for b:
12 old 7: b:=&b;
new 7: b:=12;

OUTPUT:
sum of23and12is35
PL/SQL procedure successfully completed.

GREATEST OF THREE NUMBERS

SQL> declare
2 a number;
3 b number;
4 c number;
5 d number;
6 begin
7 a:=&a;
8 b:=&b;
9 c:=&b;
10 if(a>b)and(a>c) then
11 dbms_output.put_line('A is
maximum'); 12 elsif(b>a)and(b>c)then
13 dbms_output.put_line('B is maximum');
14 else
15 dbms_output.put_line('C is maximum');
16 end if;
17 end;
18 /

INPUT:

Enter value for a: 21


old 7: a:=&a;
new 7: a:=21;
Enter value for b:
12 old 8: b:=&b;
new 8: b:=12;
Enter value for b:
45 old 9: c:=&b;
new 9: c:=45;

OUTPUT:

C is maximum

PL/SQL procedure successfully completed.

SUMMATION OF ODD NUMBERS

SQL> declare
2 n number;
3 sum1 number default 0;
4 endvalue number;
5 begin
6 endvalue:=&endvalue;
7 n:=1;
8 for n in 1..endvalue
9 loop
10 if mod(n,2)=1
11 then
12sum1:=sum1+n;
13 en d if;
14 end loop;
15dbms_output.put_line('sum ='||sum1);
16 end;
17 /

INPUT:

Enter value for endvalue: 4


old 6: endvalue:=&endvalue;
new 6: endvalue:=4;

OUTPUT:

sum =4

PL/SQL procedure successfully completed.

57
COMMANDS EXECUTION:

SQL> create table customerspro(id number(5),name varchar2(10),address


varchar2(10)); Table created.
SQL> insert into customerspro values(121,'gopal','tvamalai');
1 row created.
SQL> insert into customerspro values(190,'velu','chennai');
1 row created.

1) NO_DATA_FOUND Error:

SQL> set serveroutput on;


SQL> declare
2 cid customerspro.id % type :=8;
3 cname customerspro.name % type;
4 caddr customers.address % type;
5 begin
6 select name,address into cname,caddr from customerspro where id=cid;
7 dbms_output.put_line('name:' || cname);
8 dbms_output.put_line('address:' || caddr);
9 exception
10 when no_data_found then
11 dbms_output.put_line('No such customer');
12 when others then
13 dbms_output.put_line('error');
14 end;
15 /
No such customer
PL/SQL procedure successfully completed.

2) TOO_MANY_ROWS Error:

SQL> declare
2 a customers.address % type;
3 begin
4 select address into a from customerspro;
5 dbms_output.put_line('The address is'|| a);
6 exception
7 when TOO_MANY_ROWS then
8 dbms_output.put_line('variable can hold only one value at a time');
9 dbms_output.put_line('Please specify the name of person for getting the address');
10 end;
11 /
variable can hold only one value at a time
Please specify the name of person for getting the address

PL/SQL procedure successfully completed.

3) ZERO_DIVIDE error

SQL> declare
2 x number;
3 y number;
4 z number;
5 begin
6 x := &x;
7 y := &y;
8 z := x/y;
9 dbms_output.put_line('The answer is ' || z);
10 Exception
11 When ZERO_DIVIDE then
12 dbms_output.put_line('Cannot divide by zero!!!');
13 end;
14 /
Enter value for x: 5
old 6: x := &x;
new 6: x := 5;
Enter value for y: 0
old 7: y := &y;
new 7: y := 0;
Cannot divide by zero!!!
PL/SQL procedure successfully completed.

4) VALUE_ERROR

SQL> set serveroutput on;


SQL> declare
2 n number;
3 begin
4 n := '&n';
5 dbms_output.put_line(n);
6 Exception
7 When VALUE_ERROR then
8 dbms_output.put_line('Please enter number only');
9 end;
10 /
Enter value for n: a
old 4: n := '&n';
new 4: n := 'a';
Please enter number only
PL/SQL procedure successfully completed.

User Defined Exception:


5) Raise_application error:

SQL> set serveroutput on;


SQL> declare
2 maths number;
3 Begin
4 maths := &maths;
5 if maths < 35 then
6 raise_application_error(-20001,'Failed');
7 else
8 dbms_output.put_line('Passed');
9 end if;
10 end;
11 /
Enter value for maths: 13
old 4: maths := &maths;
new 4: maths := 13;
declare
*
ERROR at line 1:
ORA-20001: Failed
ORA-06512: at line
6

6) Exception variable using Raise key word

SQL> set serveroutput on;


SQL> declare
2 p number;
3 n number := 6;
4 si number;
5 r number := 10.5;
6 EX exception;
7 Begin
8 p := &p;
9 if p < 100 then
10 raise EX;
11 else
12 si := (p * n * r) / 100;
13 dbms_output.put_line('The Simple Interest is '|| si);
14 end if;
15 Exception
16 When EX then
17 dbms_output.put_line('The principle amt should be greater than or equal to 100.');
18 end;
19 /
Enter value for p: 50
old 8: p := &p;
new 8: p := 50;
The principle amt should be greater than or equal to 100.
PL/SQL procedure successfully

completed.

:
CODINGS

SQL> create or replace procedure pali(str in varchar,rev out varchar) is


2 c number;
3 begin
4 c:=length(str);
5 while c>0 loop
6 rev:=rev||substr(str,c,1);
7 c:=c-1;
8 end loop;
9 end;
10 /
Procedure created.

SQL> declare
str varchar2(20):='&str';
3 rev varchar2(20);
4 begin
5 pali(str,rev);
6 dbms_output.put_line('given string is '||str);
7 dbms_output.put_line('reversed string is '||rev);
8 if str=rev then
9 dbms_output.put_line('palindrome');
10 else
11 dbms_output.put_line('not a palindrome');
12 end if;
13 end;
14 /
Enter value for str: deepa
old 2: str varchar2(20):='&str';
new 2: str varchar2(20):='deepa';
given string is deepa
reversed string is apeed
not a palindrome
PL/SQL procedure successfully completed.

SQL> create or replace procedure ins (regno number,name


varchar2,mark1 number,mark2 number,mark3 number) is
begin
insert into ins values(regno,name,mark1,mark2,mark3);
end;
/
Procedure created.
SQL> exec ins(1001,'vcbharathi',20,34,54);

PL/SQL procedure successfully completed.

SQL> select * from dee;

REGNO NAME MARK1 MARK2 MARK3


1001 vcbharathi 20 34 54

SQL> create or replace procedure disp(en in number, c out integer) as


2 enum number;
3 begin
4 select eno into enum from pay where
eno=en; 5 c:=1;
6 exception
7 when no_data_found then
8 c:=0;
9 end;
10 /

Procedure created.

SQL> declare
2 p pay%rowtype;
3 c integer;
4 begin
5 p.eno:=&pno;
6 disp(p.eno,c);
7 if c=1 then
8 select eno,name into p.eno,p.name from pay where eno=p.eno;
9 dbms_output.put_line('eno '||'name ');
10 dbms_output.put_line(p.eno ||p.name);
11 else
12 dbms_output.put_line('error enter the correct emp number');
13 end if;
14 end;
15 /
Enter value for pno: 101
old 5: p.eno:=&pno;
new 5: p.eno:=101;
eno name
101 vani

PL/SQL procedure successfully completed.

Multiplication Table using Declare Statement

SQL> declare
2 i number:=1;
3 n number(3);
4 p number:=0;
5 begin
6 n:=&n;
7 for i in 1..16 loop
8 p:=i*n;
9 dbms_output.put_line(i||'*'||n ||'='||p);
10 end loop;
11 end;
12 /
Enter value for n: 5
old 6: n:=&n;
new 6: n:=5;
PL/SQL procedure successfully completed.

SQL> set serveroutput on;


Enter value for n: 5
old 6: n:=&n;
new 6: n:=5;
1*5=5
2*5=10
3*5=15
4*5=20
5*5=25
6*5=30
7*5=35
8*5=40
9*5=45
10*5=50
11*5=55
12*5=60
13*5=65
14*5=70
15*5=75
16*5=80
PL/SQL procedure successfully completed.

Sum of odd numbers using Declare Statement

declare
i number:=1;
n number(3);
f number:=0;
begin
n:=&n;
while i<=n loop
f:=f+i;
i:=i+2;
end loop;
dbms_output.put_line('sum of odd numbers:'||f);
end;
SQL> /
Enter value for n:
5 old 6: n:=&n;
new 6: n:=5;
sum of odd numbers:9

PL/SQL procedure successfully completed.

Sum of even numbers using Declare Statement


1 declare
2 i number:=0;
3 n number(3);
4 f number:=0;
5 begin
6 n:=&n;
7 while i<=n
loop 8 f:=f+i;
9 i:=i+2;
10 end loop;
11 dbms_output.put_line('sum of even numbers:'||f);
12 end;

SQL> /
Enter value for n:
5 old 6: n:=&n;
new 6: n:=5;
sum of even numbers:6

PL/SQL procedure successfully completed.

SQL> create table stud(rno number(2),mark1 number(3),mark2 number(3),total


number(3),primary key(rno));

Table created.

SQL> desc stud;


Name Null? Type

RNO NOT NULL NUMBER(2)


MARK1 NUMBER(3)
MARK2 NUMBER(3)
TOTAL NUMBER(3)
SQL> select * from stud;

RNO MARK1 MARK2 TOTAL

1 80 85 0
2 75 84 0
3 65 80 0
4 90 85 0
SQL> create or replace procedure studd(rnum number) is
m1 number;
m2 number;
total number;
begin
select mark1,mark2 into m1,m2 from stud where rno=rnum;
if m1<m2 then
update stud set total=m1+m2 where rno=rnum;
end if;
end;
/
Procedure created.
SQL> exec studd(1);

PL/SQL procedure successfully

completed. SQL> select * from stud;

RNO MARK1 MARK2 TOTAL

1 80 85 165
2 75 84 0
3 65 80 0
4 90 85 0

SQL> exec studd(2);

PL/SQL procedure successfully completed.

SQL> exec studd(3);

PL/SQL procedure successfully

completed. SQL> select * from stud;

RNO MARK1 MARK2 TOTAL

1 80 85 165
2 75 84 159
3 65 80 145
4 90 85 0

EXECUTION
1. Create trigger with before insertion
SQL> create table orders(order_id number(10),quantity
number(10),cost_per_item numeric(6,2),total_cost numeric(8,2),create_date
date,created_by varchar2(20));

Table created.

1 create or replace trigger o_before_insert


2 before insert
3 on orders
4 for each row
5 declare
6 v_username varchar2(20);
7 begin
8 select user into v_username from dual;
9 :new.create_date:=sysdate;
10 :new.created_by:=v_username;
11* end;
SQL> /

Trigger created.
To Check the created trigger:
SQL> insert into orders values(10,20,30,40,'23-jun-2006','user4');

1 row created.

SQL> select * from orders;

ORDER_ID QUANTITY COST_PER_ITEM TOTAL_COST CREATE_DA


CREATED_BY
10 20 30 40 21-AUG-07
UNIV04

2. Create Trigger with after insertion:

SQL> create table order4(order_id number(10),quantity


number(10),cost_per_item numeric(6,2),total_cost numeric(8,2));
Table created.

SQL> create table orders_audit(order_id number(10),quantity number(10),cost_per_item


numeric(6,2),total_cost numeric(8,2),username varchar2(20));
Table created.

create or replace trigger orders_after_insert


after insert
on order4
for each
row declare
v_username varchar2(20);
begin
select user into v_username from dual;
insert into orders_audit(order_id,quantity,cost_per_item,total_cost,username)
values(:new.order_id,:new.quantity,:new.cost_per_item,:new.total_cost,v_username);
10 end;
SQL> /

Trigger created.

To Check the created Trigger:

SQL> insert into order4 values(10,202,30,50);


1 row created.

SQL> select * from orders_audit;

ORDER_ID QUANTITY COST_PER_ITEM TOTAL_COST USERNAME

10 202 30 50 UNIV04

3. Create a trigger with before update:

SQL> create table order1(order_id number(10),quantity


number(10),cost_per_item numeric(6,2),total_cost numeric(8,2),updated_date
date,updated_by varchar2(20));

Table created.

create or replace trigger orders_before_update


before update
on order1
for each row
declare
v_username varchar2(20);
begin
select user into v_username from dual;
:new.updated_date:=sysdate;
:new.updated_by:=v_username;
* end;
SQL> /
Trigger created.

To Check the created Trigger:


SQL> insert into order1 values(10,202,30,50,'23=jul-2006','user4');

1 row created.

SQL> update order1 set total_cost=1000 where order_id=10;

1 row updated.

SQL> select * from order1;

ORDER_ID QUANTITY COST_PER_ITEM TOTAL_COST UPDATED_D


UPDATED_BY

10 202 30 1000 21-AUG-07


UNIV04

4. Create a Trigger with after update:

SQL> create table order2(order_id number(10),quantity


number(10),cost_per_item numeric(6,2),total_cost numeric(8,2));

Table created.

SQL> create table orders_audit1(order_id number(10),quantity_before


number(10),quantity_after number(10),username varchar2(20));

Table created.

1 create or replace trigger orders_after_update


2 after update
3 on order2
4 for each row
5 declare
6 v_username varchar2(20);
7 begin
8 select user into v_username from dual;
9 insert intoorders_audit1(order_id,quantity_before,quantity_after,username)
values(:new.order_id,:old.quantity,:new.quantity,v_username);
10* end;
SQL> /

Trigger created.

To Check the created Trigger:


SQL> insert into order2 values(10,202,30,50);
1 row created.

SQL> update order2 set quantity=100 where order_id=10;


1 row updated.

SQL> select * from orders_audit1;

ORDER_ID QUANTITY_BEFORE QUANTITY_AFTER USERNAME

10 202 100 UNIV04

5. Create a Trigger with after delete:

SQL> create table order3(order_id number(10),quantity number(10),cost_per_item


numeric(6,2),total_cost numeric(8,2));

Table created.

SQL> create table orders_audit2(order_id number(10),quantity


number(10),cost_per_item number(10),total_cost number(10),delete_date
date,deleted_by varchar2(20));

Table created.

1 create or replace trigger orders_after_delete


2 after delete
3 on order3
4 for each row
5 declare
6 v_username varchar2(20);
7 begin
8 select user into v_username from dual;
9 insert into
orders_audit2(order_id,quantity,cost_per_item,total_cost,delete_date,deleted_by)
10 values(:old.order_id,:old.quantity,:old.cost_per_item,
:old.total_cost,sysdate,v_username);
11* end;
SQL> /
Trigger created.

To Check the output:


SQL> insert into order3 values(10,2,90,50);
1 row created.

SQL> insert into order3 values(10,20,300,450);


1 row created.

SQL> delete order3 where order_id=10;


2 rows deleted.
SQL> select * from orders_audit2;

ORDER_ID QUANTITY COST_PER_ITEM TOTAL_COST DELETE_DA


DELETED_BY

10 2 90 50 21-AUG-07
UNIV04
10 20 300 450 21-AUG-07
UNIV04

FUNCTIONS
Function(Factorial of N numbers)

SQL> create or replace function fac(n integer)


2 return integer is
3 f number;
4 begin
5 f:=1;
6 for i in 1..n
7 loop
8 f:=f*i;
9 end loop;
10 return f;
11 end;
12 /

Function created.

SQL> select fac(4) from dual;

FAC(4)

24
Functions(largest of two numbers)

SQL> create or replace function large23(a in number,b in number) return number is


begin
if a>b then
return a;
else
return b;
end if;
end;
/
Function created.

SQL> select large23 (50, 12) from dual;

LARGE23 (50, 12)


50

Functions(largest of three numbers)

SQL>create or replace function large1(a in number,b in number,c in number) return


number is
2 begin
3 if a>b and a>c
then 4 return a;
5 else if b>c then
6 return b;
7 else
8 return c;
9 end if;
10 end if;
11 end;
12 /
Function created.

SQL> select large1 (10, 20, 30) from dual;

LARGE1 (10, 20, 30)

30
Function (To find the rate of the quantity)

create table purchase (icode number(3),iname varchar2(13),price number(6),quantity


number(3),rate number(8),primary key(icode),unique(iname));
Table created.

SQL> desc purchase;

Name Null? Type

ICODE NOT NULL NUMBER(3)


INAME VARCHAR2(13)
PRICE NUMBER(6)
QUANTITY NUMBER(3)
RATE NUMBER(8)

SQL> select * from purchase;

ICODE INAME PRICE QUANTITY RATE

100 LUX 20 10 0
101 CINTHOL 60 10 0
102 180pg NOTE 24 10 0
103 5 STAR 10 25 0
104 STICK FILE 10 20 0
SQL> create or replace function pur(itmcd number) return number is
2 qt number;
3 pr number;
4 rate number;
5 begin
6 select price,quantity into pr,qt from purchase where icode=itmcd;
7 rate:=qt*pr;
8 return rate;
9 end;
10 /

Function created.

SQL> select pur(102) from dual;

PUR(102)

240
Create a table in oracle

SQL> create table studentaec(name varchar2(10),regno number(5), dep varchar2(10));

Table created.

SQL> insert into studentaec values('&name','&regno','&dep');


Enter value for name: ram
Enter value for regno: 105
Enter value for dep: cse
old 1: insert into studentaec values('&name','&regno','&dep')
new 1: insert into studentaec values('ram','105','cse')

1 row
created.

SQL> /
Enter value for name: kumar
Enter value for regno: 390
Enter value for dep: eee
old 1: insert into studentaec values('&name','&regno','&dep')
new 1: insert into studentaec values('kumar','390','eee')

1 row

created.

SQL> /
Enter value for name: babu
Enter value for regno: 490
Enter value for dep: ece
old 1: insert into studentaec values('&name','&regno','&dep')
new 1: insert into studentaec values('babu','490','ece')

1 row

created.

SQL> /
Enter value for name: raj
Enter value for regno: 567
Enter value for dep: cse
old 1: insert into studentaec values('&name','&regno','&dep')
new 1: insert into studentaec values('raj','567','cse')

1 row created.

SQL> /
Enter value for name: venkat
Enter value for regno: 456
Enter value for dep: cse
old 1: insert into studentaec values('&name','&regno','&dep')
new 1: insert into studentaec values('venkat','456','cse')

1 row created.
SQL> select * from

studentaec; NAME REGNO

DEP

ram 105 cse


kumar 390 eee
babu 490 ece
raj 567 cse
venkat 456 cse
commit;
SQL> commit completed.

1. Select the Microsoft Visual Basic 6.0 from the Start menu.

2. Select the Project type as Standard EXE and click Open.

3. Design the form with needed tools. Place the ADODC tool in the form by the
following steps.
4. Click on the ADODC Tool and select ADODC propertites and to make
the connection do the following steps.
Then click ok and by these following steps the connection bewteen the oracle and VB
has been established. Then run the project.

Thus the records which has been inserted in the oracle which act as back end.
Code:
Private Cn As New ADODB.Connection
Private Rs As New ADODB.Recordset

Private Sub cmdAppointment_Click()


frmAppointment.Show vbModal, Me
End Sub

Private Sub cmdClose_Click()


End
End Sub

Private Sub cmdDoctors_Click()


frmDoctors.Show vbModal, Me
End Sub

Private Sub cmdPatient_Click()


frmPatient.Show vbModal, Me
End Sub

Private Sub Form_Load()


Set Cn = New ADODB.Connection
Set Rs = New ADODB.Recordset

Cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" &


App.Path & "\db.mdb;"
Cn.Open
End Sub
Private Sub Form_Unload(Cancel As Integer)
If Rs.State = 1 Then Rs.Close
If Cn.State = 1 Then Cn.Close
Set Cn = Nothing
Set Rs = Nothing
End Sub

FormAppointment:
Design View:
Code:
Private Cn As New ADODB.Connection
Private Rs As New ADODB.Recordset

Private Sub cmdAppointment_Click()


Rs.Open "Select * from tblAppointments"
Rs.AddNew
Rs!DoctorID = Val(cmbDoctor.Text) Rs!
PatientID = Val(cmbPatient.Text) Rs!
AppointmentDate = CDate(dtp.Value)
Rs.Update

MsgBox "Check In Successful!", vbInformation, "Success"


Unload Me
End Sub

Private Sub Form_Load()


Set Cn = New ADODB.Connection
Set Rs = New ADODB.Recordset

Cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" &


App.Path & "\db.mdb;"
Cn.Open

Rs.Open "Select Distinct DoctorID from tblDoctors", Cn, adOpenKeyset,


adLockOptimistic
Do Until Rs.EOF
cmbDoctor.AddItem (Rs.Fields("DoctorID"))
Rs.MoveNext
DoEvents
Loop
Rs.Close

Rs.Open "Select Distinct ID from tblPatients", Cn, adOpenKeyset, adLockOptimistic


Do Until Rs.EOF
cmbPatient.AddItem (Rs.Fields("ID"))
Rs.MoveNext
DoEvents
Loop
Rs.Close

End Sub
Private Sub Form_Unload(Cancel As Integer)
If Rs.State = 1 Then Rs.Close
If Cn.State = 1 Then Cn.Close
Set Cn = Nothing
Set Rs = Nothing
End Sub

FormPatient:
Design View:

Code:
Private Cn As New ADODB.Connection
Private Rs As New ADODB.Recordset

Private Sub cmdDelete_Click()


Cn.Execute "Delete from tblPatients where ID='" & txtID.Text & "'"

Dim ctl As Control


For Each ctl In Me
If TypeOf ctl Is TextBox Then
ctl.Locked = True
ctl.Text = ""
End If
Next

cmdNew.Enabled = True
cmdEdit.Enabled = False
cmdFind.Enabled = True
cmdDelete.Enabled = False

End Sub

Private Sub cmdEdit_Click()


Dim ctl As Control
If cmdEdit.Caption = "Edit" Then
For Each ctl In Me
If TypeOf ctl Is TextBox Then
ctl.Locked = False
End If
Next
txtID.Locked = True
txtName.SetFocus
cmdEdit.Caption = "Update"
cmdNew.Enabled = False
cmdDelete.Enabled = False
cmdFind.Enabled = False
Else
Rs.Open "Select * from tblPatients where ID='" & Val(txtID.Text) & "'", Cn,
adOpenKeyset, adLockOptimistic
If Rs.EOF = False Then Rs!
PName = txtName.Text Rs!
Address = txtAddress.Text Rs!
Phone = Val(txtPhone.Text)
Rs.Update
MsgBox "Successfully updated!", vbInformation
End If
Rs.Close
cmdEdit.Caption =
"Edit" cmdNew.Enabled
= True cmdEdit.Enabled
= False
cmdDelete.Enabled = False
cmdFind.Enabled = True

For Each ctl In Me


If TypeOf ctl Is TextBox Then
ctl.Locked = True
ctl.Text = ""
End If
Next

End If
End Sub

Private Sub cmdFind_Click()


Dim s As Integer
s = InputBox("Enter Patient ID:", "Search")
If Val(s) = 0 Then
MsgBox "Invalid Patient ID", vbExclamation, "Search Failed"
Exit Sub
End If
Rs.Open "Select * from tblPatients where ID='" & (s) & "'", Cn, adOpenKeyset,
adLockOptimistic
If Rs.EOF Then
MsgBox "No record found!", vbExclamation
Rs.Close
Exit Sub
End If
txtID.Text = Rs!ID
txtName.Text = Rs!PName
txtAddress.Text = Rs!Address
txtPhone.Text = Rs!Phone
Rs.Close

Dim ctl As Control


For Each ctl In Me
If TypeOf ctl Is TextBox Then
ctl.Locked = True
End If
Next

cmdDelete.Enabled = True
cmdEdit.Enabled = True
End Sub

Private Sub cmdNew_Click()


Dim ctl As Control
If cmdNew.Caption = "New" Then
For Each ctl In Me
If TypeOf ctl Is TextBox Then
ctl.Locked = False
ctl.Text = ""
End If
Next
txtID.SetFocus
cmdNew.Caption = "Save"
cmdEdit.Enabled = False
cmdDelete.Enabled = False
cmdFind.Enabled = False
Else
Rs.Open "Select * from tblPatients where ID='" & Val(txtID.Text) & "'", Cn,
adOpenKeyset, adLockOptimistic
If Rs.EOF Then
Rs.AddNew
Rs!ID = Val(txtID.Text) Rs!
PName = txtName.Text Rs!
Address = txtAddress.Text Rs!
Phone = Val(txtPhone.Text)
Rs.Update
MsgBox "Successfully added!", vbInformation
Else
MsgBox "Patient already exists!",
vbExclamation End If
Rs.Close
cmdNew.Caption = "New"
cmdEdit.Enabled = False
cmdDelete.Enabled = False
cmdFind.Enabled = True

For Each ctl In Me


If TypeOf ctl Is TextBox Then
ctl.Locked = True
ctl.Text = ""
End If
Next

End If

End Sub
Private Sub Form_Load()
Set Cn = New ADODB.Connection
Set Rs = New ADODB.Recordset

Cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" &


App.Path & "\db.mdb;"
Cn.Open

cmdNew.Caption = "New"

Dim ctl As Control


For Each ctl In Me
If TypeOf ctl Is TextBox Then
ctl.Locked = True
End If
Next
End Sub

Private Sub Form_Unload(Cancel As Integer)


If Rs.State = 1 Then Rs.Close
If Cn.State = 1 Then Cn.Close
Set Cn = Nothing
Set Rs = Nothing
End Sub

FormDoctors:
Design View:

Code:
Private Cn As New ADODB.Connection
Private Rs As New ADODB.Recordset

Private Sub cmdDelete_Click()


Cn.Execute "Delete from tblDoctors where DoctorID='" & txtID.Text & "'"
Dim ctl As Control
For Each ctl In Me
If TypeOf ctl Is TextBox Then
ctl.Locked = True
ctl.Text = ""
End If
Next

cmdNew.Enabled = True
cmdEdit.Enabled = False
cmdFind.Enabled = True
cmdDelete.Enabled = False

End Sub

Private Sub cmdEdit_Click()


Dim ctl As Control
If cmdEdit.Caption = "Edit" Then

For Each ctl In Me


If TypeOf ctl Is TextBox Then
ctl.Locked = False
End If
Next
txtID.Locked = True
cmbType.SetFocus
cmdEdit.Caption = "Update"
cmdNew.Enabled = False
cmdDelete.Enabled = False
cmdFind.Enabled = False
Else
Rs.Open "Select * from tblDoctors where DoctorID='" & Val(txtID.Text) & "'", Cn,
adOpenKeyset, adLockOptimistic
If Rs.EOF = False Then Rs!
Name = txtName.Text
Rs!Specialization = txtSpecialization.Text
Rs.Update
MsgBox "Successfully updated!", vbInformation
End If
Rs.Close
cmdEdit.Caption =
"Edit" cmdNew.Enabled
= True cmdEdit.Enabled
= False
cmdDelete.Enabled = False
cmdFind.Enabled = True

For Each ctl In Me


If TypeOf ctl Is TextBox Then
ctl.Locked = True
ctl.Text = ""
End If
Next
End If
End Sub

Private Sub cmdFind_Click()


Dim s As Integer
s = InputBox("Enter Doctor ID:", "Search")
If Val(s) = 0 Then
MsgBox "Invalid ID", vbExclamation, "Search
Failed" Exit Sub
End If
Rs.Open "Select * from tblDoctors where DoctorID='" & (s) & "'", Cn,
adOpenKeyset, adLockOptimistic
If Rs.EOF Then
MsgBox "No record found!", vbExclamation
Rs.Close
Exit Sub
End If
txtID.Text = Rs!DoctorID
txtName.Text = Rs!Name
txtSpecialization.Text = Rs!Specialization
Rs.Close

Dim ctl As Control


For Each ctl In Me
If TypeOf ctl Is TextBox Then
ctl.Locked = True
End If
Next

cmdDelete.Enabled = True
cmdEdit.Enabled = True
End Sub
Private Sub cmdNew_Click()
If cmdNew.Caption = "New" Then

Dim ctl As Control


For Each ctl In Me
If TypeOf ctl Is TextBox Then
ctl.Locked = False
ctl.Text = ""
End If
Next
txtID.SetFocus
cmdNew.Caption = "Save"
cmdEdit.Enabled = False
cmdDelete.Enabled = False
cmdFind.Enabled = False
Else
Rs.Open "Select * from tblDoctors where DoctorID='" & Val(txtID.Text) & "'", Cn,
adOpenKeyset, adLockOptimistic
If Rs.EOF Then
Rs.AddNew
Rs!DoctorID = Val(txtID.Text) Rs!
Name = txtName.Text
Rs!Specialization = txtSpecialization.Text
Rs.Update
MsgBox "Successfully added!", vbInformation
Else
MsgBox "Doctor already exists!", vbExclamation
End If
Rs.Close
cmdNew.Caption = "New"
cmdEdit.Enabled = False
cmdDelete.Enabled = False
cmdFind.Enabled = True
For Each ctl In Me
If TypeOf ctl Is TextBox Then
ctl.Locked = True
ctl.Text = ""
End If
Next
End If
End Sub

Private Sub Form_Load()


Set Cn = New ADODB.Connection
Set Rs = New ADODB.Recordset
Cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" &
App.Path & "\db.mdb;"
Cn.Open
cmdNew.Caption = "New"
Dim ctl As Control
For Each ctl In Me
If TypeOf ctl Is TextBox Then
ctl.Locked = True
ctl.Text = ""
End If
Next
End Sub

Private Sub Form_Unload(Cancel As Integer)


If Rs.State = 1 Then Rs.Close
If Cn.State = 1 Then Cn.Close
Set Cn = Nothing
Set Rs = Nothing
End Sub
Code:
Private Cn As New ADODB.Connection
Private Rs As New ADODB.Recordset

Private Sub cmdClose_Click()


End
End Sub

Private Sub cmdItems_Click()


frmItems.Show vbModal, Me
End Sub

Private Sub cmdOrders_Click()


frmOrders.Show vbModal, Me
End Sub

Private Sub Form_Load()


Set Cn = New ADODB.Connection
Set Rs = New ADODB.Recordset
Cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" &
App.Path & "\db.mdb;"
Cn.Open
End Sub

Private Sub Form_Unload(Cancel As Integer)


If Rs.State = 1 Then Rs.Close
If Cn.State = 1 Then Cn.Close
Set Cn = Nothing
Set Rs = Nothing
End Sub
frmItems:
Design View:
Code:
Private Cn As New ADODB.Connection
Private Rs As New ADODB.Recordset

Private Sub cmdDelete_Click()


Cn.Execute "Delete from tblItems where ID='" & txtID.Text & "'"

Dim ctl As Control


For Each ctl In Me
If TypeOf ctl Is TextBox Then
ctl.Locked = True
ctl.Text = ""
End If
Next

cmdNew.Enabled = True
cmdEdit.Enabled = False
cmdFind.Enabled = True
cmdDelete.Enabled = False

End Sub

Private Sub cmdEdit_Click()


Dim ctl As Control
If cmdEdit.Caption = "Edit" Then
For Each ctl In Me
If TypeOf ctl Is TextBox Then
ctl.Locked = False
End If
Next
txtID.Locked = True
txtName.SetFocus
cmdEdit.Caption = "Update"
cmdNew.Enabled = False
cmdDelete.Enabled = False
cmdFind.Enabled = False
Else
Rs.Open "Select * from tblItems where ID='" & Val(txtID.Text) & "'", Cn,
adOpenKeyset, adLockOptimistic
If Rs.EOF = False Then Rs!
Name = txtName.Text
Rs!Price = txtCost.Text
Rs!Qty = Val(txtQty.Text)
Rs.Update
MsgBox "Successfully updated!", vbInformation
End If
Rs.Close
cmdEdit.Caption =
"Edit" cmdNew.Enabled
= True cmdEdit.Enabled
= False
cmdDelete.Enabled = False
cmdFind.Enabled = True

For Each ctl In Me


If TypeOf ctl Is TextBox Then
ctl.Locked = True
ctl.Text = ""
End If
Next

End If
End Sub

Private Sub cmdFind_Click()


Dim s As Integer
s = InputBox("Enter ID:", "Search")
If Val(s) = 0 Then
MsgBox "Invalid ID", vbExclamation, "Search
Failed" Exit Sub
End If
Rs.Open "Select * from tblItems where ID='" & (s) & "'", Cn, adOpenKeyset,
adLockOptimistic
If Rs.EOF Then
MsgBox "No record found!", vbExclamation
Rs.Close
Exit Sub
End If
txtID.Text = Rs!ID
txtName.Text = Rs!Name
txtCost.Text = Rs!Price
txtQty.Text = Rs!Qty
Rs.Close

Dim ctl As Control


For Each ctl In Me
If TypeOf ctl Is TextBox Then
ctl.Locked = True
End If
Next

cmdDelete.Enabled = True
cmdEdit.Enabled = True
End Sub
Private Sub cmdNew_Click()
Dim ctl As Control
If cmdNew.Caption = "New" Then
For Each ctl In Me
If TypeOf ctl Is TextBox Then
ctl.Locked = False
ctl.Text = ""
End If
Next
txtID.SetFocus
cmdNew.Caption = "Save"
cmdEdit.Enabled = False
cmdDelete.Enabled = False
cmdFind.Enabled = False
Else
Rs.Open "Select * from tblCustomers where ID='" & Val(txtID.Text) & "'", Cn,
adOpenKeyset, adLockOptimistic
If Rs.EOF Then
Rs.AddNew
Rs!ID = Val(txtID.Text)
Rs!Name = txtName.Text
Rs!Price = txtCost.Text
Rs!Qty = Val(txtQty.Text)
Rs.Update
MsgBox "Successfully added!", vbInformation
Else
MsgBox "Item already exists!", vbExclamation
End If
Rs.Close
cmdNew.Caption = "New"
cmdEdit.Enabled = False
cmdDelete.Enabled = False
cmdFind.Enabled = True

For Each ctl In Me


If TypeOf ctl Is TextBox Then
ctl.Locked = True
ctl.Text = ""
End If
Next

End If
End Sub

Private Sub Form_Load()


Set Cn = New ADODB.Connection
Set Rs = New ADODB.Recordset

Cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" &


App.Path & "\db.mdb;"
Cn.Open
cmdNew.Caption = "New"
Dim ctl As Control
For Each ctl In Me
If TypeOf ctl Is TextBox Then
ctl.Locked = True
End If
Next
End Sub

Private Sub Form_Unload(Cancel As Integer)


If Rs.State = 1 Then Rs.Close
If Cn.State = 1 Then Cn.Close
Set Cn = Nothing
Set Rs = Nothing
End Sub

FormOrders:
Design View:

Code:
Private Cn As New ADODB.Connection
Private Rs As New ADODB.Recordset

Private Sub cmdDelete_Click()


Cn.Execute "Delete from tblOrders where ID='" & txtID.Text & "'"

Dim ctl As Control


For Each ctl In Me
If TypeOf ctl Is TextBox Then
ctl.Locked = True
ctl.Text = ""
End If
Next

cmdNew.Enabled = True
cmdEdit.Enabled = False
cmdFind.Enabled = True
cmdDelete.Enabled = False

End Sub
Private Sub cmdEdit_Click()
Dim ctl As Control
If cmdEdit.Caption = "Edit" Then

For Each ctl In Me


If TypeOf ctl Is TextBox Then
ctl.Locked = False
End If
Next
txtID.Locked = True
cmbType.SetFocus
cmdEdit.Caption = "Update"
cmdNew.Enabled = False
cmdDelete.Enabled = False
cmdFind.Enabled = False
Else
Rs.Open "Select * from tblOrders where ID='" & Val(txtID.Text) & "'", Cn,
adOpenKeyset, adLockOptimistic
If Rs.EOF = False Then Rs!
Items = txtItems.Text
Rs!OrderDate = CDate(dtp.Value)
Rs!Cost = txtCost.Text
Rs.Update
MsgBox "Successfully updated!", vbInformation
End If
Rs.Close
cmdEdit.Caption =
"Edit" cmdNew.Enabled
= True cmdEdit.Enabled
= False
cmdDelete.Enabled = False
cmdFind.Enabled = True

For Each ctl In Me


If TypeOf ctl Is TextBox Then
ctl.Locked = True
ctl.Text = ""
End If
Next

End If
End Sub

Private Sub cmdFind_Click()


Dim s As Integer
s = InputBox("Enter Order ID:", "Search")
If Val(s) = 0 Then
MsgBox "Invalid ID", vbExclamation, "Search
Failed" Exit Sub
End If
Rs.Open "Select * from tblOrders where ID='" & (s) & "'", Cn, adOpenKeyset,
adLockOptimistic
If Rs.EOF Then
MsgBox "No record found!", vbExclamation
Rs.Close
Exit Sub
End If
txtID.Text = Rs!ID
txtItems.Text = Rs!Items
txtCost = Rs!Cost
dtp.Value = CDate(Rs!OrderDate)
Rs.Close

Dim ctl As Control


For Each ctl In Me
If TypeOf ctl Is TextBox Then
ctl.Locked = True
End If
Next
cmdDelete.Enabled = True
cmdEdit.Enabled = True
End Sub

Private Sub cmdNew_Click()


Dim ctl As Control
If cmdNew.Caption = "New" Then

For Each ctl In Me


If TypeOf ctl Is TextBox Then
ctl.Locked = False
ctl.Text = ""
End If
Next

txtID.SetFocus
cmdNew.Caption = "Save"
cmdEdit.Enabled = False
cmdDelete.Enabled = False
cmdFind.Enabled = False
Else
Rs.Open "Select * from tblOrders where ID='" & Val(txtID.Text) & "'", Cn,
adOpenKeyset, adLockOptimistic
If Rs.EOF Then
Rs.AddNew
Rs!ID = Val(txtID.Text) Rs!
Cost = txtCost.Text Rs!Items
= txtItems.Text
Rs!OrderDate = CDate(dtp.Value)
Rs.Update
MsgBox "Successfully added!", vbInformation
Else
MsgBox "ID already exists!",
vbExclamation End If
Rs.Close
cmdNew.Caption = "New"
cmdEdit.Enabled = False
cmdDelete.Enabled = False
cmdFind.Enabled = True

For Each ctl In Me


If TypeOf ctl Is TextBox Then
ctl.Locked = True
ctl.Text = ""
End If
Next

End If

End Sub

Private Sub Form_Load()


Set Cn = New ADODB.Connection
Set Rs = New ADODB.Recordset

Cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" &


App.Path & "\db.mdb;"
Cn.Open

cmdNew.Caption = "New"

Dim ctl As Control


For Each ctl In Me
If TypeOf ctl Is TextBox Then
ctl.Locked = True
ctl.Text = ""
End If
Next
End Sub
Private Sub Form_Unload(Cancel As Integer)
If Rs.State = 1 Then Rs.Close
If Cn.State = 1 Then Cn.Close
Set Cn = Nothing
Set Rs = Nothing
End Sub

You might also like