Sei sulla pagina 1di 45

Experiment No: 1

Title: Implementation of DDL commands of SQL with suitable examples

 Create table
 Alter table
 Drop Table

Objective:

 To understand the different issues involved in the design and implementation of a


database system

 To understand and use data definition language to write query for a database
Theory:

Oracle has many tools such as SQL * PLUS, Oracle Forms, Oracle Report Writer, Oracle
Graphics etc.

 SQL * PLUS: The SQL * PLUS tool is made up of two distinct parts. These are
 Interactive SQL: Interactive SQL is designed for create, access and manipulate
data structures like tables and indexes.
 PL/SQL: PL/SQL can be used to developed programs for different applications.
 Oracle Forms: This tool allows you to create a data entry screen along with the suitable
menu objects. Thus it is the oracle forms tool that handles data gathering and data
validation in a commercial application.
 Report Writer: Report writer allows programmers to prepare innovative reports using
data from the oracle structures like tables, views etc. It is the report writer tool that
handles the reporting section of commercial application.
 Oracle Graphics: Some of the data can be better represented in the form of pictures. The
oracle graphics tool allows programmers to prepare graphs using data from oracle
structures like tables, views etc.

SQL (Structured Query Language):

Structured Query Language is a database computer language designed for managing data in
relational database management systems (RDBMS), and originally based upon Relational
Algebra. Its scope includes data query and update, schema creation and modification, and data
access control.
SQL was one of the first languages for Edgar F. Codd's relational model and became the
most widely used language for relational databases.
 IBM developed SQL in mid of 1970’s.
 Oracle incorporated in the year 1979.
 SQL used by IBM/DB2 and DS Database Systems.
 SQL adopted as standard language for RDBS by ASNI in 1989.

1
DATA TYPES:

1. CHAR (Size): This data type is used to store character strings values of fixed length. The
size in brackets determines the number of characters the cell can hold. The maximum
number of character is 255 characters.
2. VARCHAR (Size) / VARCHAR2 (Size): This data type is used to store variable length
alphanumeric data. The maximum character can hold is 2000 character.
3. NUMBER (P, S): The NUMBER data type is used to store number (fixed or floating
point). Number of virtually any magnitude may be stored up to 38 digits of precision.
Number as large as 9.99 * 10 124. The precision (p) determines the number of places to the
right of the decimal. If scale is omitted then the default is zero. If precision is
omitted, values are stored with their original precision up to the maximum of 38 digits.
4. DATE: This data type is used to represent date and time. The standard format is DD-MM-
YY as in 17-SEP-2009. To enter dates other than the standard format, use the
appropriate functions. Date time stores date in the 24-Hours format. By default the time
in a date field is 12:00:00 am, if no time portion is specified. The default date for a date field is
the first day the current month.
5. LONG: This data type is used to store variable length character strings containing up to
2GB. Long data can be used to store arrays of binary data in ASCII format. LONG values
cannot be indexed, and the normal character functions such as SUBSTR cannot be applied.
6. RAW: The RAW data type is used to store binary data, such as digitized picture or image.
Data loaded into columns of these data types are stored without any further conversion.
RAW data type can have a maximum length of 255 bytes. LONG RAW data type can
contain up to 2GB.

SQL language is sub-divided into several language elements, including:

 Clauses, which are in some cases optional, constituent components of statements and
queries.
 Expressions, which can produce either scalar values or tables consisting of columns and
rows of data.
 Predicates which specify conditions that can be evaluated to SQL three-valued logic
(3VL) Boolean truth values and which are used to limit the effects of statements and
queries, or to change program flow.
 Queries which retrieve data based on specific criteria.
 Statements which may have a persistent effect on schemas and data, or which may control
transactions, program flow, connections, sessions, or diagnostics.
 SQL statements also include the semicolon (";") statement terminator. Though not required
on every platform, it is defined as a standard part of the SQL grammar.
 Insignificant white space is generally ignored in SQL statements and queries, making it
easier to format SQL code for readability.

There are five types of SQL statements. They are:

1. DATA DEFINITION LANGUAGE (DDL)

2. DATA MANIPULATION LANGUAGE (DML)

3. DATA RETRIEVAL LANGUAGE (DRL)

4. TRANSATIONAL CONTROL LANGUAGE (TCL)


2
5. DATA CONTROL LANGUAGE (DCL)

1. DATA DEFINITION LANGUAGE (DDL): The Data Definition Language (DDL) is used
to create and destroy databases and database objects. These commands will primarily be used by
database administrators during the setup and removal phases of a database project. Let's take a
look at the structure and usage of four basic DDL commands:

1. CREATE 2. ALTER 3. DROP 4. RENAME

1. CREATE:

(a)CREATE TABLE: This is used to create a new relation (table)

Syntax: CREATE TABLE <relation_name/table_name >


(field_1 data_type(size),field_2 data_type(size), .. . );

Example:

SQL> CREATE TABLE cab(cname CHAR (10),mobno NUMBER (3), startloc CHAR (5),
endloc CHAR(5), distance VARCHAR(6), amount NUMBER(5), nopass NUMBER(6), otp
NUMBER);

2. ALTER:

(a)ALTER TABLE ...ADD...: This is used to add some extra fields into existing

relation.
Syntax: ALTER TABLE relation_name ADD (new field_1 data_type(size), new field_2
data_type(size),..);

Example: SQL>ALTER TABLE cab ADD (type CHAR(10));

(b)ALTER TABLE...MODIFY...: This is used to change the width as well as data type of
fields of existing relations.

Syntax: ALTER TABLE relation_name MODIFY (field_1 newdata_type(Size), field_2


newdata_type(Size),....field_newdata_type(Size));

Example:SQL>ALTER TABLE cab MODIFY(distance CHAR(10));

c) ALTER TABLE..DROP...: This is used to remove any field of existing relations.

Syntax: ALTER TABLE relation_name DROP COLUMN (field_name);

Example:SQL>ALTER TABLE cab DROP column (nopass);

d)ALTER TABLE..RENAME...: This is used to change the name of fields in existing


relations.

3
Syntax: ALTER TABLE relation_name RENAME COLUMN (OLD field_name) to
(NEW field_name);

Example: SQL>ALTER TABLE cab RENAME COLUMN amount to cash;;

3. DROP TABLE: This is used to delete the structure of a relation. It permanently deletes the
records in the table.

Syntax: DROP TABLE relation_name;

Example: SQL>DROP TABLE cab;

4. RENAME: It is used to modify the name of the existing database object.

Syntax: RENAME TABLE old_relation_name TO new_relation_name;

Example: SQL>RENAME TABLE cab TO cabsys;

Experiment No:2

Title : Implementation of DML commands of SQL with suitable examples


 Insert table
 Select table
 Update table
 Delete Table

Objective :
 To understand the different issues involved in the design and implementation of a
database system
 To understand and use data manipulation language to query, update, and manage a
database

Theory :
DATA MANIPULATION LANGUAGE (DML): The Data Manipulation Language (DML) is
used to retrieve, insert and modify database information. These commands will be used by all
database users during the routine operation of the database. Let's take a brief look at the basic
DML commands:

1. INSERT 2. UPDATE 3. DELETE

1. INSERT INTO: This is used to add records into a relation. These are three type of INSERT
INTO queries which are as
a) Inserting a single record

Syntax: INSERT INTO < relation/table name> (field_1,field_2……field_n)VALUES


(data_1,data_2,........data_n);
Example: SQL>INSERT INTO student(sno,sname,class,address)VALUES
(1,’Ravi’,’M.Tech’,’Palakol’);

b) Inserting a single record


4
Syntax: INSERT INTO < relation/table name>VALUES (data_1,data_2,........data_n);

Example: SQL>INSERT INTO student VALUES (1,’Ravi’,’M.Tech’,’Palakol’);

c) Inserting all records from another relation

Syntax: INSERT INTO relation_name_1 SELECT Field_1,field_2,field_n


FROM relation_name_2 WHERE field_x=data;

Example: SQL>INSERT INTO std SELECT sno,sname FROM student WHERE name = ‘Ramu‘;

d) Inserting multiple records

Syntax: INSERT INTO relation_name field_1,field_2,.....field_n) VALUES


(&data_1,&data_2,........&data_n);

Example: SQL>INSERT INTO student (sno, sname, class,address)


VALUES (&sno,’&sname’,’&class’,’&address’);

Enter value for sno: 101


Enter value for name: Ravi
Enter value for class: M.Tech
Enter value for name: Palakol

2. UPDATE-SET-WHERE: This is used to update the content of a record in a relation.


Syntax: SQL>UPDATE relation name SET Field_name1=data,field_name2=data,
WHERE field_name=data;

Example: SQL>UPDATE student SET sname = ‘kumar’ WHERE sno=1;

3. DELETE-FROM: This is used to delete all the records of a relation but it will retain the
structure of that relation.

a) DELETE-FROM: This is used to delete all the records of relation.


Syntax:SQL>DELETE FROM relation_name;

Example: SQL>DELETE FROM std;

b) DELETE -FROM-WHERE: This is used to delete a selected record from a relation.


c)
Syntax: SQL>DELETE FROM relation_name WHERE condition;

Example: SQL>DELETE FROM student WHERE sno = 2;

5. TRUNCATE: This command will remove the data permanently. But structure will not be
removed.

5
Difference between Truncate & Delete:-

 By using truncate command data will be removed permanently & will not get back where
as by using delete command data will be removed temporally & get back by using roll
back command.
 By using delete command data will be removed based on the condition where as by using
truncate command there is no condition.
 Truncate is a DDL command & delete is a DML command.

Syntax: TRUNCATE TABLE <Table name>


Example TRUNCATE TABLE student;

 To Retrieve data from one or more tables.

2. SELECT FROM: To display all fields for all records.


3.
Syntax : SELECT * FROM relation_name;
Example : SQL> select * from dept;
DEPTNO DNAME LOC
-------- ----------- ----------
NEW
10 ACCOUNTING YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

2. SELECT FROM: To display a set of fields for all records of relation.

DEPTNO DNAME
10 ACCOUNTING
20 RESEARCH
30 SALES

3. SELECT - FROM -WHERE: This query is used to display a selected set of fields for a
selected set of records of a relation.

Syntax: SELECT a set of fields FROM relation_name WHERE condition;

Example: SQL> select * FROM dept WHERE deptno<=20;

DEPTNO DNAME LOC


------ ----------- ------------
NEW
10 ACCOUNTING YORK
20 RESEARCH DALLAS

6
Experiment No:3

● Creating relationship between the databases – Nested Queries & Join Queries
● A Subquery or Inner query or a Nested query is a query within another SQL query and
embedded within the WHERE clause.
● A subquery is used to return data that will be used in the main query as a condition to
further restrict the data to be retrieved.
● Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements
along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
There are a few rules that subqueries must follow −
● Subqueries must be enclosed within parentheses.
● A subquery can have only one column in the SELECT clause, unless multiple columns
are in the main query for the subquery to compare its selected columns.
● An ORDER BY command cannot be used in a subquery, although the main query can
use an ORDER BY. The GROUP BY command can be used to perform the same
function as the ORDER BY in a subquery.
● Subqueries that return more than one row can only be used with multiple value operators
such as the IN operator.
● The SELECT list cannot include any references to values that evaluate to a BLOB,
ARRAY, CLOB, or NCLOB.
● A subquery cannot be immediately enclosed in a set function.
● The BETWEEN operator cannot be used with a subquery. However, the BETWEEN
operator can be used within the subquery.
Subqueries with the SELECT Statement
Subqueries are most frequently used with the SELECT statement. The
basic syntax is as follows −

SELECT column_name [, column_name ]


FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])
Example
Consider the CUSTOMERS table having the following records −

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

7
Now, let us check the following subquery with a SELECT statement.

SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500) ;
This would produce the following result.

+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+
Subqueries with the INSERT Statement
Subqueries also can be used with INSERT statements. The INSERT statement uses the data
returned from the subquery to insert into another table. The selected data in the subquery can be
modified with any of the character, date or number functions.
The basic syntax is as follows.

INSERT INTO table_name [ (column1 [, column2 ]) ]


SELECT [ *|column1 [, column2 ]
FROM table1 [, table2 ]
[ WHERE VALUE OPERATOR ]
Example
Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Now to
copy the complete CUSTOMERS table into the CUSTOMERS_BKP table, you can use the
following syntax.

SQL> INSERT INTO CUSTOMERS_BKP


SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS) ;
Subqueries with the UPDATE Statement
The subquery can be used in conjunction with the UPDATE statement. Either single or multiple
columns in a table can be updated when using a subquery with the UPDATE statement.
The basic syntax is as follows.

UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Example

8
Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS
table. The following example updates SALARY by 0.25 times in the CUSTOMERS table for
all the customers whose AGE is greater than or equal to 27.

SQL> UPDATE CUSTOMERS


SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 27 );
This would impact two rows and finally CUSTOMERS table would have the following records.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 125.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 2125.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Subqueries with the DELETE Statement
The subquery can be used in conjunction with the DELETE statement like with any other
statements mentioned above.
The basic syntax is as follows.

DELETE FROM TABLE_NAME


[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Example
Assuming, we have a CUSTOMERS_BKP table available which is a backup of the
CUSTOMERS table. The following example deletes the records from the CUSTOMERS table
for all the customers whose AGE is greater than or equal to 27.

SQL> DELETE FROM CUSTOMERS

WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP

WHERE AGE >= 27 );

This would impact two rows and finally the CUSTOMERS table would have the following
records.

+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
9
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+

Title : Implementation of different types of Joins


● A SQL JOIN combines records from two tables.
● A JOIN locates related column values in the two tables.
● A query can contain zero, one, or multiple JOIN operations.
● INNER JOIN is the same as JOIN; the keyword INNER is optional.

Objective :
 To implement different types of joins
Theory :
The SQL Joins clause is used to combine records from two or more tables in a
database. A JOIN is a means for combining fields from two tables by using values common

to each.The join is actually performed by the ‘where’ clause which combines specified rows
of tables.
Syntax:
SELECT column 1, column 2, column 3...FROM table_name1, table_name2
WHERE table_name1.column name = table_name2.columnname;
Types of Joins :
1. Simple Join
2. Self Join
3. Outer Join
Simple Join:
It is the most common type of join. It retrieves the rows from 2 tables having a common
column and is further classified into
Equi-join :
A join, which is based on equalities, is called equi-join.
Example:
Select * from item, cust where item.id=cust.id;

In the above statement, item-id = cust-id performs the join statement. It retrieves rows from
both the tables provided they both have the same id as specified by the where clause. Since
the where clause uses the comparison operator (=) to perform a join, it is said to be equijoin.
It combines the matched rows of tables. It can be used as follows:

 To insert records in the target table.


 To create tables and insert records in this table.
 To update records in the target table.
 To create views.

Non Equi-join:
It specifies the relationship between columns belonging to different tables by
making use of relational operators other than’=’.
Example:
Select * from item, cust where item.id<cust.id;

Table Aliases
10
Table aliases are used to make multiple table queries shorted and more readable. We give an
alias name to the table in the ‘from’ clause and use it instead of the name throughout
the query.
Self join:
Joining of a table to itself is known as self-join. It joins one row in a table to another.
It can compare each row of the table to itself and also with other rows of the same table.

Example:
select * from emp x ,emp y where x.salary >= (select avg(salary) from x.emp
where x. deptno =y.deptno);

Outer Join:
It extends the result of a simple join. An outer join returns all the rows returned by simple
join as well as those rows from one table that do not match any row from the table. The
symbol (+) represents outer join.

Different Types of SQL JOINs


Here are the different types of the JOINs in SQL:
● (INNER) JOIN: Returns records that have matching values in both tables
SELECT column_name(s)
FROM table1
INNER JOIN table2 ON table1.column_name = table2.column_name;
● LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the
right table.
SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;
● RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from
the left table.
SELECT column_name(s)
FROM table1
RIGHT JOIN table2 ON table1.column_name = table2.column_name;
● FULL (OUTER) JOIN: Return all records when there is a match in either left or right table
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2 ON table1.column_name = table2.column_name;

11
The SQL Joins clause is used to combine records from two or more tables in a database. A
JOIN is a means for combining fields from two tables by using values common to each.
Consider the following two tables −
Table 1 − CUSTOMERS Table
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Table 2 − ORDERS Table

+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+
Now, let us join these two tables in our SELECT statement as shown below.

SQL> SELECT ID, NAME, AGE, AMOUNT


FROM CUSTOMERS, ORDERS
WHERE CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
This would produce the following result.

+----+----------+-----+--------+
| ID | NAME | AGE | AMOUNT |
+----+----------+-----+--------+
| 3 | kaushik | 23 | 3000 |
| 3 | kaushik | 23 | 1500 |
| 2 | Khilan | 25 | 1560 |
| 4 | Chaitali | 25 | 2060 |
+----+----------+-----+--------+
Here, it is noticeable that the join is performed in the WHERE clause. Several operators can be
used to join tables, such as =, <, >, <>, <=, >=, !=, BETWEEN, LIKE, and NOT; they can all be
used to join tables. However, the most common operator is the equal to symbol.

Experiment No: 4
12
Objective:
 To practice and implement constraints
Theory:
CONSTRAINTS:
Constraints are used to specify rules for the data in a table. If there is any violation between the
constraint and the data action, the action is aborted by the constraint. It can be specified when the
table is created (using CREATE TABLE statement) or after the table is created (using ALTER
TABLE statement).

1. NOT NULL: When a column is defined as NOTNULL, then that column becomes a
mandatory column. It implies that a value must be entered into the column if the record is to be
accepted for storage in the table.
Syntax:
CREATE TABLE Table_Name (column_name data_type (size) NOT NULL, );
Example:
CREATE TABLE student (sno NUMBER(3)NOT NULL, name CHAR(10));
2. UNIQUE: The purpose of a unique key is to ensure that information in the column(s) is
unique i.e. a value entered in column(s) defined in the unique constraint must not be repeated
across the column(s). A table may have many unique keys.
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) UNIQUE, ….);
Example:
CREATE TABLE student (sno NUMBER(3) UNIQUE, name CHAR(10));
3.CHECK: Specifies a condition that each row in the table must satisfy. To satisfy the
constraint, each row in the table must make the condition either TRUE or unknown (due to a
null).
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) CHECK(logical
expression), ….);
Example:
CREATE TABLE student (sno NUMBER (3), name CHAR(10),class
CHAR(5),CHECK(class IN(‘CSE’,’CAD’,’VLSI’));
4. PRIMARY KEY: A field which is used to identify a record uniquely. A column or
combination of columns can be created as primary key, which can be used as a reference from
other tables. A table contains primary key is known as Master Table.

 It must uniquely identify each record in a table.


 It must contain unique values.
 It cannot be a null field.
 It cannot be multi port field.
 It should contain a minimum no. of fields necessary to be called unique.
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) PRIMARY KEY,..);
Example:
CREATE TABLE faculty (fcode NUMBER(3) PRIMARY KEY, fname
CHAR(10));

5. FOREIGN KEY: It is a table level constraint. We cannot add this at column level. To
reference any primary key column from other table this constraint can be used. The table in
which the foreign key is defined is called a detail table. The table that defines the primary key
and is referenced by the foreign key is called the master table.
13
Syntax: CREATE TABLE Table_Name(column_name data_type(size)
FOREIGN KEY(column_name) REFERENCES table_name);
Example:

CREATE TABLE subject (scode NUMBER (3) PRIMARY KEY, subname


CHAR(10),fcode NUMBER(3), FOREIGN KEY(fcode) REFERENCE faculty );

Defining integrity constraints in the alter table command:

Syntax: ALTER TABLE Table_Name ADD PRIMARY KEY (column_name);


Example: ALTER TABLE student ADD PRIMARY KEY (sno);
(Or)
Syntax: ALTER TABLE table_name ADD CONSTRAINT constraint_name
PRIMARY KEY(colname)
Example: ALTER TABLE student ADD CONSTRAINT SN PRIMARY KEY(SNO)

Dropping integrity constraints in the alter table command:

Syntax: ALTER TABLE Table_Name DROP constraint_name;


Example: ALTER TABLE student DROP PRIMARY KEY;
(or)
Syntax: ALTER TABLE student DROP CONSTRAINT constraint_name;
Example: ALTER TABLE student DROP CONSTRAINT SN;
6. DEFAULT : The DEFAULT constraint is used to insert a default value into a column. The
default value will be added to all new records, if no other value is specified.
Syntax:
CREATE TABLE Table_Name(col_name1,col_name2,col_name3
DEFAULT ‘<value>’);
Example:
CREATE TABLE student (sno NUMBER(3) UNIQUE, name CHAR(10),address
VARCHAR(20) DEFAULT ‘Aurangabad’);

Experiment No: 5

Objective:
To Create a Virtual table (Views) based on the result set of an SQL statement.
Theory:
VIEW
A view is nothing more than a SQL statement that is stored in the database with an associated
name. A view is actually a composition of a table in the form of a predefined SQL query.
A view can contain all rows of a table or select rows from a table. A view can be created from
one or many tables which depends on the written SQL query to create a view.
Views, which are a type of virtual tables allow users to do the
following −
● Structure data in a way that users or classes of users find natural or intuitive.

14
● Restrict access to the data in such a way that a user can see and (sometimes) modify
exactly what they need and no more.
● Summarize data from various tables which can be used to generate reports.
Creating Views
Database views are created using the CREATE VIEW statement. Views can be created from a
single table, multiple tables or another view.
To create a view, a user must have the appropriate system privilege according to the specific
implementation.
The basic CREATE VIEW syntax is as follows −

CREATE VIEW view_name AS


SELECT column1, column2.....
FROM table_name
WHERE [condition];
You can include multiple tables in your SELECT statement in a similar way as you use them in
a normal SQL SELECT query.
Example
Consider the CUSTOMERS table having the following records −

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example to create a view from the CUSTOMERS table. This view would be
used to have customer name and age from the CUSTOMERS table.

SQL > CREATE VIEW CUSTOMERS_VIEW AS

SELECT name, age FROM CUSTOMERS;

Now, you can query CUSTOMERS_VIEW in a similar way as you query an actual table.
Following is an example for the same.

SQL > SELECT * FROM CUSTOMERS_VIEW;

This would produce the following result.

+----------+-----+
| name | age |
+----------+-----+

15
| Ramesh | 32 |
| Khilan | 25 |
| kaushik | 23 |
| Chaitali | 25 |
| Hardik | 27 |
| Komal | 22 |
| Muffy | 24 |
+----------+-----+
The WITH CHECK OPTION
The WITH CHECK OPTION is a CREATE VIEW statement option. The purpose of the WITH
CHECK OPTION is to ensure that all UPDATE and INSERTs satisfy the condition(s) in the
view definition.
If they do not satisfy the condition(s), the UPDATE or INSERT returns an error.
The following code block has an example of creating same view CUSTOMERS_VIEW with
the WITH CHECK OPTION.

CREATE VIEW CUSTOMERS_VIEW AS


SELECT name, age FROM CUSTOMERS
WHERE age IS NOT NULL WITH CHECK OPTION;
The WITH CHECK OPTION in this case should deny the entry of any NULL values in the
view's AGE column, because the view is defined by data that does not have a NULL value in
the AGE column.
Updating a View
A view can be updated under certain conditions which are given below

● The SELECT clause may not contain the keyword DISTINCT.
● The SELECT clause may not contain summary functions.
● The SELECT clause may not contain set functions.
● The SELECT clause may not contain set operators.
● The SELECT clause may not contain an ORDER BY clause.
● The FROM clause may not contain multiple tables.
● The WHERE clause may not contain subqueries.
● The query may not contain GROUP BY or HAVING.
● Calculated columns may not be updated.
● All NOT NULL columns from the base table must be included in the view in order for
the INSERT query to function.
So, if a view satisfies all the above-mentioned rules then you can update that view. The
following code block has an example to update the age of Ramesh.

SQL > UPDATE CUSTOMERS_VIEW SET AGE = 35 WHERE name = 'Ramesh';

This would ultimately update the base table CUSTOMERS and the same would reflect in the
view itself. Now, try to query the base table and the SELECT statement would produce the
following result.

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
16
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Inserting Rows into a View
Rows of data can be inserted into a view. The same rules that apply to the UPDATE command
also apply to the INSERT command.
Here, we cannot insert rows in the CUSTOMERS_VIEW because we have not included all the
NOT NULL columns in this view, otherwise you can insert rows in a view in a similar way as
you insert them in a table.
Deleting Rows into a View
Rows of data can be deleted from a view. The same rules that apply to the UPDATE and
INSERT commands apply to the DELETE command.
Following is an example to delete a record having AGE = 22.

SQL > DELETE FROM CUSTOMERS_VIEW WHERE age = 22;

This would ultimately delete a row from the base table CUSTOMERS and the same would
reflect in the view itself. Now, try to query the base table and the SELECT statement would
produce the following result.

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Renaming the columns of a view:-
Syntax:-
CREATE VIEW viewname AS
SELECT newcolumnname….
FROM tablename
WHERE columnname=expression_list;

Selecting a data set from a view-


Syntax:-
SELECT columnname, columnname
FROM viewname
WHERE search condition;
17
Dropping Views
Obviously, where you have a view, you need a way to drop the view if
it is no longer needed. The syntax is very simple and is given below −

DROP VIEW view_name;


Following is an example to drop the CUSTOMERS_VIEW from the CUSTOMERS table.
DROP VIEW CUSTOMERS_VIEW;

Experiment No:6

Objective:
To create PL/SQL functions and to implement the stored procedures in SQL (Function and
Procedures).
Theory:
Introduction – PL/SQL bridges the gap between database technology and procedural
programming languages. It can be thought of as a development tool that extends the
facilities of Oracles SQL database language. Via PL/SQL you can insert, delete, update
and retrieve table data as well as writing loops or branching to another block of code.
PL/SQL Block structure-

DECLARE
Declarations of memory variables used later
BEGIN
SQL executable statements for manipulating table data.
EXCEPTIONS
SQL and/or PL.SQL code to handle errors.
END;

Displaying user Messages on the screen – Any programming tool requires a


method through which messages can be displayed to the user.
dbms_output is a package that includes a number of procedure and functions that
accumulate information in a buffer so that it can be retrieved later. These functions can
also be used to display message to the user.
put_line: put a piece of information in the buffer followed by a end of line marker. It can
also be used to display message to the user.
Setting the server output on:

SET SERVER OUTPUT ON:


Example: Write the following code in the PL/SQL block to display message to user
DBMS_OUTPUT.PUT_LINE(‘Display user message’);
Conditional control in PL/SQL-
Syntax:
IF <condition> THEN
<Action>
ELSEIF<condition>
<Action>
ELSE
<Action>
ENDIF;
The WHILE LOOP:
18
Syntax:
WHILE <condition>
LOOP
<Action>
END LOOP;

The FOR LOOP statement:


Syntax:
FOR variable IN [REVERSE] start—end
LOOP
<Action>
END LOOP;

The GOTO statement: The goto statement allows you to change the flow of control within a
PL/SQL Block
KEYWORDS AND THEIR PURPOSES
REPLACE: It recreates the procedure if it already exists.
PROCEDURE: It is the name of the procedure to be created.
ARGUMENT: It is the name of the argument to the procedure. Parenthesis can be omitted if
no arguments are present.
IN: Specifies that a value for the argument must be specified when calling the procedure ie.,
used to pass values to a sub-program. This is the default parameter.
OUT: Specifies that the procedure passes a value for this argument back to it‟s calling
environment after execution ie. used to return values to a caller of the sub-program.
INOUT: Specifies that a value for the argument must be specified when calling the
procedure and that procedure passes a value for this argument back to it‟s calling
environment after execution.
RETURN: It is the data type of the function‟s return value because every function must
return a value, this clause is required.
PROCEDURES
Syntax :
create or replace procedure <procedure name> (argument {in,out,inout} datatype )
{is,as} variable declaration;
constant declaration;
begin
PL/SQL subprogram body;
exception
exception PL/SQL block;
end;
FUNCTIONS
Syntax:
create or replace function <function name> (argument in datatype,……) return datatype {is,as}
variable declaration;
constant declaration;
begin
PL/SQL subprogram body;
exception
exception PL/SQL block;
19
end;

Tables used:
SQL> select * from ititems;
PRODI
ITEMID ACTUALPRICE ORDID D
--------- ----------- -------- ---------
101 2000 500 201
102 3000 1600 202
103 4000 600 202

PROGRAM FOR GENERAL PROCEDURE – SELECTED RECORD‘S PRICE IS


INCREMENTED BY 500 , EXECUTING THE PROCEDURE CREATED AND
DISPLAYING THE UPDATED TABLE
SQL> create procedure itsum(identity number, total number) is price number;
2 null_price exception;
3 begin
4 select actualprice into price from ititems where itemid=identity;
5 if price is null then
6 raise null_price;
7 else
8 update ititems set actualprice=actualprice+total where itemid=identity;
9 end if;
10 exception
11 when null_price then
12 dbms_output.put_line('price is null');
13 end;
14 /

Procedure created.
SQL> exec itsum(101, 500);
PL/SQL procedure successfully completed.
SQL> select * from ititems;
PRODI
ITEMID ACTUALPRICE ORDID D
--------- ----------- --------- ---------
101 2500 500 201
102 3000 1600 202
103 4000 600 202
PROCEDURE FOR ‗IN‘ PARAMETER – CREATION,
EXECUTION SQL> set serveroutput on;
SQL> create procedure yyy (a IN number) is price number;
2 begin
3 select actualprice into price from ititems where itemid=a;
4 dbms_output.put_line('Actual price is ' || price);
5 if price is null then
6 dbms_output.put_line('price is null');
7 end if;
8 end;
9 /
Procedure created.
20
SQL> exec yyy(103);
Actual price is 4000
PL/SQL procedure successfully completed.

PROCEDURE FOR 'OUT‘ PARAMETER – CREATION, EXECUTION


SQL> set serveroutput on;
SQL> create procedure zzz (a in number, b out number) is identity number;
begin
select ordid into identity from ititems where itemid=a;
if identity<1000 then
b:=100;
end if;
end; /
SQL> declare
2 a number;
3 b number;
4 begin
5 zzz(101,b);
6 dbms_output.put_line('The value of b is '|| b);
7 end;
8 /
The value of b is 100
PL/SQL procedure successfully completed.
PROCEDURE FOR ‗INOUT‘ PARAMETER – CREATION, EXECUTION
SQL> create procedure itit ( a in out number) is
2 begin
3 a:=a+1;
4 end;
5 /
Procedure created.

SQL> declare
2 a number:=7;
3 begin
4 itit(a);
5 dbms_output.put_line(„The updated value is „||a);
6 end;
7 /

The updated value is 8


PL/SQL procedure successfully completed.
Tables used:

SQL>select * from ittrain;


TNO TFARE
---------------------
1001 550
1002 600
PROGRAM FOR FUNCTION AND IT‘S EXECUTION

SQL> create function trainfn (trainnumber number) return number is


21
2 trainfunction ittrain.tfare % type;
3 begin
4 select tfare into trainfunction from ittrain where tno=trainnumber;
5 return(trainfunction);
6 end;
7 /
Function created.

SQL> declare
2 total number;
3 begin
4 total:=trainfn (1001);
5 dbms_output.put_line('Train fare is Rs. '||total);

6 end;
7 /

Train fare is Rs.550


PL/SQL procedure successfully completed.

FACTORIAL OF A NUMBER USING FUNCTION — PROGRAM AND EXECUTION


SQL> create function itfact (a number) return number is
2 fact number:=1;
3 b number;
4 begin
5 b:=a;
6 while b>0
7 loop
8 fact:=fact*b;
9 b:=b-1;
10 end loop;
11 return(fact);
12 end;
13 /
Function created.
SQL> declare
2 a number:=7;
3 f number(10);
4 begin
5 f:=itfact(a);
6 dbms_output.put_line(„The factorial of the given number is‟||f);
7 end;
8 /

The factorial of the given number is 5040

Experiment No: 7

Objective:

22
To study the basics of front end tools.

Procedure
Object
• An object is a type of user interface element you create on a Visual Basic form by using a
toolbox control.
• In fact, in Visual Basic, the form itself is also an object.
• You can move, resize, and customize objects by setting object properties.
• A property is a value or characteristic held by a Visual Basic object, such as Caption or Fore
Color.
• Properties can be set at design time by using the Properties window or at run time by using
statements in the program code.

Object. Property = Value


• Where Object is the name of the object you‟re customizing. Property is the characteristic you
want to change. Value is the new property setting.
• For example,

Command1.Caption = "Hello" 1.The Form Object


• The Form is where the user interface is drawn. It is central to the development of Visual Basic
applications.
• Form Properties:
o Appearance Selects 3-D or flat appearance.
o BackColor Sets the form background color.
o BorderStyle Sets the form border to be fixed or sizeable.
o Caption sets the form window title.
o Enabled If True, allows the form to respond to mouse and keyboard events;

if False, disables form.


o Font Sets font type, style, size.
o ForeColor Sets color of text or graphics.
o Picture Places a bitmap picture in the form.
o Visible If False, hides the form.
• Form Events:
• Activate Form_Activate event is triggered when form becomes the active window.
23
• Click Form_Click event is triggered when user clicks on form.
• DblClick Form_DblClick event is triggered when user doubleclicks on form.
• Load Form_Load event occurs when form is loaded.This is a good place to initialize variables
and set any runtime properties.
• Form Methods:
• Cls Clears all graphics and text from form. Does not clear any objects.
• Print Prints text string on the form.

• Examples
frmExample.Cls ' clears the form frmExample.Print "This will print on the form" 2.
CommandButton
• The Command Button control is use to create buttons with a variety of uses on a form.
• A command button is the most basic way to get user input while a program is running.
• By clicking a command button, the user requests that a specific action be taken in the program.
• Visual Basic terms, clicking a command button creates an event, which must be processed in
your program.
• Command Button Properties:
• Appearance Selects 3-D or flat appearance.
• Cancel Allows selection of button with Esc key (only one button on a form can have this
property True).
• Caption String to be displayed on button.
• Default Allows selection of button with Enter key (only one button on a form can have this
property True).
• Font Sets font type, style, size.
• Command Button Events:
• Click Event triggered when button is selected either by clicking on it or by pressing the access
key.
3. Label Boxes
• Label, the simplest control in the Visual Basic toolbox, displays formatted text on a user
interface form. Typical uses for the Label control include:
• Help text
• Program splash screen headings
• Formatted output, such as names, times, and dates
• Descriptive labels for other objects, including text boxes and list boxes.
• Label Properties:
• Alignment Aligns caption within border.
• Appearance Selects 3-D or flat appearance.
• AutoSize -If True, the label is resized to fit the text specified by the caption property. If False,
the label will remain the size defined at design time and the text may be clipped.
• BorderStyle Determines type of border.
• Caption String to be displayed in box.
• Font Sets font type, style, size.
• Label Events:
• Click Event triggered when user clicks on a label.
• DblClick Event triggered when user double-clicks on a label.
4. Textbox
• A Textbox is used to display information entered at design time, by a user at run-time, or
assigned within code.
• The displayed text may be edited.

24
• The Textbox control is one of the most versatile tools in the Visual Basic toolbox.
• This control performs two functions:
• Displaying output (such as operating instructions or the contents of a file) on a form.
• Receiving text (such as names and phone numbers) as user input.
• Text Box Properties:
1. Appearance : Selects 3-D or flat appearance.
2. BorderStyle : Determines type of border.
3. Font : Sets font type, style, size.
4. MaxLength : Limits the length of displayed text (0 value indicates unlimited length).
5. MultiLine : Specifies whether text box displays single line or multiple lines. 6. PasswordChar
:Hides text with a single character.
7. ScrollBars :Specifies type of displayed scroll bar(s). 8. SelLength :Length of selected text
(run-time only). 9. SelStart :Starting position of selected text (run-time only). 10.SelText
:Selected text (run-time only). 11.Tag : Stores a string expression. 12.Text :Displayed text
• Text Box Events:
1. Change :Triggered every time the Text property changes.
2. LostFocus :Triggered when the user leaves the text box. This is a good place to examine the
contents of a text box after editing.
3. KeyPress :Triggered whenever a key is pressed. Used for key trapping, as seen in last class.
5. Check Boxes
• Check boxes provide a way to make choices from a list of potential candidates.
• Some, all, or none of the choices in a group may be selected
• Check Box Properties:
• Caption :Identifying text next to box.
• Font :Sets font type, style, size.
• Value :Indicates if unchecked (0, vbUnchecked), checked (1,vbChecked), or grayed out (2,
vbGrayed).
• Check Box Events:
• Click :Triggered when a box is clicked. Value property is automatically changed by Visual
Basic.
6. Option Buttons
• Option buttons provide the capability to make a mutually exclusive choice among a group of
potential candidate choices.
• Hence, option buttons work as a group, only one of which can have a True (or selected) value.
• Option Button Properties:
• Caption :Identifying text next to button.
• Font :Sets font type, style, size.
• Value :Indicates if selected (True) or not (False). Only one option button in a group can be
True. One button in each group of option buttons should always be initialized to True at design
time.
7. List Boxes
• A list box displays a list of items from which the user can select one or more items.
• If the number of items exceeds the number that can be displayed, a scroll bar is automatically
added.
• List Box Properties:
1. Appearance :Selects 3-D or flat appearance.
2. List :Array of items in list box.
3. ListCount :Number of items in list.
4. ListIndex :The number of the most recently selected item in list.If no item is
25
selected, ListIndex = -1. 5. MultiSelect :Controls how items may be selected (0-no multiple
selection allowed, 1-multiple selection allowed, 2-group selection allowed). 6. Selected :Array
with elements set equal to True or False, depending on whether corresponding list item is
selected. 7. Sorted :True means items are sorted in 'Ascii' order, else items appear in order added.
8. Text : Text of most recently selected item.
• List Box Events:
• Click :Event triggered when item in list is clicked.
• DblClick :Event triggered when item in list is double-clicked.Primary way used to process
selection.
• List Box Methods:
• AddItem :Allows you to insert item in list.
• Clear :Removes all items from list box.
• RemoveItem :Removes item from list box, as identified by index of item to remove.
• Examples
• lstExample.AddItem "This is an added item" ' adds text string to list
• lstExample.Clear ' clears the list box
• lstExample.RemoveItem 4 ' removes lstExample.List(4) from list box
8.Combo Boxes
• The combo box is similar to the list box.
• The differences are a combo box includes a text box on top of a list box and only allows
selection of one item.
• In some cases, the user can type in an alternate response.
• Combo Box Properties:
• Combo box properties are nearly identical to those of the list box, with the deletion of the
MultiSelect property and the addition of a Style property.
• Appearance Selects 3-D or flat appearance.
• List Array of items in list box portion.
• ListCount Number of items in list.
• ListIndex The number of the most recently selected item in list.If no item is
selected, ListIndex = -1.
• Sorted True means items are sorted in 'Ascii' order, else items appear in order added.
• Style Selects the combo box form.Style = 0, Dropdown combo; user can change selection.Style
= 1, Simple combo; user can change selection. Style = 2,
Dropdown combo; user cannot change selection.
• Text Text of most recently selected item.
• Combo Box Events:
• Click Event triggered when item in list is clicked.
• DblClick Event triggered when item in list is double-clicked. Primary way used to
process selection.
• Combo Box Methods:
• AddItem Allows you to insert item in list.
• Clear Removes all items from list box.
• RemoveItem Removes item from list box, as identified by index of item to remove.
• Examples
• cboExample.AddItem "This is an added item" ' adds text string to list
• cboExample.Clear ' clears the combo box
• cboExample.RemoveItem 4 ' removes cboExample.List(4) from list box

9.Horizontal and Vertical Scroll Bars

26
• Horizontal and vertical scroll bars are widely used in Windows applications.
• Scroll bars provide an intuitive way to move through a list of information and make great input
devices.
• Scroll Bar Properties:
1. LargeChange Increment added to or subtracted from the scroll bar Value property when the
bar area is clicked.
2. Max The value of the horizontal scroll bar at the far right and the value of the vertical scroll
bar at the bottom.Can range from -32,768 to 32,767.
3. Min The other extreme value - the horizontal scroll bar at the left and the vertical scroll bar at
the top. Can range from -32,768 to 32,767.
4. SmallChange The increment added to or subtracted from the scroll bar Value property when
either of the scroll arrows is clicked.
5. Value The current position of the scroll box (thumb) within the scroll bar. If you set this in
code, Visual Basic moves the scroll box to the proper position.

10.Picture Boxes
• The picture box allows you to place graphics information on a form.
• It is best suited for dynamic environments - for example, when doing animation.
• Picture boxes lie in the top layer of the form display.
• They behave very much like small forms within a form, possessing most of the same properties
as a form.
• Picture Box Properties:
1. AutoSize If True, box adjusts its size to fit the displayed graphic.
2. Font Sets the font size, style, and size of any printing done in the picture box.
3. Picture Establishes the graphics file to display in the picture box.
Picture Box Events:
 Click Triggered when a picture box is clicked.
 DblClick Triggered when a picture box is double-clicked.
• Example
• picExample.Picture = LoadPicture("c:\pix\sample.bmp")

11. Frames
• Frames provide a way of grouping related controls on a form. And, in the case of option
buttons, frames affect how such buttons operate.
27
• Option buttons within a frame work as a group, independently of option buttons in other
frames.
• Option buttons on the form, and not in frames, work as another independent group.
• That is, the form is itself a frame by default.
• It is important to note that an independent group of option buttons is defined by physical
location within frames, not according to naming convention.
• That is, a control array of option buttons does not work as an independent group just because it
is a control array.
• It would only work as a group if it were the only group of option buttons within a frame or on
the form .
12.Shape Tool
• The shape tool can create circles, ovals, squares, rectangles, and rounded squares and
rectangles.
• Colors can be used and various fill patterns are available.

• Shape Tool Properties:


1. BackColor Determines the background color of the shape (only used when FillStyle not Solid.
2. BackStyle Determines whether the background is transparent or opaque.
3. BorderColor Determines the color of the shape's outline.
4. BorderStyle Determines the style o the shape's outline. The border can be transparent, solid,
dashed, dotted, and combinations.
5. BorderWidth Determines the width of the shape border line.
6. fillColor Defines the interior color of the shape.
7. FillStyle Determines the interior pattern of a shape. Some choices are: solid, transparent, cross
8. Shape Determines whether the shape is a square, circle, or some other choice.

13. The Line Control


• Like the shape control, the line control is a graphical control.
• Line is use it to display horizontal, vertical, or diagonal lines in a form.
• We can use these controls at design time as a design element or at runtime to alter the original
line you drew.
• It can also change a line at runtime by changing its X1, X2, Y1, and Y2 properties.
• Line Tool Properties:
• BorderColor Determines the line color.

28
• BorderStyle Determines the line 'shape'. Lines can be transparent, solid, dashed,dotted,and
combinations.
• BorderWidth Determines line width.

14.The Timer Control


• You use a timer control when you want to execute code at specific intervals.
• Many times, especially in using graphics, we want to repeat certain operations at regular
intervals.
• The timer tool allows such repetition. The timer tool does not appear on the form while the
application is running.
• The Timer Properties:
• Enabled Used to turn the timer on and off. When on, it continues to operate until the Enabled
property is set to False.
Interval Number of milliseconds between each invocation of the Timer Event

Result:
Thus the study of various Visual Basic tools was done.

Experiment No: 8

Objective:

To implement the forms using front end tool and use oracle for database creation.
Procedure:
1.Create a table in sql.
2. Control Panel->All Control Panel Items->Administrative Tools->ODBC datasource->ODBC
Datasource admistrator->Add->Create new data source->Microsoft ODBC for Oracle-
>finish->Microsoft ODBC for oracle setup->give sourse name(table name),username then
click ok.
3.Open Microsoft visual basic 6.0->standard exe->open new project design a form
4.Project->Component->control ->choose Microsoft ADO data control 6.0(OLEDB)->apply
Designers->choose dataenvironment,data report ok
5.Tool box adodc there drag and drop into the form.
6.Right click adodc goto properties->gerenal->2 radio button use ODBC data source name-
>choose table name then ok.apply ,authentication->give user name & password-
>apply.goto record source->Command Type (2nd command table),next give table name-
>apply.
Goto general->3rd use connection string->build->datalink properties->Microsoft OLEDB
provider for ODBC driver->next connection under 1.datasource name,2.username &
password then give test connection ok .then property page apply ok.
4.Click the text box change the property datasource name adodc1,datafield name id.
5.tool->menu editor give caption name then ok.
6.Write the coding.
7.Project ->dataenvironment->properties test connection.dataenvironment right click add
command->command1 right click->properties->give dataobject(table),table name .
Sql stamen under give command Select * from table name; give apply ok.
8.Compile and run the program.

29
30
31
32
33
Experiment No: 9

Objective:

Triggers – To create a statement that executes automatically as a side effect of a


modification to the DB.
Database Triggers:-

Database triggers are procedures that are stored in the database and are implicitly
executed(fired) when the contents of a table are changed.

Use of Database Triggers:-


Database triggers support Oracle to provide a highly customized database management
system. Some of the uses to which the database triggers can be put to customize
management information in Oracle are as follows:-
• A Trigger can permit DML statements against a table any if they are issued,
during regular business hours or on predetermined weekdays.
• A trigger can also be used to keep an audit trail of a table along with the operation
performed and the time on which the operation was performed.
• It can be used to prevent invalid transactions.
• Enforce complex security authorizations.

How to apply DataBase Triggers:-

A trigger has three basic parts:-


1. A triggering event or statement.
2. A trigger restriction
3. A trigger action.
Types Of Triggers
There are three action query types that you use in SQL which are INSERT, UPDATE and
DELETE. So, there are three types of triggers and hybrids that come from mixing and
34
matching the events and timings that fire them. Basically, triggers are classified into two
main types:
● After Triggers (For Triggers)
● Instead Of Triggers
(i) After Triggers
These triggers run after an insert, update or delete on a table. They are not supported for
views.
AFTER TRIGGERS can be classified further into three types as:
● AFTER INSERT Trigger
● AFTER UPDATE Trigger
● AFTER DELETE Trigger
ii) Instead Of Triggers
These can be used as an interceptor for anything that anyone tried to do on our table or view. If
you define an Instead Of trigger on a table for the Delete operation, they try to delete rows, and
they will not actually get deleted (unless you issue another delete instruction from within the
trigger).
INSTEAD OF TRIGGERS can be classified further into three types as:
o INSTEAD OF INSERT Trigger
o INSTEAD OF UPDATE Trigger
o INSTEAD OF DELETE Trigger
Using the various options , four types of triggers can be created:-

1. Before Statement Trigger:- Before executing the triggering statement, the


trigger action is executed.
2. Before Row Trigger:- Before modifying the each row affected by the triggering
statement and before appropriate integrity constraints, the trigger is executed if
the trigger restriction either evaluated to TRUE or was not included.’
3. After Statement Trigger:- After executing the triggering statement and applying
any deferred integrity constraints, the trigger action is executed.
4. After row Trigger:- After modifying each row affected by the triggering
statement and possibly applying appropriate integrity constraints, the trigger
action is executed for the current row if the trigger restriction either evaluates to
TRUE or was not included.
Syntax For Creating Trigger:-

The syntax for Creating the Trigger is as follows:-

Create or replace Trigger<Triggername> {Before,After} {Delete, Insert, Update } On


<Tablename> For Each row when Condition
Declare
<Variable declarations>;
<Constant Declarations>;
Begin
<PL/SQL> Subprogram Body;
Exception
Exception Pl/SQL block;
End;

How to Delete a Trigger:-

The syntax for Deleting the Trigger is as follows:-


35
Drop Trigger <Triggername>;
TYPES OF TRIGGERS
The various types of triggers are as follows,

VARIABLES USED IN TRIGGERS


•:new
•:old

These two variables retain the new and old values of the column updated in the database. The
values in these variables can be used in the database triggers for data manipulation

Row Level Trigger vs. Statement Level Trigger:


Row Level Trigger Statement Level Trigger
These are fired for each row affected by These are fired once for the
statement
the DML statement. instead of the no of rows modified
by it.
These are used for generating/checking These are used for generated the
the values begin inserted or updated. Summary information.

Before trigger vs. after trigger

Before Triggers After Triggers


Before triggers are fired before the After triggers are fired after the
DML statement is actually executed. DML statement has finished execution.

Sytax:
Create or replace trigger <trg_name> Before /After Insert/Update/Delete
[of column_name, column_name….]
on <table_name>
[for each row]
[when condition]
begin
---statement
end;
Drop the Created Trigger Ans:
SQL> drop trigger triggername;

Experiment No:10

Objective:
Menu Design – To Design menus using menu editor in Visual Basic.
Procedure for doing the experiment:
Create a new project in VB
In the form window place the controls like Labels , text boxes in form
Go to Tools Menu Editor or right click on the form and select Menu Editor.
In the Menu Editor dialog box enter the values for caption, name and shortcut.
36
Select next to add a new menu item and delete to remove a menu item.
To add a sub menu select the right button in the Menu Editor dialog box and then
add the sub menus caption, name and shortcut.

Use ―-― in the name field to add a separator line inside a menu. After adding all
menu items select the OK button.

Double click the menu items in the form window to add the corresponding codes.
Similarly the codes are given to the text boxes and labels.
Execute the project by selecting Run Start.
After the debugging and successful execution of the project save the project and
make an executable file(*.exe) of it using the File menu.

37
38
Experiment No: 11

Objective:

Reports – To generate data report from existing DB

Procedure:
1 Create a new VB project as data project.
2 Right click connection1 of the data environment click the property, set the provideras Oracle
provider for OLEDB and click next then type user name as scott and password as
tiger. Check whether the connection is established using test connection button.
3 Right click connection, click the Add command for the connection1 and set database object
as table and object name as scott.emp
4 Drag command1and drop it in the data reports detail section1. Two items willappear for
each object. The first label for heading information. Move this label into page header
section. The label is used to store the actual value of the object.
5
In data report1 properties set data source data environment1 and the data member as
command1. Place a button in the form write coding to view the report.
Program:
Private Sub Command1_Click()
DataReport1.Show
End Sub
Private Sub Command2_Click()
Unload Me
End Sub

Output:

39
Experiment No: 7

Objective:
Minor Project (Application Development using Oracle/Mysql)

Title of the Project : DATABASE DESIGN AND IMPLEMENTATION PAY ROLL


PROCESSING
Aim:
To create a database for payroll processing system using SQL and implement it using VB

Procedure:

● Create a database for payroll processing which request the using SQL
● Establish ODBC connection
● In the administrator tools open data source ODBC
● Click add button and select oracle in ORA home 90,click finish
● A window will appear given the data source home as oracle and select TNS source
name as lion and give the used id as SWTT
● ADODC CONTROL FOR SALARY FORM:-
● The above procedure must be follow except the table ,A select the table as
40
salary
● Write appropriate Program in form each from created in VB from each from
created in VB form project.

Program:

SQL>create table emp(eno number primary key,enamr varchar(20),age number,addr


varchar(20),DOB date,phno number(10));

Table created.

SQL>create table salary(eno number,edesig varchar(10),basic number,da number,hra number,pf


number,mc number,met number,foreign key(eno) references emp);
Table created.

TRIGGER to calculate DA,HRA,PF,MC


SQL> create or replace trigger employ
after insert on salary
declare
cursor cur is select eno,basic from salary;
begin
for cur1 in cur loop
update salary set
hra=basic*0.1,da=basic*0.07,pf=basic*0.05,mc=basic*0.03 where hra=0;
end loop;
end;
/
Trigger created

PROGRAM FOR FORM 1


Private Sub emp_Click()

Form2.Show
End Sub

Private Sub exit_Click()


Unload Me

End Sub
Private Sub salary_Click()

Form3.Show
End Sub

PROGRAM FOR FORM 2

Private Sub add_Click()

Adodc1.Recordset.AddNew
MsgBox "Record added"

41
End Sub
Private Sub clear_Click()

Text1.Text = ""
Text2.Text = ""

Text3.Text = ""
Text4.Text = ""

Text5.Text = ""
Text6.Text = ""

End Sub
Private Sub delte_Click()
Adodc1.Recordset.Delete
MsgBox "Record Deleted"

If Adodc1.Recordset.EOF = True Then


Adodc1.Recordset.MovePrevious

End If
End Sub

Private Sub exit_Click()


Unload Me

End Sub
Private Sub main_Click()

Form1.Show
End Sub

Private Sub modify_Click()


Adodc1.Recordset.Update

End Sub

PROGRAM FOR FORM 3

Private Sub add_Click()


Adodc1.Recordset.AddNew

MsgBox "Record added"


End Sub

Private Sub clear_Click()


Text1.Text = ""

Text2.Text = ""
Text3.Text = ""

42
Text4.Text = ""
Text5.Text = ""

Text6.Text = ""
End Sub

Private Sub delte_Click()


Adodc1.Recordset.Delete

MsgBox "Record Deleted"


If Adodc1.Recordset.EOF = True Then

Adodc1.Recordset.MovePrevious
End If

End Sub
Private Sub exit_Click()

Unload Me
End Sub

Private Sub main_Click()


Form1.Show

End Sub

Private Sub modify_Click()


Adodc1.Recordset.Update

43
End Sub
OUTPUT:

44
Result:

Thus the design and implementation of payroll processing system using SQL, VB was
successfully done.

45

Potrebbero piacerti anche