Upload
bharathwaj-sk
View
216
Download
0
Embed Size (px)
Citation preview
8/3/2019 CS2258-CSE-DBMSRECORD
1/135
8/3/2019 CS2258-CSE-DBMSRECORD
2/135
Sl. No. Date TitlePage
No.Signature
1 07-12-09 Introduction to Oracle-RDBMS
2 07-12-09 Introduction to SQL
3 14-12-09Data Definition Language
Commands
4 14-12-09Data Manipulation Language
commands
5 19-12-09 Constraints
6 19-12-09 Transaction Control LanguageCommands
7 28-12-09 Nested Queries
8 04-01-10 Join Queries
9 25-01-10 Set operators and simple Operators
10 25-01-10 Views
11 08-02-10Introduction to Procedures and
Functions
12 08-02-10 PL/SQL Programs using
Procedures
13 08-02-10 PL/SQL Programs using Functions
14 20-02-10 Introduction to Triggers
15 20-0210 PL/SQL Programs using Triggers
8/3/2019 CS2258-CSE-DBMSRECORD
3/135
16 26-02-0-10 Introduction to Cursors
17 26-02-10 PL/SQL Programs using Cursors
18 01-03-10 Introduction to Visual Basic
19 01-03-10 Forms
20 12-03-10Introduction to Menu Design and
Reports
21 12-03-10 Reports
22 12-03-10 Menu Design
23 22-03-10Database Design andImplementation of Library
Management System
24 22-03-10
Database Design and
Implementation of Online Banking
System
25 22-03-10
Database Design and
Implementation of Employee
Payroll System
8/3/2019 CS2258-CSE-DBMSRECORD
4/135
ORACLE:
Oracle is a powerful relational database management system that offers a large
feature set. Along with Microsoft SQL Server, Oracle is widely regarded as one of the
two most popular full-featured database systems on the market today.
Traditionally, operating systems regulated resource management among various
applications, including Oracle databases, that run on a system. The Database ResourceManager controls the distribution of resources among various sessions by controlling the
execution schedule inside the database. By controlling which sessions run and for how
long, the Database Resource Manager can ensure that resource distribution matches the
plan directive and hence, the business objectives.
All operations on information in an Oracle database are performed by using SQL statements. A SQLstatement is a string of SQL text. The SQL SELECT statement is the command that retrieves data from the
XE tables.
Sheila will use the SQL SELECT statement to:
Write queries Create SELECT statements that restrict rows
Sort output
Display data from many tables
EXP:NO: INTRODUCTION TO ORACLE-RDBMSDATE:
Customize output with functions embedded in the SELECT
statement
8/3/2019 CS2258-CSE-DBMSRECORD
5/135
What is the basic difference between RDBMS andDBMS?
RDBMS - Relational Database Management System - Multiple users can access
and there will be relationships between the tables, security is increasedDBMS - Database Mangement system - small number of users
A DBMS, is any system that manages databases, an RDBMS is a subtype of DBMS
that is limited to what are called relationaldatabases. Relational databases must use 'relations'
to connect data (a 'relation' might be 'contains' or 'owes-money-to' or any other relationshipbetween two objects [rows in a table, or two or more tables]) as rows have no structure in an
RDBMS - they have to be 'flat' unlike an 'object oriented' dbms which can 'nest' things (as you
may be used to in object oriented programming languages. Check out 'relational algebra' to see
some of the theory behind RDBMSs or even 'RDBMS' and 'SQL' on wikipedia for a betterunderstanding of how they are actually used) P.S. nearly every DBMS is an RDBMS these
days, check out apache's 'couchDB' for a non-relational (document-oriented) DBMS.
ORACLE is a fourth generation relational database management system(RDBMS).In general, a database management system (DBMS) must be able to reliably manage a large
amount of data in a multi-user environment so that many users can concurrently access thesame data. All this must be accomplished while delivering high performance to the users of the
database. A DBMS must also be secure from unauthorized access and provide efficient
solutions for failure recovery. The ORACLE Server provides efficient and effective solutions
for the major database features.ORACLE consists of many tools that allow you to create an application with ease and
flexibility. You must determine how to implement your requirements using the features
available in ORACLE, along with its tools. The features and tools that you choose to useto implement your application can significantly affect the performance of your
application.Several of the more useful features available to ORACLE application developers areintegrity constraints, stored procedures and packages, database triggers, cost-based
optimizer, shared SQL, locking and sequences.
Oracle versions:
Oracle 8:
Oracle8 has been designed to be able to support more users and bigger databases
than Oracle7 by making better use of resources and to be easier to administer and
maintain. It also provides better support for distributed and n-tier environments andsupports a limited set of object oriented features to make the database structure closer to
the real world.
The new features include:Enhancements for very large databasesandon-line transaction processing systems
A Recovery Manager utility to complement Enterprise Manager
Ad hoc enhancements such as password management and index only tablesObject support within the database and object extensions to SQL and PL/SQL
Support for the network computing architecture
http://www.smart-soft.co.uk/Oracle/oracle8-vldb.htmhttp://www.smart-soft.co.uk/Oracle/oracle8-vldb.htmhttp://www.smart-soft.co.uk/Oracle/oracle8-oltp.htmhttp://www.smart-soft.co.uk/Oracle/oracle8-oltp.htmhttp://www.smart-soft.co.uk/Oracle/oracle8-rman.htmhttp://www.smart-soft.co.uk/Oracle/oracle8-adhoc.htmhttp://www.smart-soft.co.uk/Oracle/oracle8-obj.htmhttp://www.smart-soft.co.uk/Oracle/oracle8-nca.htmhttp://www.smart-soft.co.uk/Oracle/oracle8-oltp.htmhttp://www.smart-soft.co.uk/Oracle/oracle8-rman.htmhttp://www.smart-soft.co.uk/Oracle/oracle8-adhoc.htmhttp://www.smart-soft.co.uk/Oracle/oracle8-obj.htmhttp://www.smart-soft.co.uk/Oracle/oracle8-nca.htmhttp://www.smart-soft.co.uk/Oracle/oracle8-vldb.htm8/3/2019 CS2258-CSE-DBMSRECORD
6/135
Oracle 9i:
With Oracle 9i, Oracle continued to enhance the database in many areas but
particularly in terms of support for large customers (unsurprisingly as they spend themost money and have the most demanding requirements) by increasing performance and
scalability but at the same time making the database easier to manage thereby reducing
the total cost of ownership (TCO), and balancing the demands of accountants, developers
and the users.
Changes have been made to Oracle 9i to improve the following technical aspects :-Oracle 9i database performance
ease of management
scalabilitysecurity
availability
Oracle 10g:
The idea of Oracle 10g is that the database will be able to dynamically"requisition" resources from the grid to meet levels of peak demand.
Application of oracle 10g
Other enhancements for Oracle 10g are aimed at reducing costs and improving thequality of service by making the database easier to deploy and manage including
enhancements to backup and recovery and data warehousing .
http://www.smart-soft.co.uk/Oracle/oracle9i-new-features-ov-perf.htmhttp://www.smart-soft.co.uk/Oracle/oracle9i-new-features-ov-man.htmhttp://www.smart-soft.co.uk/Oracle/oracle9i-new-features-ov-scal.htmhttp://www.smart-soft.co.uk/Oracle/oracle9i-new-features-ov-sec.htmhttp://www.smart-soft.co.uk/Oracle/oracle9i-new-features-ov-avail.htmhttp://www.smart-soft.co.uk/Oracle/oracle9i-new-features-ov-perf.htmhttp://www.smart-soft.co.uk/Oracle/oracle9i-new-features-ov-man.htmhttp://www.smart-soft.co.uk/Oracle/oracle9i-new-features-ov-scal.htmhttp://www.smart-soft.co.uk/Oracle/oracle9i-new-features-ov-sec.htmhttp://www.smart-soft.co.uk/Oracle/oracle9i-new-features-ov-avail.htm8/3/2019 CS2258-CSE-DBMSRECORD
7/135
1. Ease of Management
As with Oracle 9i, one of the major focuses of Oracle 10g is on reducing costs
and increasing up-time by making the database easier to manage. One way of doing thisis to automate tasks that previously had to be done manually by the dba. To achieve this
for Oracle 10g, a new Automated Storage Management (ASM) sub-system has been
introduced. This feature removes the need to have a file system or a volume manager for
managing the database files and eliminates the complexity of balancing data across disksand controllers manually. Instead, the ASM stripes data across the disks automatically,
thereby maximizing throughput and minimizing the risk of data loss. The ASM also
maintains the data striping as disks are added/removed and re-balances the i/o loaddynamically.
2. Availability
Oracle 10g Real Application Clusters have been enhanced to provide Automatic
Service Provisioning - servers are automatically allocated to work loads and clients are
automatically assigned to the server with the least load. Also on failure of a server, thesurviving servers are automatically reallocated to work loads.
Other enhancements in this area include:flashback available at the row, transaction, table or database level;
recovery area on disk that is maintained automatically by the database and contains onlythose blocks changed since the last backup - thereby enabling faster recovery from media
failure;
data guard (standby database) has been enhanced to enable compression and encryptionof log traffic from the master database to the standby system;
tables can now be redefined without invalidating stored procedures;
support for rolling upgrades of the hardware, operating system and the database to reduceplanned down time.
3. Data Warehousing
Oracle 10g Data Warehousing enhancements include:an increase in the size limits of the database to support ultra-large databases of millionsof terabytes in size and ultra-large files of terabytes in size. The 4GB restriction on LOBs
has been raised to 128 terabytes.
Improvements to Real Application Clusters (RAC) enable resources to be allocatedautomatically and means that operational data can be used immediately without the need
to copy it to another database.
Enhancements to OLAP analytic, a data-mining GUI and a new SQL model allow queryresults to be treated as sets of multi-dimensional arrays on which complex inter-
dependent operations - such as forecasting - can be run without the need to extract data to
spreadsheets or perform complex joins and unions on the data.
A new changed data capture facility based on Oracle Streams provides low or zerolatency trickle feeds that combined with integrated extraction, transformation and loading
(etl) enable real-time warehousing.
8/3/2019 CS2258-CSE-DBMSRECORD
8/135
Oracle 11g:
The Oracle Database 11g server enables high-speed transactions, better
business decisions and sophisticated applications. These capabilities provide users
the functionality to build high-quality and efficient database applicationsOracle 11g databases, including:
Designing a database with a data model
Navigating the dictionary with Enterprise ManagerCoding with SQL Developer and SQL*Plus
Retrieving and manipulating data with SQL constructs
Creating tables, sequences, views and synonymsManaging security, integrity and performance
Programming with cursors, loops and control logic
Debugging PL/SQL programsBuilding procedures, packages and triggers
Summary
As with Oracle 9i, Oracle 10g has many enhancements to support the largest customers interms of database size limits and continues to remove complexity from the database to
make it easier to manage and reduce the total cost of ownership (TCO), thereby keeping
everyone happy and enhancing the competitiveness of Oracle compared to Microsoft andIBM.
Relational Database Management System
A Relational Database Management System (RDBMS) provides a comprehensive and
integrated approach to information management.A relational model provides the basis for a relational database. A relational model hasthree aspects:
Structures
OperationsIntegrity rules
Structuresconsist of a collection of objects or relations that store data. An example ofrelation is a table. You can store information in a table and use the table to retrieve and
modify data.
Operations are used to manipulate data and structures in a database. When usingoperations. You must adhere to a predefined set of integrity rules.
Integrity rules are laws that govern the operations allowed on data in a database. Thisensures data accuracy and consistency.
8/3/2019 CS2258-CSE-DBMSRECORD
9/135
Relational database components include:
Table
Row
ColumnField
Primary key
Foreign key
A Table is a basic storage structure of an RDBMS and consists of columns androws. A table represents an entity. For example, the S_DEPT table stores information
about the departments of an organization.ARowis a combination of column values in a table and is identified by a primary key.Rows are also known as records. For example, a row in the table S_DEPT contains
information about one department.
A Column is a collection of one type of data in a table. Columns represent the
attributes of an object. Each column has a column name and contains values that are
bound by the same type and size. For example, a column in the table S_DEPT specifiesthe names of the departments in the organization.
Fieldis an intersection of a row and a column. A field contains one data value. If
there is no data in the field, the field is said to contain a NULL value.
8/3/2019 CS2258-CSE-DBMSRECORD
10/135
Figure 1-2. Table, Row,
Column & Field
APrimary key is a column or a combination of columns that is used to uniquely identify
each row in a table. For example, the column containing department numbers in theS_DEPT table is created as a primary key and therefore every department number is
different. A primary key must contain a value. It cannot contain a NULL value.
A Foreign key is a column or set of columns that refers to a primary key in the same table
or another table. You use foreign keys to establish principle connections between, orwithin, tables. A foreign key must either match a primary key or else be NULL. Rows are
connected logically when required. The logical connections are based upon conditions
that define a relationship between corresponding values, typically between a primary keyand a matching foreign key. This relational method of linking provides great flexibility as
it is independent of physical links between records.
RDBMS Properties
8/3/2019 CS2258-CSE-DBMSRECORD
11/135
An RDBMS is easily accessible. You execute commands in the Structured Query
Language (SQL) to manipulate data. SQL is the international Standards Organization
(ISO) standard language for interacting with a RDBMS.
An RDBMS provides full data independence. The organization of the data is independent
of the applications that use it. You do not need to specify the access routes to tables or
know how data is physically arranged in a database.
A relational database is a collection of individual, named objects. The basic unit of data
storage in a relational database is called a table. A table consists of rows and columnsused to store values. For access purpose, the order of rows and columns is insignificant.
You can control the access order as required.
When querying the database, you use conditional operations such as joins and
restrictions. A join combines data from separate database rows. A restriction limits thespecific rows returned by a query.
Database Resource Manager
Traditionally, operating systems regulated resource management among variousapplications, including Oracle databases, that run on a system. The Database Resource
Manager controls the distribution of resources among various sessions by controlling the
execution schedule inside the database. By controlling which sessions run and for howlong, the Database Resource Manager can ensure that resource distribution matches the
plan directive and hence, the business objectives.
Several of the more useful features available to ORACLE application developers
are integrity constraints, stored procedures and packages, database triggers, cost-based
optimizer, shared SQL, locking and sequences.
8/3/2019 CS2258-CSE-DBMSRECORD
12/135
Figure 1-5. Conditional operations
An RDBMS enables data sharing between users. At the same time, you can
ensure consistency of data across multiple tables by using integrity constraints. An
RDBMS uses various types of data integrity constraints. These types include entity,column, referential and user-defined constraints.
The constraint, entity, ensures uniqueness of rows, and the constraint column ensures
consistency of the type of data within a column. The other type, referential, ensures
validity of foreign keys, and user-defined constraints are used to enforce specific businessrules.
An RDBMS minimizes the redundancy of data. This means that similar data is not
repeated in multiple tables.
ADVANTAGE AND DISADVANTAGE OF USING SMALLER AND
BIGGER DATA BLOCKS IN ORACLE
Whether I will use bigger or smaller data blocks in my database it can be
specified by parameter DB_BLOCK_SIZE or DB_nK_CACHE_SIZE. With the settings
I can I can differentiate three types of data blocks in oracle.
1)Small Block(2KB-4KB)
2)Medium Block(8KB)
3)Large Block(16KB-32KB)
8/3/2019 CS2258-CSE-DBMSRECORD
13/135
Advantages of Bigger Blocks
Using bigger blocks means more data transfer per I/O call. So faster data transfer from
disk to memory.
Using bigger blocks means more space for key storage in the branch nodes of B*-tree
indexes, which reduces index height, which improves the performance of indexed
queries.
When using large block there are less probability of chained and migrated rows, which
in turn reduced the number of reads required to get the information.
Disadvantages of bigger Blocks
If the rows are predominated random then you are increasing the possibility ofcontention in the buffer cache. Because now with same same amount of memory in
buffer cache as it was in small blocks, we need more memory in the buffer cache to keep
the same amount of buffers in memory in the buffer cache.
If you have high transactional concurrency to a segment, using bigger blocks is justgoing to make the concurrency even higher.
Advantages and disadvantages of these blocks
1)Small Block(2KB-4KB): The advantage of small blocks are they reduce blockcontention and they are really good where there is small rows or the selectivity of rows
are highly random.
The disadvantages of small blocks are they have relatively larger overhead.
2)Medium Block(8KB): The advantage of medium blocks are if the rows are of mediumsize then you can bring a number of rows in a single I/O.
8/3/2019 CS2258-CSE-DBMSRECORD
14/135
The disadvantage of it is space in the buffer cache will be wasted if you are doing
random access to small rows and have a large block size. For example, with an 8KB
block size and 60 byte row size, you are wasting 8000-60=7940 bytes in the buffer cachewhen doing random access.
3)Large Block(16KB-32KB): If you use larger block then relatively less overhead. PerI/O you can fetch more data. This is very good for sequential access, or very large rows.
Large block size is not good for index blocks used in an OLTP(Online Transaction
Processing) type environment, because they increase block contention on the index leafblocks.
8/3/2019 CS2258-CSE-DBMSRECORD
15/135
RESULT:
Thus the introduction to ORACLE-RDBMS has been studied.
8/3/2019 CS2258-CSE-DBMSRECORD
16/135
Structured Query Language (SQL) is the set of statements with which all programs
allow users access to the database without using SQL directly, but these applications in
turn must use SQL when executing the user's request. This chapter provides
background information on SQL as used by most database systems.
History of SQL
Dr. E. F. Codd published the paper, "A Relational Model of Data for Large Shared DataBanks", in June 1970 in the Association of Computer Machinery (ACM) journal,
Communications of the ACM. Codd's model is now accepted as the definitive model for
relational database management systems (RDBMS). The language, Structured EnglishQuery Language ("SEQUEL") was developed by IBM Corporation, Inc., to use Codd's
model. SEQUEL later became SQL (still pronounced "sequel"). In 1979, Relational
Software, Inc. (now Oracle Corporation) introduced the first commercially availableimplementation of SQL. Today, SQL is accepted as the standard RDBMS language.
SQL Standards
Oracle Corporation strives to comply with industry-accepted standards and participates
actively in SQL standards committees. Industry-accepted committees are the American
National Standards Institute (ANSI) and the International Standards Organization (ISO),which is affiliated with the International Electrotechnical Commission (IEC). Both ANSI
and the ISO/IEC have accepted SQL as the standard language for relational databases.
When a new SQL standard is simultaneously published by these organizations, the namesof the standards conform to conventions used by the organization, but the standards are
technically identical.
The latest SQL standard was adopted in July 1999 and is often called SQL:99. The
formal names of this standard are:
ANSI X3.135-1999, "Database Language SQL", Parts 1 ("Framework"), 2
("Foundation"), and 5 ("Bindings")
ISO/IEC 9075:1999, "Database Language SQL", Parts 1 ("Framework"), 2
("Foundation"), and 5 ("Bindings")
EXP:NO: INTRODUCTION TO ORACLE-SQL
DATE:
8/3/2019 CS2258-CSE-DBMSRECORD
17/135
ANSI and ISO standard SQL:
SQL-86
SQL-89
SQL-92
SQL:1999 (language name became Y2K compliant!)
SQL:2003
IMPORTANCE OF SQL:
SQL provides statements for a variety of tasks, including:
Querying data
Inserting, updating, and deleting rows in a table
Creating, replacing, altering, and dropping objects
Controlling access to the database and its objects Guaranteeing database consistency and integrity
Common Language for All Relational Databases
All major relational database management systems support SQL, so you can transfer all
skills you have gained with SQL from one database to another. In addition, all programswritten in SQL are portable. They can often be moved from one database to another with
very little modification.
Embedded SQL
Embedded SQL refers to the use of standard SQL statements embedded within a
procedural programming language. The embedded SQL statements are documented in theOracle precompiler books.
Embedded SQL is a collection of these statements:
All SQL commands, such as SELECT and INSERT, available with SQL with
interactive tools
Dynamic SQL execution commands, such as PREPARE and OPEN, which
integrate the standard SQL statements with a procedural programming language
Embedded SQL also includes extensions to some standard SQL statements. Embedded
SQL is supported by the Oracle precompilers. The Oracle precompilers interpretembedded SQL statements and translate them into statements that can be understood by
procedural language compilers.
.
Using SQL *Plus to communicate with Oracle Databases
8/3/2019 CS2258-CSE-DBMSRECORD
18/135
SQL*Plus is an interactive and batch query tool that is installed with every Oracle Serveror Client installation. It has a command-line user interface, and more recently, a web-
based user INTERFACE called SQL*PLUS.
On Windows platforms, context menu options accessed through the right mouse buttonenable local files to be sent to the SQL*Plus user interface.
SQL*Plus has its own commands and environment, and it provides access to the Oracle
RDBMS. It allows you to enter and execute SQL, PL/SQL, SQL*Plus and operating
system commands to perform the following:
1. enter SQL*Plus commands to configure the SQL*Plus environment
2. enter, edit, store, retrieve, and run SQL commands and PL/SQL blocks
3. format , perform calculations on, store, and print from query results4. interact with an end user
5. startup and shutdown a database
6. connect to a database
7. define variables8. capture errors
9. list column definitions for any table
10. perform database administration
Result:
8/3/2019 CS2258-CSE-DBMSRECORD
19/135
Thus the introduction to ORACLE-SQL has been studied.
DDL COMMANDS OUTPUT:
1. Create table:
SQL> create table student(RegNo number(10),name varchar2(15),dept varchar2(10));
Table created.
SQL> desc student;
Name Null? Type--------------------------------------- -------- ----------------------------
REGNO NUMBER(10)
NAME VARCHAR2(15)DEPT VARCHAR2(10)
2. Alter table:
(i) add
SQL> alter table student add(status varchar2(5));
Table altered.
SQL> desc student;
Name Null? Type
----------------------------------------- -------- ----------------------------REGNO NUMBER(10)
NAME VARCHAR2(15)
DEPT VARCHAR2(10)STATUS VARCHAR2(5)
(ii) modify
SQL> alter table student modify(dept varchar2(5));
Table altered.
SQL> desc student;
Name Null? Type
----------------------------------------- -------- ----------------------------
REGNO NUMBER(10)NAME VARCHAR2(15)
DEPT VARCHAR2(5)
STATUS VARCHAR2(5)
EXP:NO: DATA DEFINITION LANGUAGE COMMANDS
DATE:
8/3/2019 CS2258-CSE-DBMSRECORD
20/135
(iii) drop
SQL> alter table student drop column status;Table altered.
SQL> desc student;
Name Null? Type----------------------------------------- -------- ----------------------------
REGNO NUMBER(10)
NAME VARCHAR2(15)
DEPT VARCHAR2(5)
3. Truncate Command
SQL> truncate table student;
Table truncated.
SQL> select * from student;no rows selected
4. Drop Command
SQL> drop table student;
Table dropped.
SQL> desc student;
ERROR:
ORA-04043: object student does not exist
8/3/2019 CS2258-CSE-DBMSRECORD
21/135
SQL> create table customer(cname char(10) constraint c1 primary key,cstreet
char(15),ccity char(10));Table created.
SQL> desc customer;
Name Null? Type
----------------------------- ----------- ----------------------------CNAME NOT NULL CHAR(10)
CSTREET CHAR(15)
CCITY CHAR(10)
SQL> insert into customer values('&cname','&cstreet','&ccity');
Enter value for cname: RajEnter value for cstreet: STG streetEnter value for ccity: Chennai
old 1: insert into customer values('&cname','&cstreet','&ccity')
new 1: insert into customer values('Raj','STG street','Chennai')
1 row created.
SQL> /
Enter value for cname: Ram
Enter value for cstreet: KK street
Enter value for ccity: Kolkattaold 1: insert into customer values('&cname','&cstreet','&ccity')
new 1: insert into customer values('Ram','KK street','Kolkatta')
1 row created.
SQL> /Enter value for cname: Kumar
Enter value for cstreet: VSV street
Enter value for ccity: Mumbai
old 1: insert into customer values('&cname','&cstreet','&ccity')
new 1: insert into customer values('Kumar','VSV street','Mumbai')
1 row created.
EXP:NO: DATA MANIPULATION LANGUAGE COMMANDSDATE:
8/3/2019 CS2258-CSE-DBMSRECORD
22/135
SQL> /Enter value for cname: Rajan
Enter value for cstreet: SSR street
Enter value for ccity: Chennaiold 1: insert into customer values('&cname','&cstreet','&ccity')
new 1: insert into customer values('Rajan','SSR street','Chennai')
1 row created.
SQL> select * from customer;
CNAME CSTREET CCITY
---------- --------------- ----------
Raj STG street ChennaiRam KK street Kolkatta
Kumar VSV street Mumbai
Rajan SSR street Chennai
4 rows selected.
SQL> update customer set ccity='Madurai' where cname='Ram';1 row updated.
SQL> select * from customer;CNAME CSTREET CCITY
---------- --------------- ----------
Raj STG street ChennaiRam KK street Madurai
Kumar VSV street Mumbai
Rajan SSR street Chennai
SQL> delete from customerwhere ccity='Chennai';
2 rows deleted.
SQL> select * from customer;
CNAME CSTREET CCITY
---------- --------------- ----------Ram KK street Madurai
Kumar VSV street Mumbai
8/3/2019 CS2258-CSE-DBMSRECORD
23/135
1. Table Creations
SQL> create table customer(cname char(10) constraint c1 primarykey,cstreet
char(15),ccity char(10));
Table created.
SQL> desc customer;
Name Null? Type----------------------------------------- ------------ ----------------------------
CNAME NOT NULL CHAR(10)
CSTREET CHAR(15)
CCITY CHAR(10)
SQL> insert into customer values('Raj','STG street','Chennai');
1 row created.
SQL> insert into customer values('Ram','KK street','Kolkatta');
1 row created.
SQL> insert into customer values('Kumar','VSV street','Mumbai');
1 row created.
SQL> insert into customer values('Rajan','SSR street','Chennai');1 row created.
SQL> select * from customer;
CNAME CSTREET CCITY
---------- --------------- ----------Raj STG street Chennai
Ram KK street Kolkatta
Kumar VSV street MumbaiRajan SSR street Chennai
4 rows selected.
SQL> create table branch(bname char(10) constraint c2 primary key,baddr char(15));
Table created.
SQL> desc branch;
Name Null? Type
----------------------------------------- ------------- ----------------------------BNAME NOT NULL CHAR(10)
EXP:NO: CONSTRAINTSDATE:
8/3/2019 CS2258-CSE-DBMSRECORD
24/135
BADDR CHAR(15)SQL> insert into branch values('AVJ','Chennai');
1 row created.
SQL> insert into branch values('STG','Mumbai');
1 row created.
SQL> insert into branch values('RRJ','Saidapet');1 row created.
SQL> insert into branch values('BSS','Kerala');1 row created.
SQL> select * from branch;BNAME BADDR
---------- ---------------
AVJ ChennaiSTG Mumbai
RRJ SaidapetBSS Kerala
SQL> create table account(acno number(10) constraint c3 primary key,bname
char(10),balance number(10));
Table created.
SQL> desc account;
Name Null? Type----------------------------------------- ------------- ----------------------------
ACNO NOT NULL NUMBER(10)
BNAME CHAR(10)BALANCE NUMBER(10)
SQL> insert into account values(1000,'AVJ',55000);
1 row created.
SQL> insert into account values(1001,'BSS',45210);
1 row created.
SQL> insert into account values(1002,'STG',100000);
1 row created.
SQL> insert into account values(1003,'RRJ,55410);
1 row created.
SQL> select * from account;
ACNO BNAME BALANCE---------- ---------- ----------
1000 AVJ 55000
8/3/2019 CS2258-CSE-DBMSRECORD
25/135
1001 BSS 452101002 STG 100000
1003 RRJ 55410
SQL> create table depositor(dname char(15) constraint c4 referencescustomer(cname),accno number(10) constraint c5 references account(acno));
Table created.
SQL> desc depositor;
Name Null? Type
----------------------------------------- -------- ----------------------------DNAME CHAR(15)
ACCNO NUMBER(10)
8/3/2019 CS2258-CSE-DBMSRECORD
26/135
TCL COMMAND OUTPUT:
SQL> create table tab(name char(10), lno number(10));
Table created.
SQL> desc tab;
Name Null? Type
----------------------------- -------------------- ----------------------------NAME VARCHAR2(10)
LNO NUMBER(10)
SQL> insert into tab values('Raj',1000);1 row created.
SQL> insert into tab values('Kumar',1001);1 row created.
SQL> savepoint s;
Savepoint created.
SQL> insert into tab values('Babu',1002);
1 row created.
SQL> insert into tab values('Ragu',1003);1 row created.
SQL> select * from tab;
NAME LNO
---------- ----------Raj 1000
Kumar 1001
Babu 1002
Ragu 1003
SQL> rollback to s;
Rollback complete.
EXP:NO: TRANSACTION CONTROL LANGUAGE COMMANDSDATE:
8/3/2019 CS2258-CSE-DBMSRECORD
27/135
SQL> select * from tab;
NAME LNO
---------- ----------
Raj 1000Kumar 1001
8/3/2019 CS2258-CSE-DBMSRECORD
28/135
NESTED QUERIES
CREATING TABLES:
SQL> create table acc1(accno number(10), br_name varchar2(10), balance number(10));Table created.
SQL> desc acc1;
Name Null? Type--------------------- ---------- ----------------------
ACCNO NUMBER(10)
BR_NAME VARCHAR2(10)BALANCE NUMBER(10)
SQL> select * from acc1;ACCNO BR_NAME BALANCE
---------- --------------- ----------------
1231 Mumbai 500001232 Delhi 700001233 Jaipur 80000
1234 Hyderabad 45000
SQL> create table acc12(accno number(10), br_name varchar2(10), balance
number(10));
Table created.
SQL> desc acc12;
Name Null? Type
--------------------- ---------- ----------------------ACCNO NUMBER(10)
BR_NAME VARCHAR2(10)
BALANCE NUMBER(10)
SQL> select * from acc12;ACCNO BR_NAME BALANCE
---------- ---------------- ----------------
EXP:NO: NESTED QUERIESDATE:
8/3/2019 CS2258-CSE-DBMSRECORD
29/135
1235 Chennai 340001236 Mysore 47000
TO CREATE A TABLE USING NESTED QUERY:
SQL> create table acc72 as select * from acc1;Table created.
SQL> select * from acc72;
ACCNO BR_NAME BALANCE---------- ---------- ----------
1231 Mumbai 50000
1232 Delhi 700001233 Jaipur 80000
1234 Hyderabad 45000
TO INSERT TUPLE USING NESTED QUERY:
SQL> insert into acc72 select * from acc12;2 rows created.
SQL> select * from acc72;
ACCNO BR_NAME BALANCE---------- --------------- ---------------1231 Mumbai 50000
1232 Delhi 70000
1233 Jaipur 800001234 Hyderabad 45000
1235 Chennai 34000
1236 Mysore 47000
6 rows selected.
TO DELETE A TUPLE USING NESTED QUEYR:
SQL> delete from acc72 where accno= (select accno from acc1 where
balance=45000);
1 row deleted.
8/3/2019 CS2258-CSE-DBMSRECORD
30/135
SQL> select * from acc72;
ACCNO BR_NAME BALANCE---------- -------------- ---------------
1231 Mumbai 50000
1232 Delhi 700001233 Jaipur 80000
1235 Chennai 34000
1236 Mysore 47000
TO UPDATE A TUPLE USING NESTED QUERY:
SQL> update acc72 set balance=75000 where br_name= (select br_name from acc1 where accn
=1231);
1 row updated.
SQL> select * from acc72;
ACCNO BR_NAME BALANCE
---------- ---------------- ---------------1231 Mumbai 75000
1232 Delhi 70000
1233 Jaipur 800001235 Chennai 340001236 Mysore 47000
TO SELECT A TUPLE USING NESTED QUERY:
SQL> select * from acc72 where accno= 2 (select accno from acc12 where
balance=34000);
ACCNO BR_NAME BALANCE
---------- ---------------- ----------------1235 Chennai 34000
1 row selected.
8/3/2019 CS2258-CSE-DBMSRECORD
31/135
JOIN OPERATION OUTPUT:1.SELF JOIN
SQL> create table emplo(name char(10), id number(10),cabin number(10));Table created.
SQL> desc emplo;
Name Null? Type
----------------------- -------------- ------------------------- NAME CHAR(10)
ID NUMBER(10)
CABIN NUMBER(10)
SQL> insert into emplo values('selvaraj',88,2);
1 row created.
SQL> insert into emplo values('Rajiv',76,3);
1 row created.
SQL> insert into emplo values('Prakash',72,6);
1 row created.
SQL> insert into emplo values('Rahul',96,96);
1 row created.
SQL> select * from emplo; NAME ID CABIN
---------- ---------- ----------
Selvaraj 88 2Rajiv 76 3
Prakash 72 6
Rahul 96 96
SQL> select emplo.name,emplo.id,emplo.cabin from emplo where
emplo.id=emplo.cabin;
EXP:NO: JOIN QUERIESDATE:
8/3/2019 CS2258-CSE-DBMSRECORD
32/135
NAME ID CABIN---------- ---------- ----------
Rahul 96 96
2.EQUI JOIN AND NON-EQUI JOIN
SQL> create table stud1(name char(10),Rno number(10),status char(10));
Table created.
SQL> desc stud1;
Name Null? Type--------------------- ------------- -------------------
NAME CHAR(10)
RNO NUMBER(10)STATUS CHAR(10)
SQL> insert into stud1 values('Selva',88,'Pass');
1 row created.
SQL> insert into stud1 values('Vinoth',13,'Pass');
1 row created.
SQL> insert into stud1 values('Vipin',65,'Pass');
1 row created.
SQL> insert into stud1 values('Prakash',72,'Pass');
1 row created.
SQL> select * from stud1;
NAME RNO STATUS------------- ---------- ----------Selva 88 Pass
Vinoth 13 Pass
Vipin 65 PassPrakash 72 Pass
SQL> create table stud2(name char(10),Rno number(10),status char(10));Table created.
SQL>desc stud2;
Name Null? Type-------------------- ------------- ------------------
NAME CHAR(10)
RNO NUMBER(10)STATUS CHAR(10)
SQL> insert into stud2 values('Rajiv',76,'Pass');1 row created.
8/3/2019 CS2258-CSE-DBMSRECORD
33/135
SQL> insert into stud2 values('Priya',89,'Fail');1 row created.
SQL> insert into stud2 values('Gopi',72,'Pass');1 row created.
SQL> insert into stud2 values('Vinoth',12,'Pass');
1 row created.
SQL> select * from stud2;
NAME RNO STATUS--------------- ---------- ----------
Rajiv 76 Pass
Priya 89 FailGopi 72 Pass
Vinoth 12 Pass
SQL> select e1.name,e2.name from stud1 e1,stud2 e2 where e1.Rno=e2.Rno;
NAME NAME---------- ----------
Prakash Gopi
SQL> select stud1.name,stud2.name from stud1,stud2 where
stud1.statusstud2.status;
NAME NAME
---------- ----------
Selva PriyaRaj Priya
Ram Priya
Prakash Priya
3.LEFT OUTER JOIN
SQL> select s.name,ss.name from stud1 s,stud2 ss where s.Rno=ss.Rno(+);
NAME NAME---------- ----------
Raj
RamPrakash Gopi
Selva
4.RIGHT OUTER JOIN
SQL> select s.name,ss.name from stud1 s,stud2 ss where s.Rno(+)=ss.Rno; NAME NAME
---------- ----------Vinoth
Prakash Gopi
Rajiv
8/3/2019 CS2258-CSE-DBMSRECORD
34/135
Priya
SET OPERATION
SQL> create table stud2(s_rollno number(10), name varchar2(15), mark number(10));
Table created.
SQL> desc stud2; Name Null? Type
--------------------------------------- -------- ----------------------------
S_ROLLNO NOT NULL NUMBER(10)NAME VARCHAR2(15)
MARK NUMBER(10)
SQL> select * from stud2;S_ROLLNO NAME MARK
---------------- ------------ ----------
21308104 Prakash 8921308105 Rajiv 90
21308106 Rahul 78
21308107 Selva 7821308108 Vinoth 98
SQL> create table stud3(s_rollno number(10), name varchar2(15), mark number(10));Table created.
SQL> desc stud3; Name Null? Type
--------------------------------------- -------- ----------------------------
S_ROLLNO NOT NULL NUMBER(10)
NAME VARCHAR2(15)MARK NUMBER(10)
SQL> select * from stud3;S_ROLLNO NAME MARK
EXP:NO: SET OPERATORS AND SIMPLE OPERATORSDATE:
8/3/2019 CS2258-CSE-DBMSRECORD
35/135
---------- ---------- ----------21308106 Rahul 78
21308107 Selva 78
21308108 Vinoth 9921308109 Vipin 56
21308110 Tharachand 89
UNION
SQL> select name from stud2 union select name from stud3;NAME
----------
PrakashRahul
Rajiv
SelvaTharachand
VipinVinoth
7 rows selected.
SQL> select name, s_rollno from stud2 union select name, s_rollno from stud3; NAME S_ROLLNO
---------- ----------
Prakash 21308104Rahul 21308106
Rajiv 21308105
Selva 21308107Tharachand 21308110Vipin 21308109
Vinoth 21308108
7 rows selected.
UNION ALL
SQL> select name from stud2 union all select name from stud3;
NAME
----------Prakash
Rajiv
RahulSelva
Vinoth
RahulSelva
Vinoth
8/3/2019 CS2258-CSE-DBMSRECORD
36/135
VipinTharachand
10 rows selected.
SQL> select name, s_rollno from stud2 union all select name, s_rollno from stud3; NAME S_ROLLNO
---------- ----------Prakash 21308104
Rajiv 21308105
Rahul 21308106Selva 21308107
Vinoth 21308108
Rahul 21308106Selva 21308107
Vinoth 21308108Vipin 21308109
Tharachand 21308110
10 rows selected.
INTERSECT
SQL> select name, s_rollno from stud2 intersect select name, s_rollno from stud3; NAME S_ROLLNO
--------- ----------Rahul 21308106Selva 21308107
Vinoth 21308108
MINUS
SQL> select name, s_rollno from stud2 minus select name, s_rollno from stud3; NAME S_ROLLNO
--------- ----------
Prakash 21308104
Rajiv 21308105
SQL> select name, s_rollno from stud3 minus select name, s_rollno from stud2;
NAME S_ROLLNO---------- ----------
Tharachand 21308110
Vipin 21308109
8/3/2019 CS2258-CSE-DBMSRECORD
37/135
SIMPLE OPERATIONS
ARITHMETIC OPERATION
SQL> select s_rollno, name, mark+10 from stud2;S_ROLLNO NAME MARK+10
--------------- ------------ ---------------
21308104 Prakash 9921308105 Rajiv 100
21308106 Rahul 88
21308107 Selva 8821308108 Vinoth 108
RENAME OPERATION
SQL> select mark+10 "New mark" from stud3;New mark
----------88
88
10966
99
COMPARISON OPERATON
SQL> select * from stud2 where mark>80;
S_ROLLNO NAME MARK-------------------- ---------------- ------------------
21308104 Prakash 89
21308105 Rajiv 9021308108 Vinoth 98
LOGICAL OPERATION
SQL> select * from stud2 where mark>80 and mark
8/3/2019 CS2258-CSE-DBMSRECORD
38/135
SQL> select * from stud3 where mark between 80 and 95;S_ROLLNO NAME MARK
---------- ---------- ----------
21308110 Tharachand 89
NOT BETWEEN OPERATION
SQL> select * from stud3 where mark not between 80 and 95;S_ROLLNO NAME MARK
-------------------- -------------- ------------------21308106 Rahul 78
21308107 Selva 78
21308108 Vinoth 9921308109 Vipin 56
LIKE OPERATION
SQL> select * from stud2 where name like 'P%;S_ROLLNO NAME MARK
-------------------- ------------- --------------21308104 Prakash 89
IN OPERATION
SQL> select * from stud2 where name in ('Prakash','Rajiv');
S_ROLLNO NAME MARK-------------- ---------- ----------
21308104 Prakash 89
21308105 Rajiv 90
NOT IN OPERATION
SQL> select * from stud2 where name not in ('Prakash','Rajiv');S_ROLLNO NAME MARK
---------- -------- -------
21308106 Rahul 78
21308107 Selva 7821308108 Vinoth 98ORDERING OPERATION
SQL> select * from stud3 order by name desc;S_ROLLNO NAME MARK
---------- ---------- ----------
8/3/2019 CS2258-CSE-DBMSRECORD
39/135
21308108 Vinoth 9921308109 Vipin 56
21308110 Tharachand 89
21308107 Selva 7821308106 Rahul 78
SQL> select * from stud3 order by name asc;S_ROLLNO NAME MARK
---------- ---------- ----------21308106 Rahul 78
21308107 Selva 78
21308110 Tharachand 8921308109 Vipin 56
21308108 Vinoth 99
DISTINCT OPERATION
SQL> select distinct mark from stud2;
MARK----------
78
8990
98
SQL> select distinct mark from stud3;MARK
----------
5678
89
99.
8/3/2019 CS2258-CSE-DBMSRECORD
40/135
JOIN VIEW:
SQL> create table cust(name varchar2(10),street varchar2(10),age number(10));
Table created.
SQL> desc cust;
Name Null? Type
-------------------------------- -------- ----------------------------NAME VARCHAR2(10)
STREET VARCHAR2(10)
AGE NUMBER(10)
SQL> insert into cust values('Rajiv','abc st',78);
1 row created.
SQL> into cust values('Praksh','bcd st',18);
1 row created.
SQL> insert into cust values('STG','rama st',16);
1 row created.
SQL>insert into cust values('Rahul','sss st',19);
1 row created.
SQL> insert into cust values('Vipin','keral st',21);
1 row created.
SQL> insert into cust values('Vinoth','rama st',18);
1 row created.
SQL> select * from cust;
EXP:NO: VIEWS
DATE:
8/3/2019 CS2258-CSE-DBMSRECORD
41/135
NAME STREET AGE---------- ------------- ----------
Rajiv abc st 78
Praksh bcd st 18STG rama st . 16
Rahul sss st 19
Vipin keral st 21
Vinoth rama st 18
6 rows selected.
SQL> create table customer (c_name varchar2(10),c_street varchar2(10), c_cityvarchar2(10));
Table Created.
SQL> desc customer;
Name Null? Type----------------------------- --------------- ----------------------------
C_NAME NOT NULL VARCHAR2(10)C_STREET VARCHAR2(10)
C_CITY VARCHAR2(10)
SQL> insert into customer values('Rahul','bengal st','Avadi');
1 row created.
SQL> insert into customer values('Vipin','raja st','Kerala');
1 row created.
SQL> insert into customer values('Sarvesh','tagore st','Bangalore');1 row created.
SQL> insert into customer values('Prakash','Bharathi st','Chennai');1 row created.
SQL> select * from customer;C_NAME C_STREET C_CITY
------------- ---------------- ------------
Sarvesh tagore st Banglore
Prakash barathi st ChennaiRahul bengal st Avadi
Vipin raja st Kerala
4 rows selected.
SQL> create view v1 as select customer.c_name,customer.c_city,cust.age fromcustomer,cust where customer.c_name=cust.name;
View created.
8/3/2019 CS2258-CSE-DBMSRECORD
42/135
SQL> desc v1;
Name Null? Type
---------------------------- --------------- ----------------------------C_NAME NOT NULL VARCHAR2(10)
C_CITY VARCHAR2(10)
AGE NUMBER(10)
SQL> select * from v1;C_NAME C_CITY AGE
------------- ---------- ----------
Rahul Avadi 19Vipin Kerala 21
GROUP BY VIEW:
SQL> create view v2 as select age from cust group by age;
View created.
SQL> desc v2;
Name Null? Type
--------------------------------- -------- ----------------------------AGE NUMBER(10)
SQL> select * from v2;AGE
----------
1618
19
21
78
READ ONLY VIEW:
SQL> create view v3 as select * from cust where age=18 with read only;View created.
SQL> desc v3;
Name Null? Type
--------------------------------- -------- ----------------------------
NAME VARCHAR2(10)STREET VARCHAR2(10)
AGE NUMBER(10)
8/3/2019 CS2258-CSE-DBMSRECORD
43/135
SQL> select * from v3;
NAME STREET AGE
---------- --------------- ----------Praksh bcd st 18
Vinoth rama st 18
SQL> update v3 set age=19 where name='Praksh';update v3 set age=19 where name='Praksh'
*
ERROR at line 1:ORA-01733: virtual column not allowed here
SQL> delete from v3 where age=18;
delete from v3 where age=18*
ERROR at line 1:
ORA-01752: cannot delete from view without exactly one key-preserved table
8/3/2019 CS2258-CSE-DBMSRECORD
44/135
Procedures and Functions
PL/SQL subprograms
A subprogram is a named block of PL/SQL. There are two types of subprograms in
PL/SQL namely Procedures and Functions. Every subprogram will have a declarativepart, an executable part or body, and an exception handling part, which is optional.
Declarative part contains variable declarations. Body of a subprogram contains
executable statements of SQL and PL/SQL. Statements to handle exceptions are writtenin exception part.
When client executes a procedure are function, the processing is done in the server. Thisreduces network traffic. The subprograms are compiled and stored in the Oracle database
as stored programs and can be invoked whenever required. As they are stored in
compiled form when called they only need to be executed. Hence they save time neededfor compilation.
Subprograms provide the following advantages
1. They allow you to write PL/SQL program that meet our need
2. They allow you to break the program into manageable modules.3. They provide reusability and maintainability for the code.
Procedures
Procedure is a subprogram used to perform a specific action. A procedure contains twoparts specification and the body. Procedure specification begins with CREATE and ends
with procedure name or parameters list. Procedures that do not take parameters are
written without a parenthesis. The body of the procedure starts after the keyword IS orAS and ends with keyword END.
EXP:NO: INTRODUTION TO PROCEDURES AND FUNCTIONS
DATE:
8/3/2019 CS2258-CSE-DBMSRECORD
45/135
In the above given syntax things enclosed in between angular brackets (< > ) are
user defined and those enclosed in square brackets ([ ]) are optional.OR REPLACE is used to overwrite the procedure with the same name if there any.
AUTHID clause is used to decide whether the procedure should execute with invoker
(current-user or person who executes it) or with definer (owner or person created) rights .
Parameter Modes
Parameters are used to pass the values to the procedure being called. There are 3 modesto be used with parameters based on their usage. IN, OUT, and IN OUT.IN mode parameter used to pass the values to the called procedure. Inside the program IN
parameter acts like a constant. i.e it cannot be modified.
OUT mode parameter allows you to return the value from the procedure. Inside
Procedure the OUT parameter acts like an uninitialized variable. Therefore its value
cannot be assigned to another variable.
IN OUT mode parameter allows you to both pass to and return values from the
subprogram. Default mode of an argument is IN.
8/3/2019 CS2258-CSE-DBMSRECORD
46/135
Functions:
A function is a PL/SQL subprogram, which is used to compute a value. Function is samelike a procedure except for the difference that it have RETURN clause.
Syntax for Function
Examples
Function without arguments
8/3/2019 CS2258-CSE-DBMSRECORD
47/135
Function with arguments. Different ways of executing the function.
To drop the procedure or function :
Drop procedure procedurename;Drop function functionname;
For Discovering Errors:
Show errors procedure procedurename;
8/3/2019 CS2258-CSE-DBMSRECORD
48/135
Show errors function functionname;
Result:
Thus the introduction to procedure and functions has been studied.
Aim:
To create PL/SQL procedures for various operations.
PROCEDURES
1. Write a procedure to insert records into a student table
2. Write a procedure to update the values inserted in student table.
3. Write a procedure to check if particular record exists.
4. Write a PL/SQL block to find the area for the following radius and it insert it
into AREAS table.
TABLES TO BE CREATED:
SQL> create table stu(st_name varchar2(10),st_age number(3));
Table created.
SQL> create table ar(area numeric(5,2),radius numeric(6,2));
Table created.
EXP:NO: PL/SQL PROGRAMS USING PROCEDURESDATE:
8/3/2019 CS2258-CSE-DBMSRECORD
49/135
SQL> create table pupil(name varchar2(10),age number(3));
Table created.
TABLE DESCRIPTION:
SQL> desc stu;
Name Null? Type----------------------------------------- -------- ----------------------------
ST_NAME VARCHAR2(10)
ST_AGE NUMBER(3)
SQL> desc ar;
Name Null? Type----------------------------------------- -------- ----------------------------
AREA NUMBER(5,2)
RADIUS NUMBER(6,2)
SQL> desc pupil;
Name Null? Type----------------------------------------- -------- ----------------------------
NAME VARCHAR2(10)
AGE NUMBER(3)
PROCEDURE 1:
SQL> create procedure newstu(st_name in varchar,st_age in number)as2 begin
3 insert into stu(st_name,st_age)
4 values(st_name,st_age);5 end;
6 /
Procedure created.
SQL> exec newstu('ram','20');
PL/SQL procedure successfully completed.
SQL> select * from stu;
ST_NAME ST_AGE
8/3/2019 CS2258-CSE-DBMSRECORD
50/135
---------- ----------ram 20
SQL> exec newstu('sita','24');
PL/SQL procedure successfully completed.
SQL> select * from stu;
ST_NAME ST_AGE
---------- ----------ram 20
sita 24
PROCEDURE 2:
SQL> create or replace procedure stude2 as
3 begin4 update stu set st_age='21' where st_name='ram';
5 end;6 /
Procedure created.
SQL> exec stude;
PL/SQL procedure successfully completed.
SQL> select * from stu;
ST_NAME ST_AGE---------- ----------
ram 21
sita 24
PROCEDURE 3:
SQL> create or replace procedure n_pup2 (
3 p_age in number
4 )5 is
6 i pupil.age%type;
7 Begin8 select age
9 into i
8/3/2019 CS2258-CSE-DBMSRECORD
51/135
10 from pupil11 where age=p_age;
12 dbms_output.put_line('value age '||i||' exist');
13 Exception14 when no_data_found
15 then
16 dbms_output.put_line('value age '||i||' does not exist');
17* End;SQL>/
Procedure created.
SQL> exec n_pup(19);value age 19 exist
PL/SQL procedure successfully completed.
SQL> exec n_pup(10);
value age 10 does not exist
PL/SQL procedure successfully completed.
PROCEDURE 4:
SQL> declare
2 pi constant numeric(9,2):=3.14;
3 radius integer(5);4 area numeric(14,2);5 begin
6 for radius in 1..7 loop
7 area:=pi*power(2,radius);8 insert into ar values(area,radius);
9 end loop;
10 end;11 /
PL/SQL procedure successfully completed.
SQL> select * from ar;
AREA RADIUS---------- ----------
6.28 1
12.56 225.12 3
50.24 4
8/3/2019 CS2258-CSE-DBMSRECORD
52/135
100.48 5200.96 6
401.92 7
7 rows selected.
Result:
Thus the PL/SQL procedures has been verified and executed.
Aim:
To create PL/SQL functions for various operations.
FUNCTIONS:
1. Write a Function to display the factorial of the given number.
2. Write a function to find the sum of odd numbers.
3. Write a function to check if a value exists in the table.
FUNCTION 1:
SQL> create or replace function fact(n in number)
2 return number3 is
4 s number;
5 begin6 s:=1;
EXP:NO: PL/SQL PROGRAMS USING FUNCTIONSDATE:
8/3/2019 CS2258-CSE-DBMSRECORD
53/135
7 if n=0 then
8 return 1;
9 end if;10 for i in 1..n loop
11 s:=s*i;
12 end loop;
13 return s;14 end;
15 /
Function created.
SQL> select fact(10) from dual;
FACT(10)
------------
3628800
FUNCTION 2:
SQL> set serveroutput on
SQL> declare2 n number;3 sum1 number default 0;
4 endvalue number;
5 begin6 endvalue:=&endvalue;
7 n:=1;
8 while(n
8/3/2019 CS2258-CSE-DBMSRECORD
54/135
PL/SQL procedure successfully completed.
FUNCTION 3:
SQL> create table pupil(name varchar2(10),age number(3));
Table created.
SQL> select * from pupil; NAME AGE
---------- ---------
Sound 18Shwetha 19
SQL> create or replace function pup
2 (
3 p_age in number4 )
5 return varchar6 is
7 i pupil.age%type;8 Begin
9 select age into i
10 from pupil11 where age=p_age;
12 return 'exist';
13 Exception14 when no_data_found
15 then
16 return 'not exist';17* End;
SQL> /
Function created.
SQL> select pup(18) from dual;
PUP(18)
----------------------------------------------------------------------------------------------------
exist
SQL> select pup(20) from dual;
PUP(20)
----------------------------------------------------------------------------------------------------
not exist
8/3/2019 CS2258-CSE-DBMSRECORD
55/135
Result:
Thus the PL/SQL functions has been verified and executed.
Triggers:
A trigger is a statement that the system executes automatically.Triggers are similar to
stored procedures. A trigger stored in the database can include SQL and PL/SQL or Java
statements to run as a unit and can invoke stored procedures. However, procedures andtriggers differ in the way that they are invoked. A procedure is explicitly run by a user,
application, or trigger. Triggers are implicitly fired by Oracle when a triggering event
occurs, no matter which user is connected or which application is being used.
A database trigger has three parts
1. A triggering event
2. A trigger constraint (Optional)
3. Trigger action
A triggering event can be an insert, update, or delete statement or a instance shutdown orstartup etc. The trigger fires automatically when any of these events occur A trigger
constraint specifies a Boolean expression that must be true for the trigger to fire. This
EXP:NO: INTRODUCTION TO TRIGGERSDATE:
8/3/2019 CS2258-CSE-DBMSRECORD
56/135
condition is specified using the WHEN clause. The trigger action is a procedure thatcontains the code to be executed when the trigger fires.
Types of Triggers
The following are the different types of triggers.
Row triggers and statement triggers
A Row trigger fires once for each row affected. It uses FOR EACH ROW clause. Theyare useful if trigger action depends on number of rows affected.
Statement Trigger fires once, irrespective of number of rows affected in the table.
Statement triggers are useful when triggers action does not depend on
Before and afterTriggers
While defining the trigger we can specify whether to perform the trigger action (i.e.
execute trigger body) before or after the triggering statement. BEFORE and AFTERtriggers fired by DML statements can only be defined on tables.
BEFORE triggers The trigger action here is run before the trigger statement.
AFTER triggers The trigger action here is run after the trigger statement.
INSTEAD of Triggers provide a way of modifying views that can not be modified
directly using DML statements.
LOGON triggers fires after successful logon by the user and LOGOFF trigger fires atthe start of user logoff.
Trigger uses and limitations:
A trigger cannot include COMMIT, SAVEPOINT and ROLLBACK.
We can use only one trigger of a particular type .
A table can have any number of triggers.
We use correlation names :new and :old can be used to refer to data in command
line and data in table respectively.
Triggers on DDL statements
DDL trigger are of the following types
BEFORE CREATE OR AFTER CREATE trigger is fired when a schema object is
created.BEFORE OR AFTER ALTER trigger is fired when a schema object is altered.
BEFORE OR AFTER DROP trigger is fired when a schema object is dropped.
8/3/2019 CS2258-CSE-DBMSRECORD
57/135
A trigger can be enabled means can be made to run or it can disabled means it cannot run.
A trigger is automatically enabled when it is created. We need re-enable trigger for using
it if it is disabled. To enable or disable a trigger using ALTER TRIGGER command, youmust be owner of the trigger or should have ALTER ANY TRIGGER privilege. To
create a trigger you must have CREATE TRIGGER privilege, which is given to as part of
RESOURCE privilege at the time of user creation.
Trigger Execution
A trigger is in either of two distinct modes:
Trigger
Mode Definition
Enabled An enabled trigger runs its trigger action if a triggering statement is issued
and the trigger restriction (if any) evaluates to true.
Disabled A disabled trigger does not run its trigger action, even if a triggering
statement is issued and the trigger restriction (if any) would evaluate to true.
8/3/2019 CS2258-CSE-DBMSRECORD
58/135
Result:
Thus the introduction to triggers has been studied
.
Aim:
To Perform a study on triggers using bank database in SQL.
TRIGGERS:
1. Write a trigger to insert into Ledger_Audit table when updating amount on
Ledger table is greater than 10%.2. Write a trigger to change into uppercase when insert or update occurs on Ledger
table
3. Write a trigger to raise an error messageyou cant delete a record on loan
tablewhen amount is greater than zero.4. Write a trigger for counting the number of insertion and deletion operations
performed on account table.5. Write a trigger to raise the exception:week days-errorwhen deletion occurs on
Wednesday and Friday and to raise the exception Not a finance userwhen
deletion is done by other than finance user.
TABLES TO BE CREATED:
EXP:NO: PL/SQL PROGRAMS USING TRIGGERS
DATE:
8/3/2019 CS2258-CSE-DBMSRECORD
59/135
SQL> create table ledger(actiondate date,item varchar(25),quantity number(3),amount
number(5),upperi
tem varchar(25));
Table created.
SQL> create table led_audit(actiondate date,item varchar(25),quantity number(3),amountnumber(5));
Table created.
SQL> create table account(acc_no varchar(20),branch_name varchar(20),balance
number(5));
Table created.
SQL> create table loan(cusname varchar(20),branchname varchar(20),amount
number(4));
Table created.
SQL> create table cc(cnt number(2));
Table created.
TABLES DESCRIPTION:
SQL> desc ledger;Name Null? Type
------------------------------- -------- ----
ACTIONDATE DATEITEM VARCHAR2(25)
QUANTITY NUMBER(3)
AMOUNT NUMBER(5)UPPERITEM VARCHAR2(25)
SQL> desc led_audit;
Name Null? Type------------------------------- -------- ----
ACTIONDATE DATE
ITEM VARCHAR2(25)QUANTITY NUMBER(3)
AMOUNT NUMBER(5)
SQL> desc account;
Name Null? Type
8/3/2019 CS2258-CSE-DBMSRECORD
60/135
------------------------------- -------- ----ACC_NO VARCHAR2(20)
BRANCH_NAME VARCHAR2(20)
BALANCE NUMBER(5)
SQL> desc loan;
Name Null? Type
------------------------------- -------- ----CUSNAME VARCHAR2(20)
BRANCHNAME VARCHAR2(20)
AMOUNT NUMBER(4)
SQL> desc cc;
Name Null? Type------------------------------- -------- ----
CNT NUMBER(2)
SQL> insert into ledger values('01-aug-05','keyboard',1,200,'keyboard');
1 row created.
SQL> insert into led_audit values('01-aug-05','keyboard',1,20000);
1 row created.
TRIGGER 1:
SQL> create or replace trigger led_f before update on ledger2 for each row
3 when(new.amount/old.amount>1.0)
4 begin5 insert into led_audit values(:old.actiondate,:old.item,:old.quantity,:old.amount);
6 end;
7 /
Trigger created.
SQL> update ledger set amount=20000;
1 row updated.
SQL> select * from ledger;
ACTIONDATE ITEM QUANTITY AMOUNT UPPERITEM------------------------------------------------------------------------------------------------------
01-AUG-05 keyboard 1 20000 keyboard
8/3/2019 CS2258-CSE-DBMSRECORD
61/135
TRIGGER 2:
SQL> create or replace trigger led_t before insert or update of item on ledger2 for each row
3 begin
4 :new.upperitem:=upper(:new.item);
5 end;6 /
Trigger created.SQL> alter trigger led_t disable;
Trigger altered.
SQL> update ledger set item='yyy';
1 row updated.
SQL> select * from ledger;
ACTIONDATE ITEM QUANTITY AMOUNT UPPERITEM
--------- ------------------------- --------- --------- ------------------------------------------
01-AUG-05 yyy 1 20000 KEYBOARD
SQL> insert into account values(1,'cse',2500);
1 row created.
SQL> insert into account values(2,'it',2000);
1 row created.
SQL> select * from account;
ACC_NO BRANCH_NAME BALANCE
-------------------- -------------------- ---------1 cse 2500
2 it 2000
SQL> insert into loan values('jhon','cse',2005);
1 row created.
SQL> insert into loan values('smith','it',2000);
1 row created.
SQL> select * from loan;
8/3/2019 CS2258-CSE-DBMSRECORD
62/135
CUSNAME BRANCHNAME AMOUNT
---------------------------------------------------------------------------
jhon cse 2005smith it 2000
TRIGGER 3
SQL> create or replace trigger q before delete on loan
2 for each row
3 begin4 if:old.amount>0 then
5 raise_application_error(-20001,'deletion is not allowed');
6 end if;7 end;
8 /
Trigger created.
SQL> select * from loan;
CUSNAME BRANCHNAME AMOUNT
-------------------------------------------------------------------------
jhon cse 2005smith it 2000
SQL> delete loan where cusname='jhon';delete loan where cusname='jhon'
*
ERROR at line 1:
ORA-20001: deletion is not allowedORA-06512: at "SCOTT.Q", line 3
ORA-04088: error during execution of trigger 'SCOTT.Q'
TRIGGER 4:
SQL>create or replace trigger q
After insert or update an account
8/3/2019 CS2258-CSE-DBMSRECORD
63/135
For each rowBegin
Update cc set cnt =cnt+1;
End;/
Trigger created
SQL>delete amount where acc_no=1;1 row deleted
TRIGGER 5:
SQL> create or replace trigger header before insert or update or delete on ledger
2 for each row3 declare
4 sydate char(3);
5 begin6 sydate:=to_char(sysdate,'dy');
7 if sydate in('wed','fri')then8 raise_application_error(-20005,'noinsertion/update/delete allowed');
9 end if;10 end;
11 /
Trigger created.
SQL> delete ledger where quantity=1;delete ledger where quantity=1
*
ERROR at line 1:ORA-20001: noinsertion/updation/deletion is not allowed
ORA-06512: at "SCOTT.HEADER", line 6
ORA-04088: error during execution of trigger 'SCOTT.HEADER'
8/3/2019 CS2258-CSE-DBMSRECORD
64/135
Result:
Thus the PL/SQL programs using triggers has been executed and verified.
Cursor Management:
Oracle reserves an area in the memory for the processing of sql statements. This area is
called the context area. The context area contains information to complete the process
including the number of rows retrieved by the statement and the pointer to the parsed
rows.
Cursor:
A cursor is the context to the pointer area. A PL/SQL program can control the context
area through the cursor.
Syntax: Cursoris;
After declaring a cursor, we can use the following commands to control the cursor,
EXP:NO: INTRODUCTION TO CURSORS
DATE:
8/3/2019 CS2258-CSE-DBMSRECORD
65/135
OPEN-The open statement executes the query, identifies the active set and positions
the cursor before the first row(open).
FETCH-The fetch statement retrieves the current row and advances the cursor to the
next row to fetch the remaining rows(fetchinto).
CLOSE-After processing the last row in the active set, the cursor is disabled with the
help of close command(close).
There are 3 types of cursors. They are
1. Static cursor
2. REF cursor
3. Dynamic curso
Static Cursor:
A cursor is called static cursor if it selects statement is known at a compile time.
Static cursors can be classified intoi) Implicit cursor-select statement returns only one row
ii) Explicit cursor-if a query returns more than one row.
Implicit Cursors:
%notfound:
It evaluates to true if the DML statement doesnt return any row. Otherwise it
evaluates to false (SQL %notfound)
%found:
It evaluates to true if the DML statement affects rows, otherwise it evaluates to
false (SQL%found)
%rowcount:
Counts the number of rows returned by an SQL DML statement. Itl return zeroif the DML statement doesnt affect any row (SQL%rowcount)
Explicit Cursors:%notfound:
After opening a cursor a fetch statement is used to fetch rows from the active set,one at a time. The attribute %notfound indicates whether a fetch statement returns row
from the active set. If the fetch fails to return a row, then %notfound evaluates a true,
else, it evaluates to false.
%rowcount:
8/3/2019 CS2258-CSE-DBMSRECORD
66/135
The %rowcount is used to return the number of rows fetched. Before the firstfetch, %rowcount is zero. When the fetch statements returns a row, then the number is
incremented.
%found:
It evaluates to true if the last fetch statemenr succeeds. It would be evaluated to
false if the fetch command failed because no more rows were available.
%isopen:
If the cursor is already open, then the attributes %open
evaluates to true, else it evaluates to false.
Result:
Thus the introduction to cursors is studied.
Aim:
To create PL/SQL programs for implicit and explicit cursors.
CORSORS:
1. Declare the cursor to contain employee number, employee name and net salary.
2. Use cursor to delete e_no=3 from employee salaries.
TABLES TO BE MAINTAINED:
SQL> create table salary_c1(e_no number(4) primary key,e_name varchar2(30),desig
varchar2(25),de
pt varchar2(30),basic number(5),da number(3),ma number(5),other_allnumber(5),deducti
on number(5));
EXP:NO: PL/SQL PROGRAMS USING CURSOR
DATE:
8/3/2019 CS2258-CSE-DBMSRECORD
67/135
Table created.
TABLE DESCRIPTION:
SQL> desc salary_c1;
Name Null? Type
----------------------------------------- -------- ----------------------------
E_NO NOT NULL NUMBER(4)
E_NAME VARCHAR2(30)
DESIG VARCHAR2(25)
DEPT VARCHAR2(30)
BASIC NUMBER(5)
DA NUMBER(3)
MA NUMBER(5)
OTHER_ALL NUMBER(5)DEDUCTION NUMBER(5)
SQL> insert into salary_c1
values('1','Arun','Manager','Accounts','5000','10','200','100','1200');
1 row created.
SQL> insert into salary_c1
values('2','John','Assist_Manager','Accounts','4000','40','200','200','12
00');
1 row created.
SQL> insert into salary_c1
values('3','Harry','Manager','Accounts','2000','43','100','50','200');
1 row created.
SQL> insert into salary_c1 values('4','Ron','Architect','Sales','5000','20','100','200','300');
1 row created.
CURSOR 1:
SQL> ed cur;
8/3/2019 CS2258-CSE-DBMSRECORD
68/135
declare
e_no number(5);
e_name varchar2(25);
net_salary number(10);
cursor cur_salary is select
e_no,e_name,basic+da*basic/100+ma+other_all-deduction from
salary_c1;
begin
dbms_output.put_line('e_no' ||' Name '|| 'Netsalary');
dbms_output.put_line('---------------------------------------------------');
open cur_salary;
loop
fetch cur_salary into e_no,e_name,net_salary;
exit when cur_salary%notfound;
dbms_output.put_line(rpad(e_no,10,' ')||rpad(e_name,30,' ')||net_salary);end loop;
close cur_salary;
end;
SQL> @ cur;
19 /
e_no Name Netsalary
---------------------------------------------------
1 Arun 4600
2 John 4800
3 Harry 2810
4 Ron 6000
PL/SQL procedure successfully completed.
CURSOR 2:
SQL> ed cur2;
begin
delete from salary_c1 where e_no=3;
if SQL % notfound thendbms_output.put_line('RECORDS ALREADY DELETED');
else
8/3/2019 CS2258-CSE-DBMSRECORD
69/135
dbms_output.put_line('RECORDS ARE DELETED NOW SUCCESSFULLY');end if;
end;
SQL> @cur2;
9 /
RECORDS ARE DELETED NOW SUCCESSFULLY
PL/SQL procedure successfully completed.
SQL> select * from salary_c1;
E_NO E_NAME DESIG DEPT BASIC DA MA OTHER_ALL DEDUCTION
-----------------------------------------------------------------------------------------------------------------------------------------------
1. Arun Manager Accounts 5000 10 200 100 1200
2. John Manager Accounts 4000 40 200 200 12004. Ron Architect Sales 5000 20 100 200 3000
8/3/2019 CS2258-CSE-DBMSRECORD
70/135
Result:
Thus the PL/SQL programs using cursors has been verified and executed.
Visual Basic (VB) is a programming environment from Microsoft in which a
programmer uses a graphical user interface (GUI) to choose and modify preselectedsections of code written in the BASIC programming language. Visual Basic is a
programming language/tool to develop stand alone applications.
A version of the BASIC programming language from Microsoft specialized for
developing Windows applications. When first released in 1991, it was similar toMicrosoft's QuickBASIC. With its visual user interface development tools, Visual Basic
became very popular by the mid-1990s. Visual Basic 6.0, which was released in early
1999, was the last version of Visual Basic to be offered as a stand-alone development
product. Visual Basic became part of Visual Studio.NET.
Visual Basic for Applications (VBA) is a subset that provides a common macro language
included with many Microsoft applications.
Up until VB 5, the Visual Basic compiler only converted the source code written by the
EXP:NO: INTRODUCTION TO VISUAL BASICDATE:
http://searchwindevelopment.techtarget.com/sDefinition/0,,sid8_gci213989,00.htmlhttp://whatis.techtarget.com/definition/0,,sid9_gci213805,00.htmlhttp://searchwindevelopment.techtarget.com/sDefinition/0,,sid8_gci213989,00.htmlhttp://whatis.techtarget.com/definition/0,,sid9_gci213805,00.html8/3/2019 CS2258-CSE-DBMSRECORD
71/135
programmer into an intermediate language called "bytecode." Starting with VB 5, nativeexecutable programs can be generated.
Creating the Project
First thing to do is to create a Directory where you will store all your VB Projects. Call it
VBApps, for example. Then start VB. The first screen will ask whether you want to open
a new project or an existing one - it's obviously a new one and it will be a Standard EXE.
Then, maximize all the windows Now, save your project. It will first ask you to save theform - call it Score.frm - and then the Project - call it Scorebrd.vbp. From now on, do
File-->Save Project very, very frequently.
Form1 Structure:
To set background color to form1:
8/3/2019 CS2258-CSE-DBMSRECORD
72/135
Select different font styles using font property:
8/3/2019 CS2258-CSE-DBMSRECORD
73/135
Set Background image to form1:
8/3/2019 CS2258-CSE-DBMSRECORD
74/135
Opening an existing Visual Basic project.
Running and viewing the project in detail.
Once an application is loaded it can be run by click on the icon from the toolbar, to
pause press and to terminate use .Once a project is loaded, the name of the form(s) that it contains is displayed in the
project window. To view a form in design mode, select the form required by clicking
with the mouse to highlight its name, then clicking on the view form button.
The Default Layout
When we start Visual Basic, we are provided with a VB project.A VB project is acollection of the following modules and files.
The global module( thatcontains declaration and procedures)
The form module(that contains the graphic elements of the VB application alongwith theinstruction)
Thegeneral module (that generally contains general-purpose instructions not
pertaining to anything graphic on-screen)
Theclass module(that contains the defining characteristics of a class, including
its properties and methods)
Theresource files(that allows you to collect all of the texts and bitmaps for anapplication in one place)
On start up, Visual Basic will displays the following windows :
The Blank Form window The Project window
The Properties window
It also includes a Toolbox that consists of all the controls essential for developing a VBApplication. Controls are tools such as boxes, buttons, labels and other objects draw on a
form to get input ordisplay output.
8/3/2019 CS2258-CSE-DBMSRECORD
75/135
Understanding the tool box.
Button Properties for reference
, Command Button & labels properties
Property Description
Name The name of the object so you can call it at runtime
BackColor
This specifies the command button's background color. Click the
BackColor's palette down arrow to see a list of common Windows control
colours, you must change this to the style property from 0 - standard to 1 graphical
CancelDetermines whether the command button gets a Click event if the user
presses escape
Caption Holds the text that appears on the command button.
DefaultDetermins if the command button responds to an enter keypress even if
another control has the focus
EnableDetermines whether the command button is active. Often, you'll change the
enable property at runtime with code to prevent the user pressing the button
FontProduces a Font dialog box in which you can set the caption's font name ,
style and size.
Height Positions the height of the object can be used for down
Left Positions the left control - can be used for right
MousePointerIf selected to an icon can change the picture of the mouse pointer over that
object
Picture Hold's the name of an icon graphic image so that it appears as a picture
8/3/2019 CS2258-CSE-DBMSRECORD
76/135
instead of a Button for this option to work the graphical tag must be set to 1
StyleThis determins if the Command Button appears as a standard windowsdialog box or a graphical image
Tab index Specifies the order of the command button in tab order
Tab StopWhether the object can be tabbed to ( this can be used in labels which have
no other function )
Tool Tip TextIf the mouse is held over the object a brief description can be displayed (forexample hold your mouse over one of the above pictures to see this
happening
VisibleIf you want the user to see the button/label select true other wise just press
false
Width Show the width of the object
Handling some of the common controls
The Text Box
The text box is the standard control for accepting input from the user as well as to display
the output. It can handle string (text) and numeric data but not images or pictures. String
in a text box can be converted to a numeric data by using the function Val(text)..
The Label
The label is a very useful control for Visual Basic, as it is not only used to provide
instructions and guides to the users, it can also be used to display outputs. One of its most
important properties is Caption. Using the syntax label.Caption, it can display text and
numeric data . You can change its caption in the properties window and also at runtime.
The Command Button
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.
8/3/2019 CS2258-CSE-DBMSRECORD
77/135
The Picture Box
The Picture Box is one of the controls that is used to handle graphics. You can load a
picture at design phase by clicking on the picture item in the properties window and
select the picture from the selected folder. You can also load the picture at runtime using
the LoadPicture method. For example, the statement will load the picture grape.gif into
the picture box.
Picture1.Picture=LoadPicture ("C:\VB program\Images\grape.gif")
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 anImage 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 List Box
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
Private Sub Form_Load ( )
List1.AddItem Lesson1
List1.AddItem Lesson2
List1.AddItem Lesson3List1.AddItem Lesson4
End Sub
The Combo Box
8/3/2019 CS2258-CSE-DBMSRECORD
78/135
The function of the Combo Box is also to present a list of items where the user can click
and select the items from the list. However, the user needs to click on the small
arrowhead on the right of the combo box to see the items which are presented in a drop-
down list. In order to add items to the list, you can also use the AddItem method. For
example, if you wish to add a number of items to Combo box 1, you can key in the
following statements
Example
Private Sub Form_Load ( )
Combo1.AddItem Item1
Combo1.AddItem Item2
Combo1.AddItem Item3Combo1.AddItem Item4
End Sub
The Check Box
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.
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
8/3/2019 CS2258-CSE-DBMSRECORD
79/135
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.
The Drive List Box
The Drive ListBox is for displaying a list of drives available in your computer. When youplace this control into the form and run the program, you will be able to select different
drives from your computer as shown in Figure 3.3
Figure The Drive List Box
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 3.4
The File List Box
8/3/2019 CS2258-CSE-DBMSRECORD
80/135
The File List Box is for displaying the list of files in a selected directory or folder. When
you place this control into the form and run the program, you will be able to shown the
list of files in a selected directory .
Visual Basic Data Types
Visual Basic classifies the information mentioned above into two major data types, theyare the numeric data types and the non-numeric data types.
Numeric Data Types
Numeric data types are types of data that consist of numbers, which can be computed
mathematically with various standard operators such as add, minus, multiply, divide and
more. Examples of numeric data types are examination marks, height, weight, the number
of students in a class, share values, price of goods, monthly bills, fees and others. In
Visual Basic, numeric data are divided into 7 types, depending on the range of values
they can store. Calculations that only involve round figures or data that does not need
precision can use Integer or Long integer in the computation. Programs that require high
precision calculation need to use Single and Double decision data types, they are also
called floating point numbers. For currency calculation , you can use the currency data
typ