You are on page 1of 135

Sl. No.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Date
07-12-09 07-12-09 14-12-09 14-12-09 19-12-09 19-12-09 28-12-09 04-01-10 25-01-10 25-01-10 08-02-10 08-02-10 08-02-10 20-02-10 20-0210

Title
Introduction to Oracle-RDBMS Introduction to SQL Data Definition Language Commands Data Manipulation Language commands Constraints Transaction Control Language Commands Nested Queries Join Queries Set operators and simple Operators Views Introduction to Procedures and Functions PL/SQL Programs using Procedures PL/SQL Programs using Functions Introduction to Triggers PL/SQL Programs using Triggers

Page No.

Signature

16 17 18 19 20 21 22 23 24 25

26-02-0-10 26-02-10 01-03-10 01-03-10 12-03-10 12-03-10 12-03-10 22-03-10 22-03-10 22-03-10

Introduction to Cursors PL/SQL Programs using Cursors Introduction to Visual Basic Forms Introduction to Menu Design and Reports Reports Menu Design Database Design and Implementation of Library Management System Database Design and Implementation of Online Banking System Database Design and Implementation of Employee Payroll System

EXP:NO: DATE:

INTRODUCTION TO ORACLE-RDBMS

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 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 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 SQL statement 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 Customize output with functions embedded in the SELECT statement

What is the basic difference between RDBMS and DBMS?


RDBMS - Relational Database Management System - Multiple users can access and there will be relationships between the tables, security is increased DBMS - 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 relationship between 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 better understanding 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 the same 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 use to implement your application can significantly affect the performance of your application. 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. 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 and supports 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 databases and on-line transaction processing systems A Recovery Manager utility to complement Enterprise Manager Ad hoc enhancements such as password management and index only tables Object support within the database and object extensions to SQL and PL/SQL Support for the network computing architecture

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 the most 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 scalability security 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 the quality of service by making the database easier to deploy and manage including enhancements to backup and recovery and data warehousing .

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 this is 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 disks and 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 load dynamically. 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, the surviving 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 only those blocks changed since the last backup - thereby enabling faster recovery from media failure; data guard (standby database) has been enhanced to enable compression and encryption of 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 reduce planned 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 millions of 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 allocated automatically 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 query results to be treated as sets of multi-dimensional arrays on which complex interdependent 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 zero latency trickle feeds that combined with integrated extraction, transformation and loading (etl) enable real-time warehousing.

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 applications Oracle 11g databases, including: Designing a database with a data model Navigating the dictionary with Enterprise Manager Coding with SQL Developer and SQL*Plus Retrieving and manipulating data with SQL constructs Creating tables, sequences, views and synonyms Managing security, integrity and performance Programming with cursors, loops and control logic Debugging PL/SQL programs Building procedures, packages and triggers Summary As with Oracle 9i, Oracle 10g has many enhancements to support the largest customers in terms 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 and IBM. 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 has three aspects: Structures Operations Integrity rules Structures consist of a collection of objects or relations that store data. An example of relation 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 using operations. You must adhere to a predefined set of integrity rules. Integrity rules are laws that govern the operations allowed on data in a database. This ensures data accuracy and consistency.

Relational database components include: Table Row Column Field Primary key Foreign key

A Table is a basic storage structure of an RDBMS and consists of columns and rows. A table represents an entity. For example, the S_DEPT table stores information about the departments of an organization. A Row is 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 specifies the names of the departments in the organization. Field is 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.

Figure 1-2. Table, Row, Column & Field A Primary 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 the S_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, or within, 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 key and a matching foreign key. This relational method of linking provides great flexibility as it is independent of physical links between records.

RDBMS Properties

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 columns used 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 the specific rows returned by a query. Database Resource Manager Traditionally, operating systems regulated resource management among various applications, 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 how long, 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.

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 business rules. 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)

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 of contention 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 just going 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 block contention 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 medium size then you can bring a number of rows in a single I/O.

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 cache when doing random access. 3)Large Block(16KB-32KB): If you use larger block then relatively less overhead. Per I/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 leaf blocks.

RESULT: Thus the introduction to ORACLE-RDBMS has been studied.

EXP:NO: DATE:

INTRODUCTION TO ORACLE-SQL

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 Data Banks", 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 English Query 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 available implementation 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 names of 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")

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 programs written 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 the Oracle 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 interpret embedded SQL statements and translate them into statements that can be understood by procedural language compilers. . Using SQL *Plus to communicate with Oracle Databases

SQL*Plus is an interactive and batch query tool that is installed with every Oracle Server or Client installation. It has a command-line user interface, and more recently, a webbased user INTERFACE called SQL*PLUS. On Windows platforms, context menu options accessed through the right mouse button enable 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 results 4. interact with an end user 5. startup and shutdown a database 6. connect to a database 7. define variables 8. capture errors 9. list column definitions for any table 10. perform database administration

Result:

Thus the introduction to ORACLE-SQL has been studied.

EXP:NO: DATE:

DATA DEFINITION LANGUAGE COMMANDS

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)

(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

EXP:NO: DATE:

DATA MANIPULATION LANGUAGE COMMANDS

SQL> create table customer(cname char(10) constraint c1 primary key,cstreet char(15),ccity char(10)); Table created. SQL> desc customer; Name ----------------------------CNAME CSTREET CCITY Null? Type -------------------------------------NOT NULL CHAR(10) CHAR(15) CHAR(10)

SQL> insert into customer values('&cname','&cstreet','&ccity'); Enter value for cname: Raj Enter value for cstreet: STG street Enter 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: Kolkatta old 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.

SQL> / Enter value for cname: Rajan Enter value for cstreet: SSR street Enter value for ccity: Chennai old 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 ---------- --------------Raj STG street Ram KK street Kumar VSV street Rajan SSR street 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 Chennai Ram KK street Madurai Kumar VSV street Mumbai Rajan SSR street Chennai SQL> delete from customer where ccity='Chennai'; 2 rows deleted. SQL> select * from customer; CNAME CSTREET CCITY ---------- -----------------------Ram KK street Madurai Kumar VSV street Mumbai CCITY ---------Chennai Kolkatta Mumbai Chennai

EXP:NO: DATE:

CONSTRAINTS

1. Table Creations 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('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 Mumbai Rajan 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)

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 Chennai STG Mumbai RRJ Saidapet BSS 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

1001 1002 1003

BSS STG RRJ

45210 100000 55410

SQL> create table depositor(dname char(15) constraint c4 references customer(cname),accno number(10) constraint c5 references account(acno)); Table created. SQL> desc depositor; Name Null? Type ----------------------------------------- -------- ---------------------------DNAME CHAR(15) ACCNO NUMBER(10)

EXP:NO: DATE:

TRANSACTION CONTROL LANGUAGE COMMANDS

TCL COMMAND OUTPUT:


SQL> create table tab(name char(10), lno number(10)); Table created. SQL> desc tab; Name ----------------------------NAME LNO Null? Type -------------------- ---------------------------VARCHAR2(10) 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 ---------Raj Kumar Babu Ragu LNO ---------1000 1001 1002 1003

SQL> rollback to s; Rollback complete.

SQL> select * from tab; NAME ---------Raj Kumar LNO ---------1000 1001

EXP:NO: DATE:

NESTED QUERIES

NESTED QUERIES
CREATING TABLES: SQL> create table acc1(accno number(10), br_name varchar2(10), balance number(10)); Table created. SQL> desc acc1; Name --------------------ACCNO BR_NAME BALANCE Null? ---------Type ---------------------NUMBER(10) VARCHAR2(10) NUMBER(10) BALANCE ---------------50000 70000 80000 45000

SQL> select * from acc1; ACCNO BR_NAME -----------------------1231 Mumbai 1232 Delhi 1233 Jaipur 1234 Hyderabad

SQL> create table acc12(accno number(10), br_name varchar2(10), balance number(10)); Table created. SQL> desc acc12; Name --------------------ACCNO BR_NAME BALANCE Null? ---------Type ---------------------NUMBER(10) VARCHAR2(10) NUMBER(10)

SQL> select * from acc12; ACCNO BR_NAME -------------------------

BALANCE ----------------

1235 1236

Chennai Mysore

34000 47000

TO CREATE A TABLE USING NESTED QUERY: SQL> create table acc72 as select * from acc1; Table created. SQL> select * from acc72; ACCNO ---------1231 1232 1233 1234 BR_NAME ---------Mumbai Delhi Jaipur Hyderabad BALANCE ---------50000 70000 80000 45000

TO INSERT TUPLE USING NESTED QUERY: SQL> insert into acc72 select * from acc12; 2 rows created. SQL> select * from acc72; ACCNO ---------1231 1232 1233 1234 1235 1236 BR_NAME --------------Mumbai Delhi Jaipur Hyderabad Chennai Mysore BALANCE --------------50000 70000 80000 45000 34000 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.

SQL> select * from acc72; ACCNO ---------1231 1232 1233 1235 1236 BR_NAME -------------Mumbai Delhi Jaipur Chennai Mysore BALANCE --------------50000 70000 80000 34000 47000

TO UPDATE A TUPLE USING NESTED QUERY: SQL> update acc72 set balance=75000 where br_name= (select br_name from acc1 where accno =1231); 1 row updated. SQL> select * from acc72; ACCNO BR_NAME ------------------------1231 Mumbai 1232 Delhi 1233 Jaipur 1235 Chennai 1236 Mysore BALANCE --------------75000 70000 80000 34000 47000

TO SELECT A TUPLE USING NESTED QUERY: SQL> select * from acc72 where accno= 2 (select accno from acc12 where balance=34000); ACCNO ---------1235 BR_NAME ---------------Chennai BALANCE ---------------34000

1 row selected.

EXP:NO: DATE:

JOIN QUERIES

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? ----------------------- -------------NAME ID CABIN Type ------------------------CHAR(10) NUMBER(10) 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 2 Rajiv 76 3 Prakash 72 6 Rahul 96 96 SQL> select emplo.name,emplo.id,emplo.cabin from emplo where emplo.id=emplo.cabin;

NAME ---------Rahul

ID CABIN ---------- ---------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 Pass Prakash 72 Pass SQL> create table stud2(name char(10),Rno number(10),status char(10)); Table created. SQL>desc stud2; Name Null? -------------------- ------------NAME RNO STATUS Type -----------------CHAR(10) NUMBER(10) CHAR(10)

SQL> insert into stud2 values('Rajiv',76,'Pass'); 1 row created.

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 Fail Gopi 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.status<>stud2.status; NAME NAME ---------- ---------Selva Priya Raj 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 Ram Prakash 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

Priya

EXP:NO: DATE:

SET OPERATORS AND SIMPLE OPERATORS

SET OPERATION
SQL> create table stud2(s_rollno number(10), name varchar2(15), mark number(10)); Table created. SQL> desc stud2; Name Null? --------------------------------------- -------S_ROLLNO NOT NULL NAME MARK SQL> select * from stud2; S_ROLLNO NAME --------------------------21308104 Prakash 21308105 Rajiv 21308106 Rahul 21308107 Selva 21308108 Vinoth MARK ---------89 90 78 78 98 Type ---------------------------NUMBER(10) VARCHAR2(15) NUMBER(10)

SQL> create table stud3(s_rollno number(10), name varchar2(15), mark number(10)); Table created. SQL> desc stud3; Name Null? --------------------------------------- -------S_ROLLNO NOT NULL NAME MARK SQL> select * from stud3; S_ROLLNO NAME MARK Type ---------------------------NUMBER(10) VARCHAR2(15) NUMBER(10)

---------21308106 21308107 21308108 21308109 21308110 UNION

---------Rahul Selva Vinoth Vipin Tharachand

---------78 78 99 56 89

SQL> select name from stud2 union select name from stud3; NAME ---------Prakash Rahul Rajiv Selva Tharachand Vipin Vinoth 7 rows selected. SQL> select name, s_rollno from stud2 union select name, s_rollno from stud3; NAME S_ROLLNO ------------------Prakash 21308104 Rahul 21308106 Rajiv 21308105 Selva 21308107 Tharachand 21308110 Vipin 21308109 Vinoth 21308108 7 rows selected. UNION ALL SQL> select name from stud2 union all select name from stud3; NAME ---------Prakash Rajiv Rahul Selva Vinoth Rahul Selva Vinoth

Vipin Tharachand 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 21308106 Selva 21308107 Vinoth 21308108 Rahul 21308106 Selva 21308107 Vinoth 21308108 Vipin 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 21308106 Selva 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

SIMPLE OPERATIONS
ARITHMETIC OPERATION SQL> select s_rollno, name, mark+10 from stud2; S_ROLLNO NAME MARK+10 --------------- ------------ --------------21308104 Prakash 99 21308105 Rajiv 100 21308106 Rahul 88 21308107 Selva 88 21308108 Vinoth 108 RENAME OPERATION SQL> select mark+10 "New mark" from stud3; New mark ---------88 88 109 66 99 COMPARISON OPERATON SQL> select * from stud2 where mark>80; S_ROLLNO NAME MARK -------------------- ---------------- -----------------21308104 Prakash 89 21308105 Rajiv 90 21308108 Vinoth 98 LOGICAL OPERATION SQL> select * from stud2 where mark>80 and mark<=90; S_ROLLNO NAME MARK -------------------- ------------------ -----------------21308104 Prakash 89 21308105 Rajiv 90 BETWEEN OPERATON

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 99 21308109 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 78 21308108 Vinoth 98 ORDERING OPERATION SQL> select * from stud3 order by name desc; S_ROLLNO NAME MARK ----------------------------

21308108 21308109 21308110 21308107 21308106

Vinoth Vipin Tharachand Selva Rahul

99 56 89 78 78

SQL> select * from stud3 order by name asc; S_ROLLNO NAME MARK ---------------------------21308106 Rahul 78 21308107 Selva 78 21308110 Tharachand 89 21308109 Vipin 56 21308108 Vinoth 99 DISTINCT OPERATION SQL> select distinct mark from stud2; MARK ---------78 89 90 98 SQL> select distinct mark from stud3; MARK ---------56 78 89 99 .

EXP:NO: DATE:

VIEWS

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;

NAME ---------Rajiv Praksh STG Rahul Vipin Vinoth

STREET ------------abc st bcd st rama st . sss st keral st rama st

AGE ---------78 18 16 19 21 18

6 rows selected.

SQL> create table customer (c_name varchar2(10),c_street varchar2(10), c_city varchar2(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 Chennai Rahul bengal st Avadi Vipin raja st Kerala 4 rows selected. SQL> create view v1 as select customer.c_name,customer.c_city,cust.age from customer,cust where customer.c_name=cust.name; View created.

SQL> desc v1; Name ---------------------------C_NAME C_CITY AGE

Null? Type --------------- ---------------------------NOT NULL VARCHAR2(10) VARCHAR2(10) NUMBER(10)

SQL> select * from v1; C_NAME C_CITY ------------- ---------Rahul Avadi Vipin Kerala

AGE ---------19 21

GROUP BY VIEW:
SQL> create view v2 as select age from cust group by age; View created. SQL> desc v2; Name Null? --------------------------------- -------AGE SQL> select * from v2; AGE ---------16 18 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) Type ---------------------------NUMBER(10)

SQL> select * from v3; NAME STREET ---------- --------------Praksh bcd st Vinoth rama st

AGE ---------18 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

EXP:NO: DATE:

INTRODUTION TO PROCEDURES AND FUNCTIONS

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 declarative part, 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 written in exception part. When client executes a procedure are function, the processing is done in the server. This reduces 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 needed for 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 two parts 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 or AS and ends with keyword END.

In the above given syntax things enclosed in between angular brackets (&lt; &gt; ) 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 modes to 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.

Functions: A function is a PL/SQL subprogram, which is used to compute a value. Function is same like a procedure except for the difference that it have RETURN clause. Syntax for Function

Examples Function without arguments

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;

Show errors function functionname;

Result: Thus the introduction to procedure and functions has been studied.

EXP:NO: DATE:

PL/SQL PROGRAMS USING PROCEDURES

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.

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)as 2 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

---------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 stude 2 as 3 begin 4 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_pup 2 ( 3 p_age in number 4 ) 5 is 6 i pupil.age%type; 7 Begin 8 select age 9 into i

10 from pupil 11 where age=p_age; 12 dbms_output.put_line('value age '||i||' exist'); 13 Exception 14 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 2 25.12 3 50.24 4

100.48 200.96 401.92

5 6 7

7 rows selected.

Result: Thus the PL/SQL procedures has been verified and executed.

EXP:NO: DATE:

PL/SQL PROGRAMS USING FUNCTIONS

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 number 3 is 4 s number; 5 begin 6 s:=1;

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> declare 2 n number; 3 sum1 number default 0; 4 endvalue number; 5 begin 6 endvalue:=&endvalue; 7 n:=1; 8 while(n<endvalue) 9 loop 10 sum1:=sum1+n; 11 n:=n+2; 12 end loop; 13 dbms_output.put_line('sum of odd numbers between 1 and '||endvalue|| ' is '|| sum1); 14 end; 15 / Enter value for endvalue: 20 old 6: endvalue:=&endvalue; new 6: endvalue:=20; sum of odd numbers between 1 and 20 is 100

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 18 Shwetha 19 SQL> create or replace function pup 2 ( 3 p_age in number 4 ) 5 return varchar 6 is 7 i pupil.age%type; 8 Begin 9 select age into i 10 from pupil 11 where age=p_age; 12 return 'exist'; 13 Exception 14 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

Result: Thus the PL/SQL functions has been verified and executed.

EXP:NO: DATE: Triggers:

INTRODUCTION TO 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 and triggers 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 or startup 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

condition is specified using the WHEN clause. The trigger action is a procedure that contains 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. They are 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 AFTER triggers 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 at the 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.

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, you must 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 Enabled Disabled Definition An enabled trigger runs its trigger action if a triggering statement is issued and the trigger restriction (if any) evaluates to true. 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.

Result: Thus the introduction to triggers has been studied

EXP:NO: DATE: . Aim:

PL/SQL PROGRAMS USING TRIGGERS

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:

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),amount number(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 DATE ITEM 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

------------------------------- -------- ---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 ledger 2 for each row 3 when(new.amount/old.amount>1.0) 4 begin 5 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

TRIGGER 2: SQL> create or replace trigger led_t before insert or update of item on ledger 2 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 -------------------- -------------------- --------1 cse 2500 2 it 2000 BALANCE

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;

CUSNAME BRANCHNAME AMOUNT --------------------------------------------------------------------------jhon cse 2005 smith it 2000

TRIGGER 3 SQL> create or replace trigger q before delete on loan 2 for each row 3 begin 4 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 2005 smith it 2000 SQL> delete loan where cusname='jhon'; delete loan where cusname='jhon' * ERROR at line 1: ORA-20001: deletion is not allowed ORA-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

For each row Begin 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 row 3 declare 4 sydate char(3); 5 begin 6 sydate:=to_char(sysdate,'dy'); 7 if sydate in('wed','fri')then 8 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'

Result: Thus the PL/SQL programs using triggers has been executed and verified.

EXP:NO: DATE:

INTRODUCTION TO CURSORS

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: Cursor<cursor_name>is<select statement>; After declaring a cursor, we can use the following commands to control the cursor,

OPEN-The open statement executes the query, identifies the active set and positions the cursor before the first row(open<cursor_name>). FETCH-The fetch statement retrieves the current row and advances the cursor to the next row to fetch the remaining rows(fetch<cursor_name>into<column_name>). CLOSE-After processing the last row in the active set, the cursor is disabled with the help of close command(close<cursor_name>). 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 into i) 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 zero if 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:

The %rowcount is used to return the number of rows fetched. Before the first fetch, %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.

EXP:NO: DATE:

PL/SQL PROGRAMS USING CURSOR

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_all number(5),deducti on number(5));

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 values('1','Arun','Manager','Accounts','5000','10','200','100','1200'); 1 row created. SQL> insert into values('2','John','Assist_Manager','Accounts','4000','40','200','200','12 00'); 1 row created. SQL> insert into values('3','Harry','Manager','Accounts','2000','43','100','50','200'); 1 row created.

salary_c1

salary_c1

salary_c1

SQL> insert into salary_c1 values('4','Ron','Architect','Sales','5000','20','100','200','300'); 1 row created.

CURSOR 1: SQL> ed cur;

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 then dbms_output.put_line('RECORDS ALREADY DELETED'); else

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. 2. 4. Arun John Ron Manager Manager Architect Accounts 5000 Accounts 4000 Sales 5000 10 40 20 200 200 100 100 200 200 1200 1200 3000

Result: Thus the PL/SQL programs using cursors has been verified and executed.

EXP:NO: DATE:

INTRODUCTION TO VISUAL BASIC

Visual Basic (VB) is a programming environment from Microsoft in which a programmer uses a graphical user interface (GUI) to choose and modify preselected sections 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 to Microsoft'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

programmer into an intermediate language called "bytecode." Starting with VB 5, native executable 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 the form - 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:

Select different font styles using font property:

Set Background image to form1:

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 a collection of the following modules and files.

The global module( that contains declaration and procedures) The form module(that contains the graphic elements of the VB application along with the instruction ) The general module (that generally contains general-purpose instructions not pertaining to anything graphic on-screen) The class module(that contains the defining characteristics of a class, including its properties and methods) The resource files(that allows you to collect all of the texts and bitmaps for an application 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 VB Application. Controls are tools such as boxes, buttons, labels and other objects draw on a form to get input or display output.

Understanding the tool box.

Button Properties for reference , Command Button & labels properties Property Name Description The name of the object so you can call it at runtime This specifies the command button's background color. Click the BackColor's palette down arrow to see a list of common Windows control BackColor colours, you must change this to the style property from 0 - standard to 1 graphical Determines whether the command button gets a Click event if the user Cancel presses escape Caption Holds the text that appears on the command button. Determins if the command button responds to an enter keypress even if Default another control has the focus Determines whether the command button is active. Often, you'll change the Enable enable property at runtime with code to prevent the user pressing the button Produces a Font dialog box in which you can set the caption's font name , Font 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 If selected to an icon can change the picture of the mouse pointer over that MousePointer object Picture Hold's the name of an icon graphic image so that it appears as a picture

instead of a Button for this option to work the graphical tag must be set to 1 This determins if the Command Button appears as a standard windows Style dialog box or a graphical image Tab index Specifies the order of the command button in tab order Whether the object can be tabbed to ( this can be used in labels which have Tab Stop no other function ) If the mouse is held over the object a brief description can be displayed (for Tool Tip Text example hold your mouse over one of the above pictures to see this happening If you want the user to see the button/label select true other wise just press Visible 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.

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 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 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 Lesson3 List1.AddItem Lesson4 End Sub The Combo Box

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 dropdown 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 Item3 Combo1.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

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

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, they are 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 types. Lastly, if even more precision is required to perform calculations that involve a many decimal points, we can use the decimal data types. These data types summarized. Type Storage Byte 1 byte Integer 2 bytes Long 4 bytes Single Double Currency Decimal Range of Values 0 to 255 -32,768 to 32,767 -2,147,483,648 to 2,147,483,648 -3.402823E+38 to -1.401298E-45 for negative values 4 bytes 1.401298E-45 to 3.402823E+38 for positive values. -1.79769313486232e+308 to -4.94065645841247E-324 for negative values 8 bytes 4.94065645841247E-324 to 1.79769313486232e+308 for positive values. 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 12 bytes use +/- 7.9228162514264337593543950335 (28 decimal places).

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. Data Type String(fixed length) String(variable length) Date Boolean Object Variant(numeric) Variant(text) Managing Variables 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. Variable Names The following are the rules when naming the variables in Visual Basic

Storage Length of string Length + 10 bytes 8 bytes 2 bytes 4 bytes 16 bytes Length+22 bytes

Range 1 to 65,400 characters 0 to 2 billion characters January 1, 100 to December 31, 9999 True or False Any embedded object Any value as large as Double Same as variable-length string

It must be less than 255 characters No spacing is allowed It must not begin with a number Period is not permitted

Declaring Variables 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 Constants Constants are different from variables in the sense that their values do not change during the running of the program.

Declaring a Constant

The format to declare a constant is Const Constant Name As Data Type = Value Arithmetic Operators Operator Mathematical function ^ Exponential * / Multiplication Division Modulus(return the Mod remainder from an integer division) Integer \ Division(discards the decimal places) + or & String concatenation "Visual"&"Basic"="Visual Basic" 19\4=4 15 Mod 4=3 255 mod 10=5 Example 2^4=16 4*3=12, (5*6))2=60 12/4=3

Conditional Operators Table 7.1: Conditional Operators Meaning Equal to More than Less Than More than and equal Less than and equal Not Equal to

Operator = > < >= <= <>

Logical Operators Operator And or Xor Meaning Both sides must be true One side or other must be true One side or other must be true but not both

Not

Negates truth

Using If.....Then.....Else Statements with Operators The general format for the if...then...else statement is If conditions Then VB expressions Else VB expressions End If CASE CONTROL: The format of the Select Case control structure is show below: Select Case expression Case value1 Block of one or more VB statements Case value2 Block of one or more VB Statements Case value3 . . Case Else Block of one or more VB Statements End Select MsgBox ( ) Function The objective of MsgBox is to produce a pop-up message box and prompt the user to click on a command button before he /she can continues. This format is as follows: yourMsg=MsgBox(Prompt, Style Value, Title) The first argument, Prompt, will display the message in the message box. The Style Value will determine what type of command buttons appear on the message box, please refer Table 10.1 for types of command button displayed. The Title argument will display the title of the message board. Style Values Style Value Named Constant Buttons Displayed 0 vbOkOnly Ok button

1 2 3 4 5

vbOkCancel vbAbortRetryIgnore vbYesNoCancel vbYesNo vbRetryCancel

Ok and Cancel buttons Abort, Retry and Ignore buttons. Yes, No and Cancel buttons Yes and No buttons Retry and cancel buttons Icon

Value 1 2 3 4

Named Constant vbCritical vbQuestion vbExclamation vbInformation

Result: Thus the introduction to Visual Basic has been studied.

EXP:NO: DATE: Aim:

FORMS

To design a simple form in Visual Basic using Oracle as backend. Algorithm for creating table:

SQL> create table vb1(Name varchar2(20),Rollno number(3),Maths number(3),English number(3),Physics number(3),Chemistry number(3)); Table created. SQL> desc vb1; Name Null? Type ----------------------------------------- -------- ---------------------------NAME VARCHAR2(20) ROLLNO NUMBER(3) MATHS NUMBER(3) ENGLISH NUMBER(3) PHYSICS NUMBER(3) CHEMISTRY NUMBER(3) 2. Insert all the possible values into the vb1 table. 3. Enter commit command. Algorithm for ADO Connection: After creating the table in Oracle, Go to start menu 1. Start------> Settings------> Control Panel ------>Administrative Tools------> Data Sources (ODBC) ------>User DSN------>Add------> Select Microsoft ODBC for Oracle------>Finish------>OK 2. One new window will be appeared. In that window type Data Source Name as table name created in Oracle. Type user name as Scott. Then click O.K. Algorithm for ADODC in Visual Basic: 1. In Visual Basic create the labels, command buttons and their text boxes. 2. In Visual Basic go to Project menu, 3. Project---->Components---->Microsoft ADO Data Control 6.0 for OLEDB->O.K 4. Now ADODC Data Control available in toolbox. 5. Drag and drop the ADODC Data Control into the form. 6. Right click in ADODC Data Control then click the ADODC properties. 7. One New window will be appeared. 8. Choose general tab select ODBC Data source name as the table created in Oracle. 9. Choose authentication tab and select username, password as scott and tiger. 10. Choose record source------>select Command type as adcmdTable. 11. Select Table or Stored procedure name as table created in Oracle. 12. Click Apply------>O.K 13. Set the properties of each text box.

14. Select the data source as ADODC1 15. Select the Data field and set the required field name created in table Coding 1.ADD Private Sub ADD_Click() Text1.SetFocus Adodc1.Recordset.AddNew End Sub 2.DELETE Private Sub DELETE_Click() If MsgBox("DELETE IT?", vbOKCancel) = vbOK Then Adodc1.Recordset.DELETE MsgBox "One row deleted" End If Text1.Text = " " Text2.Text = " " Text3.Text = " " Text4.Text = " " Text5.Text = " " Text6.Text = " " End Sub 3.EXIT Private Sub EXIT_Click() Unload Me End Sub 4.SAVE Private Sub SAVE_Click() If MsgBox("SAVE IT?", vbOKCancel) = vbOK Then Adodc1.Recordset.Update Else Adodc1.Recordset.CancelUpdate End If End Sub INSERTING VALUES INTO TABLE

SQL> select * from vb1; NAME ROLLNO MATHS ENGLISH PHYSICS CHEMISTRY -------------------------------------------------------------------------------------------------------Vipin 113 100 95 96 99 Soundarya 95 82 86 88 90

DELETING ONE ROW FROM TABLE

SQL> select * from vb1; NAME ROLLNO MATHS ENGLISH PHYSICS CHEMISTRY -------------------------------------------------------------------------------------------------------Vipin 113 100 95 96 99

Result: Thus the a simple form using Visual Basic has been created.

EXP:NO: DATE:

INTRODUCTION TO MENU DESIGN AND REPORTS

MENU Menus in Visual basic 6.0 are created using the Menu object defined in the VB Library. The menu created so are flat Win98 style menus and do not support icons. Further they cannot be created at runtime and require Menu Editor, modification though can be made during runtime. Menu bar is the standard feature of most windows applications. The main purpose of the menus is for easy navigation and control of an application. Some of the most common menu items are File, Edit, View, Tools, Help and more. Each item on the main menu bar also provide a list of options or in the form of a pull-down menu. When you create a Visual Basic 6 program, you need not include as many menu items as a full fledge Windows application such as Microsoft Words. What you need is to include those menu items that can improve the ease of using your program by the user, and not to confuse the user with unnecessary items. Adding menu bar is relatively easy to accomplish in Visual Basic. There are two ways to add menus to your application, one way is to use the Visual Basic's Application Wizard and the other way is to use the menu editor. Click on Menu Editor under Tools on main menubar. Menu editor is accessible only if a form is focussed.

Adding Menu Bar Using Visual Basic's Application Wizard

The easiest way to add menu bar to your application is by using Visual Basic's Application Wizard. This wizard allows the user to insert fully customized standard windows menus into his or her application. To start using Visual Basic's Application Wizard, you click on the Application Wizard icon at the Visual Basic new project dialog box, as shown below:

REPORT STEPS TO CREATE DATA REPORT: Steps for Creating Data Reports Open the Visual Basic Project Make the connection with the database using either Data Environment or through ADO Add Data Report to the project If using Data Environment then in Report properties DataSource : <Data Environment name> DataMember : <Command name> Drag the fields from the command into the report If using ADO then Create the appropriate no. of textboxes on the report. In datafield property of textbox write the name of the field name as in Recordset. Reports are important and useful in many respects because they provide useful and meaningful information concerning a set of data. In this chapter, we will show you how to create a report in Visual Basic 6. In previous versions of Visual Basic 6, there is no primary reporting . Previous versions of Visual basic 6 uses Crystal Reports tool, a software from Seagate. Fortunately, Microsoft has integrated a good report writer into Visual Basic 6, so you no longer need to use Crystal Report.

Connecting the report to database using Data Environment Designer


Click the Project menu, then select Data Environment. from the drop-down menu. The default data environment will appear, as shown in figure 40.2

Now, to connect to the database, right-click connection1 and select Microsoft Jet 3.51 OLE DB Provider (as we are using MS Access database) from the Data Link Properties dialog (as shown in Figure 40.3), then click next.

Retrieving Information from the Database


In order to use the database in your report, you need to create query to retrieve the information from the database. Here , we will use SQL command to create the query. First of all, right click on MyConnection to add a command to the data environment. The default command is Command1, you can rename it as MyCommand, as shown in Figure 40.5.

In order to use SQL command, right-click MyCommand and you can see its properties dialog. At the General tab, select SQL statement and key in the following SQL statement: SELECT Au_ID, Author FROM Authors ORDER BY Author This command is to select all the fields from the Authors table in the Biblio.Mdb database. The command ORDER BY Author is to arrange the list in ascending order according to the Authors' Names. Now, you need to customize a few properties of your data report so that it can connect to the database. The first property to set is the DataSource, set it to MyDataEnvironment. Next, you need to set the DataMember property to MyCommand,as shown in Figure 40.6

To add data to your report, you need to drag the fields from MyCommand in MyDataEnvironment into MyDataReport, as shown in Figure 40.7.Visual Basic 6 will automatically draw a RptTextBox, along with a RptLabel control for each field on the report. You can customize the look of the labels as well as the TextBoxes from the properties window of MyDataReport.

The Final step is to set MydataReport as the Startup form from the Project menu, then run the program. You will see your report as shown in Figure 40.8. You can print out your report.

Result: Thus the introduction to Menus and Reports in Visual Basic has been studied

EXP:NO: DATE:

REPORT GENERATION

Aim: To design a simple form in Visual Basic using Oracle as backend and generate the report for it. Algorithm for creating table: SQL> create table vb1(Name varchar2(20),Rollno number(3),Maths number(3),English number(3),Physics number(3),Chemistry number(3)); Table created. Table Description SQL> desc vb1; Name Null? Type ----------------------------------------- -------- ---------------------------NAME VARCHAR2(20) ROLLNO NUMBER(3) MATHS NUMBER(3) ENGLISH NUMBER(3) PHYSICS NUMBER(3) CHEMISTRY NUMBER(3) 2. Insert all the possible values into the vb1 table. 3. Enter commit command. Coding 1.ADD Private Sub ADD_Click() Text1.SetFocus Adodc1.Recordset.AddNew End Sub 2. SAVE Private Sub SAVE_Click() If MsgBox("SAVE IT?", vbOKCancel) = vbOK Then Adodc1.Recordset.Update Else Adodc1.Recordset.CancelUpdate End If

End Sub 3.EXIT Private Sub EXIT_Click() Unload Me End Sub 4. DELETE Private Sub DELETE_Click() If MsgBox("DELETE IT?", vbOKCancel) = vbOK Then Adodc1.Recordset.DELETE MsgBox "One row deleted" End If Text1.Text = " " Text2.Text = " " Text3.Text = " " Text4.Text = " " Text5.Text = " " Text6.Text = " " End Sub 5.REPORT Private Sub Report_Click() DataReport1.Show End Sub

INSERTING VALUES INTO THE TABLE:

GENERATING REPORT

REPORT

Result: Thus a report has been generated using Visual Basic .

EXP:NO: DATE:

MENU CREATION

Aim: To design a simple form in Visual Basic using Oracle as backend and create a menu for the actions. Algorithm for creating table: SQL> create table empdet(eid number(5),ename varchar2(20),contact number(15),desig varchar2(20),sala ry number(15)); Table created. Table Description SQL> desc empdet; Name Null? Type ----------------------------------------- -------- ---------------------------EID NUMBER(5) ENAME VARCHAR2(20) CONTACT NUMBER(15) DESIG VARCHAR2(20) SALARY NUMBER(15) 2. Insert all the possible values into the empdet table. 3. Enter commit command.

1.ADD Private Sub add_Click() Adodc1.Recordset.AddNew Text1.SetFocus End Sub 2.SAVE Private Sub save_Click() If MsgBox("SAVE IT?", vbOKCancel) = vbOK Then Adodc1.Recordset.Update Else Adodc1.Recordset.CancelUpdate End If End Sub 3.DELETE Private Sub delete_Click() If MsgBox("DELETE IT?", vbOKCancel) = vbOK Then Adodc1.Recordset.delete MsgBox "One row deleted" End If Text1.Text = " " Text2.Text = " " Text3.Text = " " Text4.Text = " " Text5.Text = " " Text6.Text = " " End Sub 4..REPORT Private Sub Report_Click() DataReport1.Show End Sub 5.EXIT Private Sub exit_Click() Unload Me End Sub 6..MENU BUTTON FOR ADD Private Sub foradd_Click() Adodc1.Recordset.AddNew Text1.SetFocus End Sub

7.MENU BUTTON FOR SAVE Private Sub forsave_Click() If MsgBox("SAVE IT?", vbOKCancel) = vbOK Then Adodc1.Recordset.Update Else Adodc1.Recordset.CancelUpdate End If End Sub 8.MENU BUTTON FOR DELETE Private Sub fordelete_Click() If MsgBox("DELETE IT?", vbOKCancel) = vbOK Then Adodc1.Recordset.delete MsgBox "One row deleted" End If Text1.Text = " " Text2.Text = " " Text3.Text = " " Text4.Text = " " Text5.Text = " " End Sub 9.MENU BUTTON FOR REPORT Private Sub forshowreport_Click() DataReport1.Show End Sub 10.MENU BUTTON FOR QUIT Private Sub forquit_Click() Unload Me End Sub

Result: Thus a menu has been created using Visual Basic .

EXP:NO: DATE: Aim:

DESIGN AND IMLPEMENTATION OF LIBRARY MANAGEMENT SYSTEM

To design the library details in Visual Basic using Oracle as backend. Algorithm for creating table: 1. Create library table with following fields Name Type ------------------------------- -------- ---BOOK NO NUMBER (15) BOOKNAME VARCHAR2 (15) BOOKAUTHOR VARCHAR2 (15) BOOKRATE NUMBER (8) NCOPY NUMBER (8) ISSUE DATE DATE RETURN DATE DATE 2. Insert all the possible values into the library table. 3. Enter commit command. Algorithm for ADO Connection: After creating the table in Oracle, Go to start menu 1. Start------> Settings------> Control Panel ------>Administrative Tools------> Data Sources (ODBC) ------>User DSN------>Add------> Select Microsoft ODBC for Oracle------>Finish------>OK 2. One new window will be appeared. In that window type Data Source Name as table name created in Oracle. Type user name as Scott. Then click O.K. Algorithm for ADODC in Visual Basic: 16. In Visual Basic create the labels, command buttons and their text boxes. 17. In Visual Basic go to Project menu, 18. Project---->Components---->Microsoft ADO Data Control 6.0 for OLEDB->O.K 19. Now ADODC Data Control available in toolbox. 20. Drag and drop the ADODC Data Control into the form. 21. Right click in ADODC Data Control then click the ADODC properties. 22. One New window will be appeared.

23. Choose general tab select ODBC Data source name as the table created in Oracle. 24. Choose authentication tab and select username, password as scott and tiger. 25. Choose record source------>select Command type as adcmdTable. 26. Select Table or Stored procedure name as table created in Oracle. 27. Click Apply------>O.K 28. Set the properties of each text box. 29. Select the data source as ADODC1. 30. Select the Data field and set the required field name created in table Coding: A) ADD Private Sub ADD_Click () Text1.SetFocus Adodc1.Recordset.AddNew End Sub B) SAVE Private Sub SAVE_Click () If MsgBox ("SAVE IT?", vbOKCancel) = vbOK Then Adodc1.Recordset.Update Else Adodc1.Recordset.CancelUpdate End If End Sub C) DELETE Private Sub DELETE_Click () If MsgBox ("DELETE IT?", vbOKCancel) = vbOK Then Adodc1.Recordset.Delete MsgBox "One row deleted" End If Text1.Text = "" Text2.Text = "" Text3.Text = "" Text4.Text = "" Text5.Text = "" Text6.Text = "" Text7.Text = "" Text8.Text = "" Text9.Text = "" Text10.Text = "" End Sub D) FIND

Private Sub FIND_Click () Dim N As String N = InputBox ("Enter the book") Adodc1.Recordset.Find "book_no=" & N If Adodc1.Recordset.BOF or Adodc1.Recordset.EOF Then MsgBox "Record not found" End If End Sub E) MOVE Private Sub FIRST_Click () Adodc1.Recordset.MoveFirst End Sub Private Sub PREVIOUS_Click () Adodc1.Recordset.MovePrevious End Sub Private Sub NEXT_Click () Adodc1.Recordset.MoveNext End Sub Private Sub LAST_Click () Adodc1.Recordset.MoveLast End Sub F) UPDATE Private Sub UPDATE_Click () Adodc1.Recordset.EditMode Adodc1.Recordset.Update End Sub G) EXIT Private Sub EXIT_Click () Unload Me End Sub

OUTPUT:

RESULT: Thus the library details were designed in Visual Basic using Oracle as backend and executed successfully.

EXP:NO: DATE: Aim:

DESIGN AND IMLPEMENTATION OF ONLINE BANKING SYSTEM

To design the Online banking system in Visual Basic using Oracle as backend. Algorithm for creating table: 1. Create bank table with following fields Name Null? Type -------------------- -------- -----------------------------------ACCNO NUMBER(5) CUSNAME VARCHAR2(20) CUSCITY VARCHAR2(20) AMOUNT NUMBER(10) 2. Insert all the possible values into the bank table. 3. Enter commit command. Algorithm for ADO Connection: After creating the table in Oracle, Go to start menu 1. Start------> Settings------> Control Panel ------>Administrative Tools------> Data Sources (ODBC) ------>User DSN------>Add------> Select Microsoft ODBC for Oracle------>Finish------>OK 2. One new window will be appeared. In that window type Data Source Name as table name created in Oracle. Type user name as Scott. Then click O.K. Algorithm for ADODC in Visual Basic: 1. In Visual Basic create the labels, command buttons and their text boxes. 2. In Visual Basic go to Project menu, 3. Project---->Components---->Microsoft ADO Data Control 6.0 for OLEDB->O.K 4. Now ADODC Data Control available in toolbox. 5. Drag and drop the ADODC Data Control into the form. 6. Right click in ADODC Data Control then click the ADODC properties. 7. One New window will be appeared.

8. Choose general tab select ODBC Data source name as the table created in Oracle. 9. Choose authentication tab and select username, password as scott and tiger. 10. Choose record source------>select Command type as adcmdTable. 11. Select Table or Stored procedure name as table created in Oracle. 12. Click Apply------>O.K 13. Set the properties of each text box. 14. Select the data source as ADODC1 15. Select the Data field and set the required field name created in table CODING: ADD: Private Sub Command1_Click( ) Adodc1.Recordset.AddNew Text1.SetFocus End Sub DELETE: Private Sub Command2_Click( ) If MsgBox("DELETE IT?", vbOKCancel) = vbOK Then Adodc1.Recordset.Delete End If MsgBox ("ONE ROW DELETED") Text1.Txt = "" Text2.Text = "" Text3.Text = "" Text4.Text = "" End Sub SAVE: Private Sub Command3_Click( ) If MsgBox("SAVE IT?", vbOKCancel) = vbOK Then Adodc1.Recordset.Update Else Adodc1.Recordset.CancelUpdate End If End Sub FIND: Private Sub Command4_Click( ) Dim N As String N = InputBox("Enter the accno") Adodc1.Recordset.Find "accno=" & N If Adodc1.Recordset.BOF or Adodc1.Recordset.EOF Then

MsgBox "Record not Found" End If End Sub DEPOSIT: Private Sub Command5_Click( ) Dim N1 As String N = InputBox("Enter the accno") Adodc1.Recordset.Find "accno=" & N N1 = InputBox("Enter the amount") Text4.Text = Val(Text4.Text) + N1 Adodc1.Recordset.Update End Sub WITH DRAW: Private Sub Command6_Click() Dim N1 As String N = InputBox("Enter the accno") Adodc1.Recordset.Find "accno=" & N N1 = InputBox("Enter the amount") Text4.Text = Val(Text4.Text) - N1 Adodc1.Recordset.Update End Sub CANCEL: Private Sub Command7_Click () Unload Me End Sub

OUTPUT: STARTUP FORM

WITHDRAW AN AMOUNT

DEPOSIT AN AMOUNT

ADD A CUSTOMER DETAIL

Result: Thus the online banking system details were designed in Visual Basic using Oracle as backend and executed successfully.

EXP:NO: DATE: Aim:

DESIGN AND IMLPEMENTATION OF EMPLOYEE PAYROLL SYSTEM

To design the Employee details in Visual Basic using Oracle as backend. Algorithm for creating table: 1. Create payroll table with following fields Name Type ------------------------------- -------- ---EID NUMBER (15) ENAME VARCHAR2 (15) DESIGNATION VARCHAR2 (15) BASICPAY NUMBER (8) HRA NUMBER (8) DA NUMBER (8) MA NUMBER (8) GROSSPAY NUMBER (10) DEDUCTION NUMBER (8) NETPAY NUMBER (8) 2. Insert all the possible values into the payroll table. 3. Enter commit command. Algorithm for ADO Connection:

After creating the table in Oracle, Go to start menu 1. Start------> Settings------> Control Panel ------>Administrative Tools------> Data Sources (ODBC) ------>User DSN------>Add------> Select Microsoft ODBC for Oracle------>Finish------>OK 2. One new window will be appeared. In that window type Data Source Name as table name created in Oracle. Type user name as Scott. Then click O.K. Algorithm for ADODC in Visual Basic: 31. In Visual Basic create the labels, command buttons and their text boxes. 32. In Visual Basic go to Project menu, 33. Project---->Components---->Microsoft ADO Data Control 6.0 for OLEDB->O.K 34. Now ADODC Data Control available in toolbox. 35. Drag and drop the ADODC Data Control into the form. 36. Right click in ADODC Data Control then click the ADODC properties. 37. One New window will be appeared. 38. Choose general tab select ODBC Data source name as the table created in Oracle. 39. Choose authentication tab and select username, password as scott and tiger. 40. Choose record source------>select Command type as adcmdTable. 41. Select Table or Stored procedure name as table created in Oracle. 42. Click Apply------>O.K 43. Set the properties of each text box. 44. Select the data source as ADODC1 45. Select the Data field and set the required field name created in table Coding A) FUNCTION Function calculate () Text8.Text = Val(Text4.Text) + Val(Text5.Text) + Val(Text6.Text) + Val(Text7.Text) Text10.Text = Val (Text8.Text) + Val (Text9.Text) End Function B) ADD Private Sub ADD_Click () Text1.SetFocus Adodc1.Recordset.AddNew End Sub C) SAVE Private Sub SAVE_Click () If MsgBox ("SAVE IT?", vbOKCancel) = vbOK Then Adodc1.Recordset.Update

Else Adodc1.Recordset.CancelUpdate End If End Sub D) DELETE Private Sub DELETE_Click () If MsgBox ("DELETE IT?", vbOKCancel) = vbOK Then Adodc1.Recordset.Delete MsgBox "One row deleted" End If Text1.Text = " " Text2.Text = " " Text3.Text = " " Text4.Text = " " Text5.Text = " " Text6.Text = " " Text7.Text = " " Text8.Text = " " Text9.Text = " " Text10.Text = " " End Sub E) FIND Private Sub FIND_Click () Dim N As String N = InputBox ("Enter the eid") Adodc1.Recordset.Find "eid=" & N If Adodc1.Recordset.BOF or Adodc1.Recordset.EOF Then MsgBox "Record not found" End If End Sub F) MOVE Private Sub FIRST_Click () Adodc1.Recordset.MoveFirst End Sub Private Sub PREVIOUS_Click () Adodc1.Recordset.MovePrevious End Sub Private Sub NEXT_Click () Adodc1.Recordset.MoveNext End Sub Private Sub LAST_Click () Adodc1.Recordset.MoveLast End Sub G) UPDATE

Private Sub UPDATE_Click () Adodc1.Recordset.EditMode Adodc1.Recordset.Update End Sub H) EXIT Private Sub EXIT_Click () Unload Me End Sub BASIC PAY,HRA, DA, MA, GROSS PAY, NETPAY Private Sub HRA_Change () Call calculate End Sub Private Sub DA_Change () Call calculate End Sub Private Sub MA_Change () Call calculate End Sub Private Sub GROSSPAY_Change () Call calculate End Sub Private Sub BASICPAY_Change () Call calculate End Sub Private Sub NETPAY_Change () Call calculate End Sub OUTPUT: START UP FORM

ADD AN EMPOLYEE DETAIL

SAVE AN EMPLOYEE DETAIL

FIND AN EMPLOYEE DETAIL

RESULT:

Thus the Employee payroll details were designed in Visual Basic using Oracle as backend and executed successfully.

You might also like