C
0 0
42
AIM:
The aim of this laboratory is to inculcate the abilities of applying the principles of the
database management systems. This course aims to prepare the students for projects where a proper
implementation of databases will be required.
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
LIST OF EXPERIEMENTS
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
TOTAL: 60 PERIODS
OUTCOMES:
1
LIST OF EXPERIMENTS:
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
BEYOND SYLLABUS
MINI PROJECT
2
VEL TECH MULTI TECH
Dr. RANGARAJAN Dr. SAKUNTHALA ENGINEERING COLLEGE
COURSE OBJECTIVES:
Ex. Allotted
Experiment Name CO Mapping
No. hours
Data Definition Commands, Data Manipulation Commands for
6 Hours
1 inserting, deleting, updating and retrieving Tables and CO1
Transaction Control statements.
6 Hours
5 Procedures and Functions. CO3
3
6 Hours
7 Exception Handling . CO3
3 Hours
10 Case Study using real life database applications. CO4
Course Outcome:
CS8481.5 Critically analyze the use of Tables, Views, Functions and Procedures
CS8481.6 Normalized database design to ensure the quality
4
Ex. 1. Data Definition Commands, Data Manipulation Commands for
inserting, deleting, updating and retrieving Tables and Transaction Control
statements
Aim : To create database and perform DML and TCL queries to retrieve information from the
database.
BACKGROUND THEORY:
1. Creation of Table: Creates a table with specified attributes and its data type along with
constraints.
Syntax:
Create table r (A1 D1 , A2 D2,………An Dn,
(integrity-constraint1),
….,
(integrity-constraintk));
where r – relation name(Table name),
Ai – Attribute name,
Di – Data type.
Data Types in SQL:
5
1. char(n) : Fixed-length character string (can contain letters, numbers, and special
characters). The fixed size is specified in parenthesis. Can store up to 255 characters
2. varchar(n) : Variable-length string (can contain letters, numbers, and special
characters). The maximum size is specified in parenthesis. Can store up to 255 characters. Note:
If you put a greater value than 255 it will be converted to a TEXT type
3. int : Integer -2147483648 to 2147483647 normal. 0 to 4294967295. The maximum
number of digits may be specified in parenthesis
4. smallint : Small Integer -32768 to 32767 normal. 0 to 65535 UNSIGNED*. The
maximum number of digits may be specified in parenthesis
5. numeric(p,d) : The number consists of p digits(plus a sign), d of the p digits are to
the right of the decimal point.
6. float(n,d) : Floating-point number. The maximum number of digits may be
specified in the size parameter. The maximum number of digits to the right of the decimal point
is specified in the d parameter
7. double (size,d): A large number with a floating decimal point. The maximum
number of digits may be specified in the size parameter. The maximum number of digits to the
right of the decimal point is specified in the d parameter.
8. date : The date containing a date, month and year. Used to store date value as
DD-MON-YY, data size is 9 byte
Format: YYYY-MM-DD
Note: The supported range is from '1000-01-01' to '9999-12-31'
9. time : The time in hours, minutes and seconds.
Format: HH:MM:SS
10. timestamp : The combination of date and time.
Format: YYYY-MM-DD HH:MM:SS
6
Syntax-
(i) Select A1,A2.. ,An from r1
(ii) Select * from r1;
(iii) Select A1,A2.. ,An from r1,r2,..,rn;
(iv) Select A1,A2.. ,An from r1,r2,..,rn where condition;
Example-
(i) Select CustID,Custname from customer ;
(ii) Select CustID,Custname from customer where Custname=’Arun’);
DDL Commands:
Create
Alter
Rename
Drop
Altering the Table Schema: Add or delete or change the attribute and data type.
It also can add or drop the integrity constraints.
Syntax:
1. Alter table r add (Ai Di);
2. Alter table r drop(Ai);
3. Alter table r modify(Ai Di);
4. Alter table r add primary key(Ai);
5. Alter table r enable primary key;
6. Alter table r disable primary key;
Eg:
Alter table customer add ( phoneno int(12));
Alter table customer drop( custcity);
Alter table customer modify( custname varchar2(20));
Alter table depositor add primary key(acctno);
Alter table depositor disable primary key;
Alter table depositor enable primary key;
Dropping the Table: Deletes all information and structure about that table(relation)
Syntax:
7
Drop table r;
Eg:
Drop table customer;
1. Procedural DMLs – requires a user to specify what data are needed and how to get
those data.
2. Declarative DMLs ( nonprocedural language) - requires a user to specify what data are
needed without specifying how to get those data.
DML Component of SQL language is nonprocedural language.
(ii) Syntax-
Insert into r values(‘&A1’,’&A2’,….,’&An’); // where Ai – Attribute
Example-
Insert into customer values (‘&CustID’, ’&Custname’, ’&Custstreet’,
’&Custcity’);
2. Retrieval of Information by Select Command
(i) Syntax-
Select A1,A2.. ,An from r1,r2,..,rn where condition;
Example-
Select CustID,Custname from customer where Custname=’Arun’);
8
4. Deletion of information-
Syntax-
Delete from r where condition;
Example-
Delete from customer where Custname=’Arun’;
5. Truncating a Table: Deletes the records and not the structure of a table.
Syntax:
Truncate table r;
Ex:
Truncate table customer;
The NOT NULL constraint enforces a column to NOT accept NULL values.
The NOT NULL constraint enforces a field to always contain a value. The following SQL
enforces the "P_Id" column and the "LastName" column to not accept NULL values:
UNIQUE Constraints
9
Eg
CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
To create a UNIQUE constraint on the "P_Id" column when the table is already created, use the
following SQL:
CHECK Constraints
The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a single column it allows only certain values for this
column.
The following SQL creates a CHECK constraint on the "P_Id" column when the "Persons"
table is created. The CHECK constraint specifies that the column "P_Id" must only include integers
greater than 0.
10
ALTER TABLE Persons
ADD CHECK (P_Id>0)
DEFAULT Constraints
To create a DEFAULT constraint on the "City" column when the table is already created
without city column, use the following SQL:
The PRIMARY KEY constraint uniquely identifies each record in a database table.
Each table should have a primary key, and each table can have only one primary key.
The following SQL creates a PRIMARY KEY on the "P_Id" column when the "Persons" table is
created:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
);
11
To add a PRIMARY KEY constraint, use the following SQL:
Note: If you use the ALTER TABLE statement to add a primary key, the primary key column(s)
must already have been declared to not contain NULL values (when the table was first created).
The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
The FOREIGN KEY constraint is used to prevent actions that would destroy link
between tables.
The FOREIGN KEY constraint also prevents that invalid data is inserted into the foreign
key column, because it has to be one of the values contained in the table it points to
Let's illustrate the foreign key with an example. Look at the following two tables:
12
Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons"
table. The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
To create a FOREIGN KEY constraint on the "P_Id" column when the "Orders" table is already
created, use the following SQL:
Adding & Deleting the Constraints to the Table using constraint Names:
This example demonstrates how to specify constraints with constraint name during table
creation
create table salary_table (
fiscal_year varchar2(4) constraint nn_sal_year not null,
salary number constraint chk_sal_sal check (salary > 0 ),
fullname varchar2(64) constraint unq_sal_fullname unique,
emp_id varchar2(12) constraint fk_sal_emp_id references emp1(eno));
To disable a constraint, use the alter table command. To enable a disabled constraint, again
use the alter table command. The following examples disables and then re-enables the salary
check condition
The following example demonstrates how to drop the constraints using constraint name,
alter table salary_table drop constraint unq_sal_fullname;
alter table salary_table drop constraint chk_sal_sal;
alter table salary_table drop constraint nn_sal_year;
alter table salary_table drop constraint fk_sal_emp_id;
13
To avoid that, we use the COMMIT command to mark the changes as permanent.
Following is commit command's syntax,
COMMIT;
ROLLBACK command
This command restores the database to last commited state. It is also used
with SAVEPOINT command to jump to a savepoint in an ongoing transaction.
If we have used the UPDATE command to make some changes into the database, and realise that
those changes were not required, then we can use the ROLLBACK command to rollback those
changes, if they were not commited using the COMMIT command.
Following is rollback command's syntax,
ROLLBACK TO savepoint_name;
SAVEPOINT command
SAVEPOINT command is used to temporarily save a transaction so that you can rollback to that
point whenever required.
Following is savepoint command's syntax,
SAVEPOINT savepoint_name;
In short, using this command we can name the different states of our data in any table and then
rollback to that state using the ROLLBACK command whenever required.
EXAMPLE :
DELETE COMMAND
SQL> delete from person where lastname='Kumar';
2 rows deleted.
SQL> select * from person;
14
PID LASTNAME FIRSTNAME ADDRESS AGE
------ ---------- ---------- ------------ --------
1 Prettina Anne BAngalore 14
2 Benitto Anish Trichy 24
3 Raj Anita Chennai 27
4 Hinn Benny Britain 55
5 Prakash Bhaskar Assam 40
SQL> rollback;
Rollback complete.
Lab Exercise
15
A) NAME: branch
FIELDS DATATYPE
branch_name varchar2(30)
branch_city varchar2(30)
assets number(8,2)
B) NAME: account
FIELDS DATATYPE
account_no varchar2(11)
branch_name varchar2(30)
balance number(8)
C) NAME: customer
FIELD DATATYPE
customer_id varchar2(11)
customer_name varchar2(20)
customer_street varchar2(15)
customer_city varchar2(15)
D) NAME: depositor
FIELD DATATYPE
customer_id varchar2(11)
account_no varchar2(11)
E) NAME: loan
FIELDS DATATYPE
loan_no varchar2(4)
branch_name varchar2(30)
amount number(8,2)
F) NAME: borrower
FIELDS DATATYPE
customer_id varchar2(11)
loan_no varcahr2(4)
a. Add a new column ‘account opening date’ in the account table, which is of type Date.
b. Increase the width of the column customer_street in table customer to 20.
4. Add primary keys to all the tables for the specified attributes
16
A) NAME: branch
FIELDS DATATYPE
branch_name varchar2(30) primary key
branch_city varchar2(30)
assets number(8,2)
B) NAME: account
FIELDS DATATYPE
account_no varchar2(11) primary key
branch_name varchar2(30)
balance number(8)
C) NAME: customer
FIELD DATATYPE
customer_id varchar2(11) primary key
customer_name varchar2(20)
customer_street varchar2(15)
customer_city varchar2(15)
D) NAME: loan
FIELDS DATATYPE
loan_no varchar2(4) primary key
branch_name varchar2(30)
amount number(8,2)
5. Add foreign keys to the following tables for the specified attributes with mentioned
reference table
B) NAME: account
FIELDS DATATYPE
account_no varchar2(11) primary key
branch_name varchar2(30) references branch(branch_name)
balance number(8)
C) NAME: depositor
FIELD DATATYPE
customer_id varchar2(11)references customer (customer_id)
account_no varchar2(11)references account (account_no)
D) NAME: loan
FIELDS DATATYPE
17
loan_no varchar2(4) primary key
branch_name varchar2(30) references branch(branch_name) (Create constraint
with constraint name)
amount number(8,2)
1. branch :
2. account :
3. loan :
18
1_93 Mianus 500
4. depositor
CUSTOMER_ID ACCOUNT_NO
c_08 182_73_6091
c_03 192_83_7465
c_05 321_12_3123
c_07 336_66_9999
c_08 963_96_3963
c_02 376_66_9999
5. customer
CUSTOMER_ID CUSTOMER_NAME CUSTOMER_STREET CUSTOMER_CITY
c_01 smith north rye
c_02 turner putnam stamford
c_03 johnson alma palo alto
c_04 curry north rye
c_05 jones main harrisdon
c_06 adoms spring pittsfield
c_07 lindsay park pittsfield
c_08 hayes main harrison
c_09 williams nassau Princeton
6. borrower
CUSTOMER_ID LOAN_NO
c_01 1_11
c_01 1_23
c_03 1_93
c_05 1_17
c_03 1_16
c_05 1_14
19
13. Creates a DEFAULT constraint on the "City" column of employee table.
14. Create NOT NULL for dept_id on department table.
15. Create NOT NULL for basic in pay details.
16. Enforce CHECK constraints for (deductions > 780) on pay details.
EX. 2. Database Querying – Simple queries, Nested queries, Sub queries and
Joins
Simple Queries
1. Create Employee table and insert the values like given below
Emplo First_ Last_ Email Phone_Nu Hire_d Salary Comm Man Depar
yee_id Name Name mber ate ission_ ager_ tment
pct id _id
101 selva kumar selva@xyz. 9350454613 05- 20000 .20 104 201
com JAN-
20
1990
102 muthu Kumar muthu@xyz 7250548158 08- 30000 .10 104 201
.com FEB-
1991
103 selva laksh Selva1@xyz 8795458162 40000 104 201
mi .com
104 anu Sree anu@xyz.co 8495188645 22- 60000 .10 104 202
m MAR-
1989
105 bharath Rajan bharathi@x 6548521486 25- 20000 105 202
i yz.com MAR-
1989
106 muthu Selvi 9874525842 26- 80000 .10 105 202
APR-
1994
107 devi Priya devi@xyz.c 8547962140 70000 .20 105 203
om
108 selva Kumar 7589632410 31- 30000 .10 108 203
i SEP-
1990
109 Tamil Arasi tamil@xyz. 8546231189 29- 50000 .50 108 204
com OCT-
1997
110 maha laxmi maha@xyz. 8745962311 70000 .10 108 204
com
2. Create a query to display the last name, hire date, and employee number for each
employee, with employee number appearing first.
SOLUTION:
21
108 Kumari 30-SEP-90
101 Kumar 05-JAN-90
102 Kumar 08-FEB-91
103 lakshmi
106 Selvi 26-APR-94
107 Priya
109 Arasi 29-OCT-97
110 laxmi
10 rows selected.
SOLUTION:
SQL> select * from EMPLOYEES_TABLE where Salary>20000;
EMPLO FIRS LAST EMAI PHONE_ HIR SALA COMMI MAN DEPA
YEE_ID T_NA _NA L NUMBE E_D RY SSION_ AGE RTM
ME ME R ATE PCT R_ID ENT_
ID
---------------------------------------------------------------------------------------------------------------------
---------------------
104 anu Sree anu@ 8495188 22- 60000 .1 104 202
xyz.co 645 MAR
m -89
108 selva Kuma NULL 7589632 30- 30000 .1 108 203
ri 410 SEP-
90
102 muthu Kuma muthu 7250548 08- 30000 .1 104 201
r @xyz. 158 FEB-
com 91
103 selva laksh Selva1 8795458 40000 104 201
mi @xyz. 162
com
106 muthu Selvi NULL 9874525 26- 80000 .1 105 202
842 APR-
94
107 devi Priya devi@ 8547962 70000 .2 105 203
xyz.co 140
m
22
109 Tamil Arasi tamil 85426311 29- 50000 .5 108 204
@xyz. 89 OCT-
com 97
110 maha laxmi maha 8754962 70000 .1 108 204
@xyz. 311
com
8 rows selected.
4. Create a query to display the last name and salary of employees whose salary is not in
the range of 2000 and 80000. (hints: not between )
SOLUTION:
SQL> select Last_Name,Salary from EMPLOYEES_TABLE where Salary not between 20000
and 60000;
LAST_NAME SALARY
------------------------- ----------
Selvi 80000
Priya 70000
laxmi 70000
5. Display the employee last name, job ID, and start date of employees hired between 01-
MAR-1989 and May 1,1995. (hints: between)
SOLUTION:
SQL> select Last_Name,Employee_id,Hire_date from EMPLOYEES_TABLE where Hire_date
between '01-MAR-1989' and '01-MAY-1995';
LAST_NAME EMPLOYEE_ID HIRE_DATE
------------------------- ----------- -----------------
Sree 104 22-MAR-89
Rajan 105 25-MAR-89
Kumari 108 30-SEP-90
Kumar 101 05-JAN-90
Kumar 102 08-FEB-91
Selvi 106 26-APR-94
6 rows selected.
8. Display the last name and salary of all employees who earn between 60000 and 80000
and are in departments 201 and 204 .
SOLUTION:
SQL> select Last_Name,Salary from EMPLOYEES_TABLE where Salary between 60000 and
80000 and Department_id in (201,204);
23
LAST_NAME SALARY
------------------------- ----------
laxmi 70000
9. Display the last name and hire date of every employee who was hired in 1994.
(hints: like)
SOLUTION:
SQL> select Last_Name,Hire_date from EMPLOYEES_TABLE where Hire_date like '%94';
LAST_NAME HIRE_DATE
------------------------- ---------
Selvi 26-APR-94
10. Display employee details who does not have mail-id.
SOLUTION:
SQL> select * from EMPLOYEES_TABLE where email=’NULL’;
No rows selected
SubQueries
A subquery is a SQL query nested inside a larger query.
Syntax :
24
The subquery (inner query) executes once before the main query (outer query) executes.
The main query (outer query) use the subquery result.
student marks
Now we want to write a query to identify all students who get better marks than that of
the student who's StudentID is 'V002', but we do not know the marks of 'V002'.
- To solve the problem, we require two queries. One query returns the marks (stored in
Total_marks field) of 'V002' and a second query identifies the students who get better
marks than the result of the first query.
First query:
SELECT *
FROM `marks`
WHERE studentid = 'V002';
Copy
Query result:
25
The result of the query is 80.
- Using the result of this query, here we have written another query to identify the
students who get better marks than 80. Here is the query :
Second query:
SELECT a.studentid, a.name, b.total_marks
FROM student a, marks b
WHERE a.studentid = b.studentid
AND b.total_marks >80;
Copy
Query result:
Above two queries identified students who get the better number than the student who's
StudentID is 'V002' (Abhay).
You can combine the above two queries by placing one query inside the other. The
subquery (also called the 'inner query') is the query inside the parentheses. See the
following code and query result :
SQL Code:
SELECT a.studentid, a.name, b.total_marks
FROM student a, marks b
WHERE a.studentid = b.studentid AND b.total_marks >
(SELECT total_marks
FROM marks
WHERE studentid = 'V002');
Copy
Query result:
26
Subqueries: General Rules
A subquery SELECT statement is almost similar to the SELECT statement and it is used
to begin a regular or outer query. Here is the syntax of a subquery:
Syntax:
(SELECT [DISTINCT] subquery_select_argument
FROM {table_name | view_name}
{table_name | view_name} ...
[WHERE search_conditions]
[GROUP BY aggregate_expression [, aggregate_expression] ...]
[HAVING search_conditions])
Subqueries: Guidelines
There are some guidelines to consider when using subqueries :
27
Subqueries cannot manipulate their results internally, therefore ORDER BY clause cannot be added
into a subquery. You can use an ORDER BY clause in the main SELECT statement (outer query) which will be
the last clause.
Use single-row operators with single-row subqueries.
If a subquery (inner query) returns a null value to the outer query, the outer query will not return any
rows when using certain comparison operators in a WHERE clause.
Type of Subqueries
In the next session, we have thoroughly discussed the above topics. Apart from the above
type of subqueries, you can use a subquery inside INSERT, UPDATE and DELETE
statement. Here is a brief discussion :
SQL Code:
INSERT INTO neworder
SELECT * FROM orders
WHERE advance_amount in(2000,5000);
Output:
2 rows inserted
28
Subqueries with UPDATE statement
In a UPDATE statement, you can set new column value equal to the result returned by a
single row subquery. Here are the syntax and an example of subqueries using UPDATE
statement.
Syntax:
UPDATE table SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
If we want to update that ord_date in 'neworder' table with '15-JAN-10' which have the
difference of ord_amount and advance_amount is less than the minimum ord_amount of
'orders' table the following SQL can be used:
SQL Code:
UPDATE neworder
SET ord_date='15-JAN-10'
WHERE ord_amount-advance_amount<
(SELECT MIN(ord_amount) FROM orders);
Output:
7 rows updated
SQL Code:
DELETE FROM neworder
WHERE advance_amount<
(SELECT MAX(advance_amount) FROM orders);
Output:
34 rows deleted.
29
Correlated Subqueries
SQL Correlated Subqueries are used to select data from a table referenced in the outer
query. The subquery is known as a correlated because the subquery is related to the outer
query. In this type of queries, a table alias (also called a correlation name) must be used to
specify which table reference is to be used.
The alias is the pet name of a table which is brought about by putting directly after the
table name in the FROM clause. This is suitable when anybody wants to obtain
information from two separate tables.
the agent_code of orders table must be the same agent_code of agents table and
agent_name of agents table must be Alex,the following SQL statement can be used:
SQL Code:
SELECT a.ord_num,a.ord_amount,a.cust_code,a.agent_code
FROM orders a
WHERE a.agent_code=(
SELECT b.agent_code
FROM agents b WHERE b.agent_name='Alex');
Output:
30
Using EXISTS with a Correlated Subquery
We have already used the EXISTS operator to check the existence of a result of a
subquery. EXISTS operator can be used in correlated subqueries also. Using EXISTS the
following query display the employee_id, manager_id, first_name and last_name of those
employees who manage other employees.
31
SQL Code:
SELECT employee_id, manager_id, first_name, last_name
FROM employees a
WHERE EXISTS
(SELECT employee_id
FROM employees b
Output:
32
SQL Code:
SELECT employee_id, manager_id, first_name, last_name
FROM employees a
(SELECT employee_id
FROM employees b
Output:
33
Create a table for the following schema using attributes from EMPLOYEES table
SOLUTION:
SQL> select * from emp_training;
10 rows selected.
2. Copy records from the EMPLOYEES table whose salary is less than 60000 in to
Emp_training2 relation.
SOLUTION:
SQL> create table Emp_training2 as(select Employee_id,First_Name,Email,Phone_Number
from EMPLOYEES_TABLE where salary<60000);
34
Table created.
SQL> select * from emptraning2;
EMPID FNAME EMAILID PHNO
---------- -------------------- ---------------------------------------
105 bharathi bharathi@xyz.com 9442952654
108 selva NULL 9086543489
101 SELVA selva@xyz.com 9346790056
102 muthu muthu@xyz.com 9876545787
109 tamil tamil@xyz.com 9887654456
5 rows selected.
JOIN
SQL joins are used to fetch data from two or more tables, based on conditions between
tables.
There are various type of joins. Like
Equi-Joins
Self-Join
Outer-Join
Cross-Join
Exercise:
1. Fetch records from two tables emp, dept where deptno of employee is equal to dept
no of dept.
35
6. Select an employee's department where they have not been assigned to a
department.
8. Retrieve each employee who is in a department and each department that has an
employee and also each employee who is not part of a department and each department
which doesn't have an employee.
a. Modify the balance attribute alone such that it decreases the amount by 10% for the
account table
b. Delete all the account tuples in the ‘Redwood’ branch.
c. Delete all loans with loan amounts between 15000 to 20000.
d. Find the names of all branches in the loan relation.
e. Display all the Customer names whose come from either pittsfield or stamford.
f. Find all loan numbers for loans made at the ‘Perryridge’ branch with loan amount greater
than 1200.
g. Find loan numbers of those loans with loan amount between 10000 and 20000.
h. Display the customer name in alphabetical order
i. Display all the customer names ordered by customer city
j. Give a count of how many account holds are in each branch.
36
EX. 3. CREATION OF VIEWS, SYNONYMS AND SEQUENCE
Aim : To create views, synonyms, sequence, indexes and save point for the database.
VIEWS
A view is a virtual table. In SQL, a view is a virtual table based on the result-set of an SQL
statement.
A view contains rows and columns, just like a real table. The fields in a view are fields from one
or more real tables in the database.
You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if
the data were coming from one single table.
Syntax:
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
Note: A view always shows up-to-date data! The database engine recreates the data, using the
view's SQL statement, every time a user queries a view.
Examples
If you have the Northwind database you can see that it has several views installed by default.
The view "Current Product List" lists all active products (products that are not discontinued)
from the "Products" table. The view is created with the following SQL:
37
CREATE VIEW [Current Product List] AS
SELECT ProductID,ProductName
FROM Products
WHERE Discontinued=No
Syntax
CREATE OR REPLACE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
Example:
Now we want to add the "Category" column to the "Current Product List" view. We will update
the view with the following SQL:
Samples
1) SYNONYM S
38
ORDER_NO ISBN QUANTITY SHIP_DATE
-------------------- ---------- ---------- ---------
N121 1-101 100 12-MAR-14
N122 2-102 200 11-FEB-12
N123 3-103 200 22-FEB-13
N124 3-103 300 12-JAN-11
SQL>
CREATE SYNONYM ordernew FOR order_list;
Synonym created.
SQL> select * from ordernew;
create a sequence and design the student table with the given attributes.
SQL> create table student(student_id number, name varchar2(10),result varchar2(10));
Table created.
39
SQL> create sequence student_seq start with 100 increment by 1;
Sequence created.
SQL> insert into student values(student_seq.nextval,'Alex','pass'); 1
row created.
SQL> insert into student values(student_seq.nextval,'Joel','pass'); 1
row created.
SQL> select * from student;
INDEXES
To cre ate an inde x on the Last Name column of the student table
Index created.
1. View the customers whose Account Opening date is after 12th Jan 2006.
40
2. View the employee names whose salary is greater than 10000.
3. View for loans made at the ‘Perryridge’ branch with loan amount greater than 1200.
4. Create a view of customer table that prevents modification of the views.
41
EX. 4 DATABASE PROGRAMMING: IMPLICIT AND EXPLICIT CURSORS
Aim : To create cursor for fetching records from the given table based on the requirement
A database cursor can be thought of as a pointer to a specific row within a query result. The
pointer can be moved from one row to the next. Depending on the type of cursor, you may be
even able to move it to the previous row.
1. Implicit Cursor
Implicit cursors are automatically generated by the Oracle engine. If the Oracle Engine
opens a cursor for its internal processing, it is known as Implicit cursor.
Implicit cursors are created by default to process the statements when DML
statements(INSERT, UPDATE, DELETE) are executed.
2. Explicit Cursor
If a cursor is opened for processing data through a PL/SQL block as per requirement like
user defined cursor, is known as an Explicit cursor.
Explicit cursor is created while executing a SELECT statement that returns more than
one row.
These cursor should be defined in the declaration section of the PL/SQL block and
created on a SELECT statement which returns more than one row.
Attribute Name Description
%ISOPEN It is true if cursor is open and FALSE if cursor is not open or cursor is
closed.
It is used only with Explicit Cursors.
%FOUND TRUE if at least one row was processed or a record was fetched
successfully from the opened cursor and FALSE otherwise.
%NOTFOUND TRUE if no row were processed or if record was not fetched successfully
and FALSE otherwise.
%ROWCOUNT It returns the number of rows/records processed by a cursor Consider the
following tables to complete the following assignment.
The most commonly used loop with in a PL/SQL block is the FOR variable IN value construct.
This is an example of machine defined loop exit i.e. when all the values in FOR construct are
exhausted looping stops. Syntax: FOR variable IN cursorname Here, the verb FOR automatically
creates the variable of type %rowtype. Each record in the opened cursor becomes a value for the
memory variable of %rowtype. The FOR verb ensures that a row from the cursor is loaded in
declared variable and loop executes once. This goes until all the rows of the cursor have been
loaded into the variable. After this loop stops.
A CURSOR FOR LOOP automatically does the following:
• Implicitly declares its loop index as a %rowtype record.
• Open a cursor.
• Fetches a row from the active set for each loop iteration.
42
• Closes the cursor when all rows have been processed.
Example 1:
Cursor can be closed even when an exit or goto statement is used to leave the loop prematurely,
or an exception is raised inside the loop. Example The HRD manager has decided to raise the
salary for all employees in department number 30 by 0.05.
Emp(empno, deptno,sal)
DECLARE
CURSOR c_emp IS
SELECT empno,sal
FROM emp
WHERE deptno=30;
BEGIN
FOR rec IN c_emp
LOOP
UPDATE emp
SET sal=rec.sal+(rec.sal * .05)
WHERE empno=rec.empno;
END LOOP;
COMMIT;
END;
Example 2
Table 1: 'Emp_Detail'
Table2: 'Department'
43
Q. Write a PL/SQL block to Create a table based record.
Answer:
Note: To create a table based record/ cursor based record always preferred %ROWTYPE.
DECLARE
vr_emp emp_detail %ROWTYPE;
BEGIN
SELECT *
INTO vr_emp
FROM emp_detail
WHERE employee_id = 1;
DBMS_OUTPUT.PUT_LINE('Employee Details : '||vr_emp.employee_id ||' '||
vr_emp.first_name||' '||vr_emp.last_name||' '||vr_emp.salary);
END;
Output:
Lab Exercise:
1.Write a PL/SQL code to display the Empno, Ename and Job of employees of DeptNo 10 with
CURSOR FOR LOOP Statement.
Employee table schema (Empno, Ename, Job, Sal, DeptNo, Commission)
44
Ex. 5. PROCEDURES AND FUNCTIONS
PL/SQL PROGRAMMING
45
Decision making with IF statement :- The general syntax for the using IF-ELSE statement
is IF(TEST_CONDITION) THEN
SET OF STATEMENTS
ELSE
SET OF STATEMENTS
END IF;
For Nested IF—ELSE Statement we can use IF--ELSIF—ELSE as follows
IF(TEST_CONDITION) THEN
SET OF STATEMENTS
ELSIF (CONDITION)
SET OF STATEMENTS
END IF;
46
END LOOP;
LOOP STATEMENT
LOOP
SET OF STATEMENTS
IF (CONDITION) THEN
EXIT
SET OF STATEMENTS
END LOOP;
While using LOOP statement, we have take care of EXIT condition, otherwise it may go into
infinite loop.
Example :- Here are the example for all these types of looping statement where each program
prints numbers 1 to 10.
GOTO EXAMPLE
DECLARE
I INTEGER := 1;
BEGIN
<<OUTPUT>>
DBMS_OUTPUT.PUT_LINE(I);
I := I + 1;
IF I<=10 THEN
GOTO OUTPUT;
END IF;
END;
/
FOR LOOP EXAMPLE
BEGIN
FOR I IN 1..10 LOOP
DBMS_OUTPUT.PUT_LINE(I);
END LOOP;
END;
/
WHILE EXAMPLE
DECLARE
I INTEGER := 1;
BEGIN
WHILE(I<=10) LOOP
DBMS_OUTPUT.PUT_LINE(I);
I := I + 1;
END LOOP;
END;
/
LOOP EXAMPLE
DECLARE
47
I INTEGER := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE(I);
I := I + 1;
EXIT WHEN I=11;
END LOOP;
END;
/
DATA TYPES
Already we know following data types. NUMBER, INTEGER, VARCHAR2, DATE,
BOOLEAN, etc. Now let’s see few more data types that are useful for writing PL/SQL programs
in Oracle.
%TYPE :- %TYPE is used to give data type of predefined variable or database column.
Eg:-
itemcode Number(10);
icode itemcode%Type;
The database column can be used as
id customer.cid%type
%ROWTYPE :- %rowtype is used to provide record data type to a variable. The variable can
store row of the table or row fetched from the cursor.
Eg:-
If we want to store a row of table Sailors then we can declare variable as customer %Rowtype
Inserting values to table :- Here is the example for inserting the values into a database through
PL/SQL Program. Remember that we have to follow all the rules of SQL like Primary Key
Constraints, Foreign Key Constraints, Check Constraints, etc.
Ex:- Insert the record into Accounts table by reading the values from the Keyboard.
DECLARE
ACCNO NUMBER (5):=& ACCNO;
BRANCH_NAME VARCHAR2(30):='& BRANCH_NAME ';
BALACE NUMBER(5):=& BALACE;
BEGIN
INSERT INTO ACCOUNS VALUES(ACCNO, BRANCH_NAME,BALANCE);
END;
/
Reading from table
DECLARE
SID VARCHAR2(10); -- or can be defined SID Sailors.SID%Type
SNAME VARCHAR2(30);
RATING NUMBER(5);
48
AGE NUMBER(4,2);
BEGIN
SELECT SID, SNAME, RATING, AGE INTO SID, SNAME, RATING, AGE FROM
SAILORS WHERE SID='&SID';
DBMS_OUTPUT.PUT_LINE(SID || ' '|| SNAME || ' '|| RATING ||' '|| AGE );
END;
/
FUNCTIONS
SYNTAX
Create [or replace] function function name[(argument1,argument2,....., argument
n)]
Return function- datatype is
[local- variable-declarations]
Begin
Executable-section [exception-section]
Return-function value
End[function-name];
Exercise
Create a function for withdrawing money from an account in a bank management
system which uses bank table
49
SQL> select * from bank
ACC-NO B_NAME BALANCE
101 SBI 25000
102 SBT 5000
103 FEDERAL 10000
104 AXIS 15000
105 CANARA 50000
Calling function from a PL\SQL block:
SQL> declare
2 n number
3 begin
4 n:=withdraw(101,20000);
5 end
6/
PL/SQL procedure successfully completed.
50
Function created Calling function from a PL/SQL block
SQL> declare
2 n number
3 begin
4 n:=deposit(104,5000);
5 end
6 / PL/SQL procedure successfully completed.
Create a function for calculating the total marks and percentage of the student in a
student management system which uses a student table:
51
16 /
Function created
SQL> declare
2 n number
3 begin
4 n:=stud_update;
5 end;
6/
PL/sql Procedure successfully completed
10 Gouri a it 89 56 74 219 73
11 Akashaj s it 95 91 93 279 93
23 Lithik b bt 78 67 71 216 72
52
27 Pallavi s bt 90 98 96 284 94.6667
30 Navaj a ph 88 81 89 258 86
Creating a function for calculating net salary for all employees in an organization
using an employee table
53
E_NO E_NAME HRA DA PF BASIC NETSAL
SQL> declare
2 n number
3 begin
4 n:=salary;
5 end
6/
PROCEDURES
SYNTAX
SQL> create[or replace] procedure procedure_name [(argument1, argument2,…( argument n)]
is
[local –variable - declarations]
begin
executable-section
[exception- section]
End[procedure-name];
54
1. Create a procedure for deposit and withdrawal of money in an account in a Bank
Management System which uses bank table.
55
SQL> select * from bank;
ACC_NO NAME BAL
100 Anil 90000
101 Abi 10000
102 Bavi 2500
103 Chandru 1000
104 Divakar 20000
Example2:
The subsequent procedure is used to increase the salary of all employees who work in the
department given by the procedure's parameter. The percentage of the salary increase is given by
a parameter, too.
56
close emp cur;
commit;
end raise salary;
Table created.
SQL> select * from emp1;
EMPNO EMPNAME DEPTNO SAL EXP
1000 Akshay 250 22000 3
1010 Akshay 230 18000 2
1012 Abhirami 250 20000 2
1015 Bavi 240 34000 6
1200 Akshay 250 32000 4
1017 Lakshmi 200 28000 3
1019 Sundar 200 30000 3
1045 Sreeram 260 42000 4
7 rows selected.
2. Create a procedure for incrementing rupees 1500 for those with experience less
than 4 years and 4000 for rest of all employees in an organization which uses
employee table.
57
15 end loop;
16 end;
17 /
Procedure created.
PL/ SQL procedure successfully completed.
SQL> select * from emp1;
3. Create a procedure for checking the stock of an agency to order items which
uses inventory and orderit tables.
58
SQL > create or replace procedure invent_check
2 is
3 cursor c select * from invent1;
4 j invent% rowtype;
5 che number;
6 begin
7 open c
8 loop
9 fetch c into j;
10 if c%notfoun then exit;
11 end if;
12 che:= j.no_of_indiv;
13 if che<=5 then
14insert into orderit values(j.itname, j.no_of_indiv);
15 end if;
16 end loop;
17 close c;
18 end;
/
Procedure created.
Lab Exercise:
59
EX. 6. TRIGGERS
Aim :
To implement and execute trigger in Oracle database using Procedural Language concepts.
Triggers are stored programs, which are automatically executed or fired when some events
occur. Triggers are, in fact, written to be executed in response to any of the following events −
A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
A database definition (DDL) statement (CREATE, ALTER, or DROP).
A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the event is
associated.
-It is a stored sub program associated with a table
-It is used to keep an audit trial of a table, to prevent invalid transaction, enforce complex
security authorization, to generate data automatically
60
-ie.)A trigger is a statement that the system executes automatically as a side effect of a
modification to the database. Eg., Instead of allowing negative account balances, the bank deals
with overdrafts by setting the account balance to zero, and creating a loan in the amount of the
overdraft.
Benefits of Triggers
Triggers can be written for the following purposes −
Syntax:
EXAMPLE
61
1. Create a trigger for invent table which triggers while updating operations are performed on the
invent table
SQL> create or replace triggers inve before update on invent
2 for each row
3 declare
4 begin
5 if: new.no_of_indiv<=10 then
6 Insert into orderit values(:new.itname,:new.no_of_indiv);
7 else
8 delete from orderit where itname=:new.itname;
9 end if;
10 end;
11 / Trigger created
ITNAME NO_OF_INDIV
hard disk 3
cd rom 5
ipod 2
2. Create a trigger while insert or update or delete operations are performed on the table employ.
62
Trigger created
Lab Exercise:
63
Ex. 7. EXCEPTION HANDLING
Aim : To write a PL/SQL programs to handle pre defined and user defined exceptions in the
PLSQL block.
We have to ensure that the SELECT….INTO statement should return one & only one row. If no
row is selected then exception NO_DATA_FOUND is raised. If more than one row is selected
then exception TOO_MANY_ROWS is raised.
To handle the situation where no rows selected or so many rows selected we can use Exceptions.
We have two types of exception, User-Defined and Pre-Defined Exceptions.
User-Defined Exception
64
DECLARE
N INTEGER:=&N;
A EXCEPTION;
B EXCEPTION;
BEGIN
IF MOD(N,2)=0 THEN
RAISE A;
ELSE
RAISE B;
END IF;
EXCEPTION
WHEN A THEN
DBMS_OUTPUT.PUT_LINE('THE INPUT IS EVEN.....');
WHEN B THEN
DBMS_OUTPUT.PUT_LINE('THE INPUT IS ODD.....');
END;
/
Pre-Defined Exception
DECLARE
ACC_NO VARCHAR2(10);
BEGIN
SELECT ACCOUNT_NO INTO ACC_NO FROM ACCONTS WHERE BRANCH_NAME
='&BRANCH_NAME’;
DBMS_OUTPUT.PUT_LINE(ACC_NO);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE(‘No Account with given ACCOUNT NO found’);
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE(‘More than one ACCOUNTS with same BRANCH NAME
found’);
END;/
SQL> create or replace function stud_update
2 return number is
3 cursor c is select * from student;
4 ctot number
5 cper number
6 begin
7 for i in c
8 loop
9 ctot:=i.m1+i.m2+i.m3;
10 cper:=ctot/3;
17 update student set total=ctot where id_no=i.id_no;
18 update student set per=cper where id_no=id_no;
19 end loop;
20 Return 1;
65
21 End;
22 /
Function created
SQL> declare
2 n number
3 begin
4 n:=stud_update;
5 end;
6/
Creating a function for calculating net salary for all employees in an organization using an
employee table
SQL> create or replace function salary
2 return number is
3 cursor c is select * from employee;
4 i employee%rowtype;
5 netsalary number;
6 begin
7 open c;
8 loop
66
9 fetch c into i;
10 If c%notfound then exit
11 end if
12 netsalary=i.basic+i.hra+i.da-i.pf;
13 update employee set netsal=netsalary where e_no=i.e_no;
14 end loop;
15 return netsalary;
19 close c;
20 end
21 /
SQL> select * from employee
Roadway Travels:
67
Roadway travels is in business since 1997 with several buses connecting different places in india.
Its main office is located in Hyderabad. The company wants to computerize its operations in the
following areas.
1. E-R Model:
Analyze the problem carefully and come up with the entities in it. Identify what data
has to be persisted in the database. This contains the entities, attributes etc. In this
we wqill analyze different types of entities with attributes of “Roadways Travels”.
Entity: An Entity is an object or concept about which you want to
store information Relationship: A relationship is an association
between several entities.
Attributes: An object is characterized by its properties or attributes. In relational
database systems attributes correspond to fields.
68
Passenger
Reservation
Cancellation/modification
These Entities have following
attributes
Bus:
Bus_id
Bus_name
Bus_type
Bus_totalseats
Ticket:
Ticket_booking
Ticket_datejourney
Ticket_to
Ticket_from
Ticket_id
Ticket_no of tickets
Passenger:
Pid
Pname
Pgender
Page
precancel
Bus
Sourc
No
Bus e
2. Concept design with E-R Model and apply cardinalities for each
Destinatio
relationship. Identify strong entities and weak entities for
Departure Time n specialization.
relationships like generalization, aggregation,
Sex
Ticket No Reservation
Ticket Source
Departure
Time Age
69
Arrival Time
3. Relation Model represents attributes as columns in tables and
different types of attributes like composite, Multi-valued and
Derived.
Example: The passenger tables look as below. This is an example. You can add more
attributes based on your E-R model. This is not a normalized table. Passenger
70
Tickets
#tickets_no
no of tkts
From_place
To_place
#Bus_no
#jrny_date
71
EX 9. DATABASE CONNECTIVITY WITH FRONT END TOOLS
On the other hand, because users may click on a certain object randomly, so
each object has to be programmed independently to be able to response to
those actions (events). Therefore, a VB Program is made up of many
subprograms, each has its own program codes, and each can be executed
independently and at the same time each can be linked together in one way
or another.
1.1 FORMS
Step 1 Open Microsoft Visual Basic environment and select "New Form."
Step 2 Make the form the size that you want by clicking on the corner and
dragging. Then add any form properties that you will need (like a name: Ex:
frmOpener).
Step 3 Add all of the elements, such as control buttons and text boxes, that
you will need on the form for the user. Arrange them exactly the way you
want them to appear for the user.
Step 4 Double-click on the form to enter the code section. A coding window
will open up where the Form Load command represents the point where the
software will open and begin working.
Step 5 Within the code window, add functions for anything that you want to
happen when the form loads, before the user does anything.
72
Step 6 Add variables. The Form Load section of your code is a great place to
dimension variables, known as "global" variables, that you will use
throughout the program. Add variables by name and specify type: Ex. for an
integer to count clicks, use the command: dim click as integer
Step 7 You're not done yet. Most of the function code should be within user-
generated events. Don't try to program the whole thing within the form code
module. The application will do most of its work through functions that are
called between different objects (command buttons) and the form itself. A
programmer has to know how to "pass" variables. When you do dimension
variables in the form load, think about how they will be passed to various
functions.
First of all, you have to launch Microsoft Visual Basic 6. Normally, a default
form with the name Form1 will be available for you to start your new
project. Now, double click on Form1, the source code window for Form1 as
shown in figure 1 will appear. The top of the source code window consists
of a list of objects and their associated events or procedures. In following
figure1, the object displayed is Form and the associated procedure is Load.
When you click on the object box, the drop-down list will display a list of
objects you have inserted into your form as shown in figure 2
Here, you can see a form with the name Form1, a command button with the
name Command1, a Label with the name Label1 and a Picture Box with the
73
name Picture1. Similarly, when you click on the procedure box, a list of
procedures associated with the object will be displayed as shown in figure 3.
Some of the procedures associated with the object Form1 are Activate,
Click, DblClick (which means Double-Click) , DragDrop, keyPress and
more. Each object has its own set of procedures. You can always select an
object and write codes for any of its procedure in order to perform certain
tasks.
Example 1
Private Sub Form_Load ( )
Form1.show
Print “Welcome to Visual Basic tutorial”
End Sub
When you press F5 to run the program, the output screen will appear as shown below in
figure 4
Example 2
74
Print 20 + 10
Print 20 - 10
Print 20 * 10
Print 20 / 10
End Sub
75
For example, in order to change the caption, just highlight Form1 under the
name Caption and change it to other names. You may also try to alter the
appearance of the form by setting it to 3D or flat. Other things you can do
are to change its foreground and background color, change the font type and
font size, enable or disable minimize and maximize buttons and etc.
You can also change the properties at runtime to give special effects such
as change of color, shape, animation effect and so on. For example the
following code will change the form color to red every time the form is
loaded.
76
Finally, you must also considering making the control visible or invisible at
runtime, or when should it become visible or invisible.
77
The command button is one of the most important controls as it is used to
execute commands. It displays an illusion that the button is pressed when
the user click on it. The most common event associated with the command
button is the Click event, and the syntax for the procedure is
Private Sub Command1_Click ()
Statements
End Sub
You will learn more about the picture box in future lessons. The image in the
picture box is not resizable.
2.5 The Image Box
The Image Box is another control that handles images and pictures. It
functions almost identically to the picture box. However, there is one major
difference, the image in an Image Box is stretchable, which means it can be
resized. This feature is not available in the Picture Box. Similar to the
Picture Box, it can also use the LoadPicture method to load the picture. For
example, the statement loads the picture grape.gif into the image box.
Image1.Picture=LoadPicture ("C:\VB program\Images\grape.gif")
The function of the List Box is to present a list of items where the user can
click and select the items from the list. In order to add items to the list, we
can use the AddItem method. For example, if you wish to add a number of
items to list box 1, you can key in the following statements
Example 2.2
Private Sub Form_Load ( )
List1.AddItem “Lesson1”
List1.AddItem “Lesson2”
List1.AddItem “Lesson3”
List1.AddItem “Lesson4”
End Sub
78
The items in the list box can be identified by the ListIndex property, the
value of the ListIndex for the first item is 0, the second item has a ListIndex
1, and the second item has a ListIndex 2 and so on
Example 2.3
The Check Box control lets the user selects or unselects an option. When
the Check Box is checked, its value is set to 1 and when it is unchecked, the
value is set to 0. You can include the statements Check1.Value=1 to mark
the Check Box and Check1.Value=0 to unmark the Check Box, as well as
use them to initiate certain actions. For example, the program will change
the background color of the form to red when the check box is unchecked
and it will change to blue when the check box is checked. You will learn
about the conditional statement If….Then….Elesif in later lesson. VbRed
and vbBlue are color constants and BackColor is the background color
property of the form.
Example 2.4
79
2.9 The Option Box
The Option Box control also lets the user selects one of the choices.
However, two or more Option Boxes must work together because as one of
the Option Boxes is selected, the other Option Boxes will be unselected. In
fact, only one Option Box can be selected at one time. When an option box
is selected, its value is set to “True” and when it is unselected; its value is
set to “False”. In the following example, the shape control is placed in the
form together with six Option Boxes. When the user clicks on different
option boxes, different shapes will appear. The values of the shape control
are 0, 1, and 2,3,4,5 which will make it appear as a rectangle, a square, an
oval shape, a rounded rectangle and a rounded square respectively.
Example 2.5
Private Sub Option1_Click ( )
Shape1.Shape = 0
End Sub
Private Sub Option2_Click()
Shape1.Shape = 1
End Sub
Private Sub Option3_Click()
Shape1.Shape = 2
End Sub
Private Sub Option4_Click()
Shape1.Shape = 3
End Sub
Private Sub Option5_Click()
Shape1.Shape = 4
End Sub
Private Sub Option6_Click()
Shape1.Shape = 5
End Sub
2.10 The Drive List Box
The Drive ListBox is for displaying a list of drives available in your
computer. When you place this control into the form and run the program,
you will be able to select different drives from your computer as shown in
Figure 2.2
Figure 2.2 The Drive List Box
80
2.11 The Directory List Box
The Directory List Box is for displaying the list of directories or folders in a
selected drive. When you place this control into the form and run the
program, you will be able to select different directories from a selected drive
in your computer as shown in Figure 2.3
81
-3.402823E+38 to -1.401298E-45 for negative values
Single 4 bytes
1.401298E-45 to 3.402823E+38 for positive values.
-1.79769313486232e+308 to -4.94065645841247E-324 for negative values
Double 8 bytes
4.94065645841247E-324 to 1.79769313486232e+308 for positive values.
Currency 8 bytes -922,337,203,685,477.5808 to 922,337,203,685,477.5807
+/- 79,228,162,514,264,337,593,543,950,335 if no decimal is use
Decimal 12 bytes
+/- 7.9228162514264337593543950335 (28 decimal places).
3.2 Non-numeric Data Types
Nonnumeric data types are data that cannot be manipulated mathematically
using standard arithmetic operators. The non-numeric data comprises text
or string data types, the Date data types, the Boolean data types that store
only two values (true or false), Object data type and Variant data type .They
are summarized in Table
& Long
! Single
# Double
@ Currency
82
In addition, we need to enclose string literals within two quotations and date
and time literals within two # sign. Strings can contain any characters,
including numbers. The following are few examples:
memberName="Turban, John."
TelNumber="1800-900-888-777"
LastDay=#31-Dec-00#
ExpTime=#12:00 am#
Variables are like mail boxes in the post office. The contents of the variables
changes every now and then, just like the mail boxes. In term of VB,
variables are areas allocated by the computer memory to hold data. Like the
mail boxes, each variable must be given a name. To name a variable in
Visual Basic, you have to follow a set of rules.
The following are the rules when naming the variables in Visual Basic
It must be less than 255 characters
No spacing is allowed
It must not begin with a number
Period is not permitted
Examples of valid and invalid variable names are displayed in Table 3.4
Table 3.4
In Visual Basic, one needs to declare the variables before using them by
assigning names and data types. They are normally declared in the general
section of the codes' windows using the Dim statement.
The format is as follows:
Dim Variable Name As Data Type
83
Example 3.1
You may also combine them in one line , separating each variable with a
comma, as follows:
Example 3.2:
84
ThirdNumber = Val(usernum1.Text)
total = firstNumber + secondNumber+ThirdNumber
3.2.4 Constants
Constants are different from variables in the sense that their values do not
change during the running of the program.
Declaring a Constant
Example 5.3
Const Pi As Single=3.142
Const Temp As Single=37
Const Score As Single=100
Example 4.1
85
Dim firstName As String
Dim secondName As String
Dim yourName As String
Private Sub Command1_Click()
firstName = Text1.Text
secondName = Text2.Text
yourName = secondName + " " + firstName
Label1.Caption = yourName
End Sub
Example 4.2
In the example above, three variables are declared as integer and two
variables are declared as variant. Variant means the variable can hold any
data type. The program computes the total and average of the three numbers
that are entered into three text boxes.
5. Conditional Operators
86
Logical Operators
Operator
Meaning Operator Meaning
=
Equal to And Both sides must be true
>
More than One side or other must be
or
true
<
Less Than
One side or other must be
>= Xor
More than and equal true but not both
<= Not Negates truth
Less than and equal
<>
Not Equal to
* You can also compare strings with the above operators. However, there are
certain rules to follows: Upper case letters are less than lowercase letters,
"A"<"B"<"C"<"D".......<"Z" and number are less than letters.
5.2 Using If.....Then.....Else Statements with Operators
If conditions Then
VB expressions
Else
VB expressions
End If
* any If..Then..Else statement must end with End If. Sometime it is not
necessary to use Else.
87
Example:
88
Private Sub Compute_Click()
'Examination Marks
mark = mrk.Text
Select Case mark
Case Is >= 85
comment.Caption = "Excellence"
Case Is >= 70
comment.Caption = "Good"
Case Is >= 60
comment.Caption = "Above Average"
Case Is >= 50
comment.Caption = "Average"
Case Else
comment.Caption = "Need to work harder"
End Select
End Sub
Example 5.3
89
a) Do While condition
Block of one or more VB statements
Loop
b) Do
Block of one or more VB statements
Loop While condition
c) Do Until condition
Block of one or more VB statements
Loop
d) Do
Block of one or more VB statements
Loop Until condition
6.2 Exiting the Loop
Sometime we need exit to exit a loop prematurely because of a certain
condition is fulfilled. The syntax to use is known as Exit Do. You can
examine Example 6.1 & 6.2 for its usage.
Example 6.1
Do while counter <=1000
num.Text=counter
counter =counter+1
Loop
* The above example will keep on adding until counter >1000.
The above example can be rewritten as
Do
num.Text=counter
counter=counter+1
Loop until counter>1000
Example 6.2
Dim sum, n As Integer
Private Sub Form_Activate()
List1.AddItem "n" & vbTab & "sum"
Do
n=n+1
Sum = Sum + n
List1.AddItem n & vbTab & Sum
If n = 100 Then
Exit Do
End If
Loop
End Sub
Explanation
90
In the above example, we compute the summation of 1+2+3+4+……+100.
In the design stage, you need to insert a ListBox into the form for displaying
the output, named List1. The program uses the AddItem method to populate
the ListBox. The statement List1.AddItem "n" & vbTab & "sum" will
display the headings in the ListBox, where it uses the vbTab function to
create a space between the headings n and sum.
91
7. VB Built-in Functions
A function is similar to a normal procedure but the main purpose of the
function is to accept a certain input from the user and return a value
which is passed on to the main program to finish the execution. There
are two types of functions, the built-in functions (or internal functions)
and the functions created by the programmers.
The arguments are values that are passed on to the function. We will learn
two very basic but useful internal functions of Visual basic , i.e. the
MsgBox( ) and InputBox ( ) functions. MsgBox ( ) Function
We can use named constant in place of integers for the second argument to
make the programs more readable. In fact, VB6 will automatically shows up
a list of names constant where you can select one of them.
92
are the same. yourMsg is a variable that holds values that are returned by
the MsgBox ( ) function. The values are determined by the type of buttons
being clicked by the users. It has to be declared as Integer data type in the
procedure or in the general declaration section. Table 7.2 shows the values,
the corresponding named constant and buttons
To make the message box looks more sophisticated, you can add an icon
besides the message. There are four types of icons available in VB as shown
in table 7.3
Table 10.3
Value Named Constant
Icon
16 vbCritical
32 vbQuestion
48 vbExclamation
64 vbInformation
Example 7.1
Private Sub test2_Click()
Dim testMsg2 As Integer
testMsg2 = MsgBox("Click to Test", vbYesNoCancel + vbExclamation,
"Test Message")
If testMsg2 = 6 Then
display2.Caption = "Testing successful"
ElseIf testMsg2 = 7 Then
display2.Caption = "Are you sure?"
Else
display2.Caption = "Testing fail"
End If
93
End Sub ;
Figure 7.1
Example 7.2
Create the following Interface
Figure 7.2
94
If userMsg <> "" Then
message.Caption = userMsg
Else
message.Caption = "No Message"
End If
End Sub
When a user click the OK button, the input box as shown in Figure 10.5 will
appear. After user entering the message and click OK, the message will be
displayed on the caption, if he click Cancel, "No message" will be
displayed.
8. Mathematical Functions
The mathematical functions are very useful and important in programming
because very often we need to deal with mathematical concepts in
programming such as chance and probability, variables, mathematical
logics, calculations, coordinates, time intervals and etc. The common
mathematical functions in Visual Basic are Rnd, Sqr, Int, Abs, Exp,
Log, Sin, Cos, Tan , Atn, Fix and Round.
Rnd is very useful when we deal with the concept of chance and
probability. The Rnd function returns a random value between 0 and 1. In
Example 1. When you run the program, you will get an output of 10
random numbers between 0 and 1. Randomize Timer is a vital statement
here as it will randomize the process.
a) Int is the function that converts a number into an integer by truncating its
decimal part and the resulting integer is the largest integer that is smaller
than the number. For example, Int(2.4)=2, Int(4.8)=4, Int(-4.6)= -5,
Int(0.032)=0 and so on.
b) Sqr is the function that computes the square root of a number. For
example, Sqr(4)=2, Sqr(9)=2 and etc.
95
c) Abs is the function that returns the absolute value of a number. So Abs(-
8) = 8 and Abs(8)= 8.
d) Exp of a number x is the value of ex. For example, Exp(1)=e1 =
2.7182818284590
e) Fix and Int are the same if the number is a positive number as both
truncate the decimal part of the number and return an integer. However,
when the number is negative, it will return the smallest integer that is larger
than the number. For example, Fix(-6.34)= -6 while Int(-6.34)=-7.
f) Round is the function that rounds up a number to a certain number of
decimal places. The Format is Round (n, m) which means to round a number
n to m decimal places. For example, Round (7.2567, 2) =7.26
g) Log is the function that returns the natural Logarithm of a number. For
example,
Log 10= 2.302585
9.
String Manipulation Functions
In this lesson, we will learn how to use some of the string manipulation
function such as Len, Right, Left, Mid, Trim, Ltrim, Rtrim, Ucase, Lcase,
Instr, Val, Str ,Chr and Asc.
(i)The Len Function
The length function returns an integer value which is the length of a phrase
or a sentence, including the empty spaces. The format is
Len (“Phrase”)
For example,
Len (VisualBasic) = 11 and Len (welcome to VB tutorial) = 22
The Len function can also return the number of digits or memory locations
of a number that is stored in the computer. For example,
Private sub Form_Activate ( )
X=sqr (16)
Y=1234
Z#=10#
Print Len(x), Len(y), and Len (z)
End Sub
will produce the output 1, 4 , 8. The reason why the last value is 8 is
because z# is a double precision number and so it is allocated more memory
spaces.
96
(ii) The Right Function :The Right function extracts the right portion of a
phrase. The format is
Right (“Phrase”, n)
Where n is the starting position from the right of the phase where the portion
of the phrase is going to be extracted. For example,
Right(“Visual Basic”, 4) = asic
(iii)The Left Function
The Left$ function extract the left portion of a phrase. The format is
Left(“Phrase”, n)
Where n is the starting position from the left of the phase where the portion
of the phrase is going to be extracted. For example,
Left (“Visual Basic”, 4) = Visu
(iv) The Ltrim Function
The Ltrim function trims the empty spaces of the left portion of the phrase.
The format is
Ltrim(“Phrase”)
.For example,
Ltrim (“ Visual Basic”, 4)= Visual basic
(v) The Rtrim Function
The Rtrim function trims the empty spaces of the right portion of the phrase.
The format is
Rtrim(“Phrase”)
.For example,
Rtrim (“Visual Basic ”, 4) = Visual basic
(vi) The Trim function
The Ttrim function trims the empty spaces on both side of the phrase. The
format is
Trim(“Phrase”)
.For example,
Trim (“ Visual Basic ”) = Visual basic
(viii) The Mid Function
The Mid function extracts a substring from the original phrase or string. It
takes the following format:
Mid(phrase, position, n)
97
Where position is the starting position of the phrase from which the
extraction process will start and n is the number of characters to be
extracted. For example,
Mid(“Visual Basic”, 3, 6) = ual Bas
(ix) The InStr function
The InStr function looks for a phrase that is embedded within the original
phrase and returns the starting position of the embedded phrase. The format
is
Instr (n, original phase, embedded phrase)
Where n is the position where the Instr function will begin to look for the
embedded phrase. For example
Instr(1, “Visual Basic”,” Basic”)=8
(x) The Ucase and the Lcase functions
The Ucase function converts all the characters of a string to capital letters.
On the other hand, the Lcase function converts all the characters of a string
to small letters. For example,
Ucase(“Visual Basic”) =VISUAL BASiC
Lcase(“Visual Basic”) =visual basic
(xi) The Str and Val functions
The Str is the function that converts a number to a string while the Val
function converts a string to a number. The two functions are important
when we need to perform mathematical operations.
(xii) The Chr and the Asc functions
The Chr function returns the string that corresponds to an ASCII code
while the Asc function converts an ASCII character or symbol to the
corresponding ASCII code. ASCII stands for “American Standard Code for
Information Interchange”. Altogether there are 255 ASCII codes and as
many ASCII characters. Some of the characters may not be displayed as
they may represent some actions such as the pressing of a key or produce a
beep sound. The format of the Chr function is
Chr(charcode)
and the format of the Asc function is
Asc(Character)
The following are some examples:
Chr(65)=A, Chr(122)=z, Chr(37)=% , Asc(“B”)=66, Asc(“&”)=38
10. Creating User-Defined Functions
Creating Your Own Function
The general format of a function is as follows:
Public Function functionName (Arg As dataType,..........) As dataType
98
or
Private Function functionName (Arg As dataType,..........) As dataType
* Public indicates that the function is applicable to the whole project and
Private indicates that the function is only applicable to a certain module or
procedure.
99
CS8481 DATABASE MANAGEMENT SYSTEMS LAB
Aim : Develop the following applications using Oracle as a back end and
Visual Basic as front end Tool.
Example :-
TABLE DESIGN:
Table Name: Time table
Name Type
----------------------------------- ---------------------------
SNO NUMBER(4)
DAY VARCHAR2(15)
PERIOD 1 VARCHAR2(25)
CS8481 DATABASE MANAGEMENT SYSTEMS LAB
PERIOD 2 VARCHAR2(25)
PERIOD 3 VARCHAR2(25)
PERIOD 4 VARCHAR2(25)
PERIOD 5 VARCHAR2(25)
FORM 1:
Dim DB As Database
Dim RS AsRecordset
rs.update
MsgBox "the record is updated"
End Sub
Text4.Text = rs(3)
Text5.Text = rs(4)
Text6.Text = rs(5)
Text7.Text = rs(6)
End Sub
Text7.Text = rs(6)
End Sub
OUTPUT:
CS8481 DATABASE MANAGEMENT SYSTEMS LAB
RESULT:
Thus, the application of time table management system has been
designed and implemented in visual basic 6.0.