manual for dbms lab

147
NANDHA ENGINEERING COLLEGE Perundurai Main Road, Erode-638 052. DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING CS2258 – DATABASE MANAGEMENT SYSTEM LABORATORY LAB MANUAL SUBMITTED BY : NAME :_____________________________ ____

Upload: kavitha-subramaniam

Post on 27-Apr-2017

336 views

Category:

Documents


2 download

TRANSCRIPT

NANDHA ENGINEERING COLLEGE

Perundurai Main Road, Erode-638 052.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CS2258 DATABASE MANAGEMENT SYSTEM LABORATORY

LAB MANUAL

SUBMITTED BY :

NAME :_________________________________

REG NO: _________________________________

CS 2258DATA BASE MANAGEMENT SYSTEM LAB L T P C0 03 21. Data Definition, Table Creation, Constraints,2. Insert, Select Commands, Update & Delete Commands.3. Nested Queries & Join Queries4. Views5. High level programming language extensions (Control structures, Procedures andfunctions).6. Front end tools7. Forms8. Triggers9. Menu Design10. Reports.11. Database Design and implementation (Mini Project).(Common to Information Technology & Computer Science Engineering)Hardware and Software required for a batch of 30 students:Hardware:30 Personal ComputersSoftware:Front end: VB/VC ++/JAVABack end: Oracle 11g, my SQL, DB2Platform: Windows 2000 Professional/XPOracle server could be loaded and can be connected from individual PCs.

INDEX

Ex.No.DATETITLE OF THE EXPERIMENTPAGEMARKSREMARKS

NO.

DATA DEFINITION LANGUAGE

1.COMMANDS

DATA MANIPULATION

2.LANGUAGE COMMANDS

3.INTEGRITY CONSTRAINTS

NESTED QUERIES AND JOIN

4.QUERIES

5.VIEWS

6.TRIGGERS

PROCEDURAL LANGUAGE

7.&STRUCTURED

QUERY LANGUAGE

8.FRONT END TOOLS

9.FORMS

10.MENU DESIGN

11.REPORTS

STUDENT MANAGEMENT

12.SYSTEM

AVERAGE MARKS AWARDED

82

Ex.No.1DATA DEFINITION LANGUAGE COMMANDS

Date:

AIM:

To write and execute DDL commands in SQL.

a) Create table. b) Alter table. c) Truncate table. d) Drop table.

e) Desc(to view the structure of the table)

DESCRIPTION:

a) CREATE

This command is used to create a table with the required fields.

Syntax:

create table (,

.);

SQL> create table stud (sname varchar2(30), sid varchar2(10), sage number(2), sarea varchar2(20));

Table created.

SQL> desc stud;NameNull? Type----------------------------------------------------- -------- --------------------------------SNAMEVARCHAR2(30)SIDVARCHAR2(10)SAGENUMBER(2)

SAREAVARCHAR2(20)

b) ALTER

This command is used to modify an existing attribute or to add a new attribute.

Syntax:

Altertable modify( column de

Altertable add (column defin

Alter table drop column column_name;

SQL>alter table stud modify ( sage number(10));

Table altered.

SQL> alter table stud add ( sdept varchar2(20));

Table altered.

SQL> desc stud;NameNull? Type----------------------------------------------------- -------- --------------------------------SNAMEVARCHAR2(30)

SIDVARCHAR2(10)

SAGENUMBER(10)

SAREAVARCHAR2(20)

SDEPTVARCHAR2(20)

SQL> alter table stud drop ( sdept varchar2(20));

Table altered.

SQL> desc stud;

NameNull?Type

----------------------------------------------------- -------- ------------------------------------SNAMEVARCHAR2(30)SIDVARCHAR2(10)SAGENUMBER(10)

SAREAVARCHAR2(20)

c) TRUNCATE

This command is to remove the records in the table and to retain the structure of the table. By adding the REUSE STORAGE clause at the end of the truncate table command, the allocated memory space can be reclaimed.

Syntax:

Truncate table ;

Truncate table reuse storage;

SQL> truncate table stud;

Table truncated.

SQL> desc stud;

NameNull?Type----------------------------------------------------- -------- ------------------------------------SNAMEVARCHAR2(30)SIDVARCHAR2(10)SAGENUMBER(10)SAREAVARCHAR2(20)

d) DROP

This command is to drop a table. It deletes both records and the structure of the table.

Syntax:

Drop table ;

SQL> drop table stud; Table dropped.

e) DESC or DESCRIBE

This command is to view the structure of the table at any point of time

Syntax:

Desc ;

RESULT

Thus the DDL commands were implemented and the output was verified.

Ex.No.2DATA MANIPULATION LANGUAGE COMMANDS

Date:

AIM:

To study the various categories of DML commands such as logical operations, aggregate functions, string functions, numeric functions, date functions, conversion functions and group functions, set operations.

DESCRIPTION

THE ORACLE TABLE DUAL

Dual is a small oracle table which consists of only one row and one column and contains the value X in that column.

INSERT

This command is used to insert the records into the already created table.

Syntax:

Insert into table_name values ( a list of data values );

Insertinto table_name values(&column1,

Insert into table_name(column names) values (list of values);

SELECT

This command is to retrieve the data stored in the tables.

Syntax:

Select * from table_name;

Select column_name from table_name;

Select column_name from table_name where ;

UPDATE

This command is used to reflect the changes to the records.

Syntax:

Update table_name set field_name=value where ;

DELETE

This command is used to delete unwanted records in the table.

Syntax:

Delete from table_name;

Delete from table_name where ;

RENAME

This command renames the name of the table.

ARITHMETIC OPERATIONS

Various operations such as addition, multiplication, subtraction and division can be performed using the numbers available in the table.

DISTINCT

This keyword is used along with select keyword to display unique values from the specified column. It avoids duplicates during display.

ORDER BY CLAUSE

The order by clause arranges the contents of the table in ascending order (by default) or in descending order (if specified explicitly) according to the specified column.

CONCATENATION OPERATOR

This combines information from two or more columns in a sentence according to the format specified.

LOGICAL OPERATORS

AND:The oracle engine will process all rows in a table and displays the result only when allof the conditions specified using the AND operator are specified.

ORThe :oracle engine will process all rows in a table and displays the result only when anyof the conditions specified using the OR operators are satisfied.

NOTThe oracle: engine will process all rows in a table and displays the result only whennone of the conditions specified using the NOT operator are specified. BETWEENInorder:to select data that is within a range of values, the between operator isused. (AND should be included)

PATTERN MATCH

LIKE PREDICATETheuseoflike predicate: is that it allows the comparison of one stringvalue with another string value, which is not identical. This is achieved by using wildcard characters which are % and _. The purpose of % is that it matches any string and _ matches any single character.

IN AND NOT IN ThePREDICATEarithmeticoperator =:compares a single value toanother single value. In case a value needs to be compared to a list of values then the in predicate is used.The not in predicate is the opposite of the in predicate. This will select all the rows whose values do not match all of the values in the list.

NUMERIC FUNCTIONS

ABS: It returns. the absolute value of n POWER: It returns m raised to nthturned . power. nROUND: It returns n rounded to m places ri rounded to zero places. m must be an integer.

SQRT: It returns square root of n. n should

STRING FUNCTIONS

LOWER: It returns char with letters in lowe INITCAP: It returns char with the first let UPPER: It returns char with all letters for SUBSTR: It returns a portiong upofton characters. If beginn n is omitted result is written up to the end character. The 1st position of char is one.

LENGTH: It returns the length of char LTRIM: It removes characters from the left

1st character not in set.

RTRIM: It returns char with final character is optional. It defaults to spaces.

LPAD: It returns char1, left padded to leng defaults to blanks.

RPAD: It returns char1, right padded to le many times as necessary. If char2 is omitted, it is padded with blanks.

AGGREGATE FUNCTIONS

AVG (N): It returnsnoringnull averagevalues. value of n ig MIN (EXPR): It returns minimum value of the COUNT (EXPR): It returns the number of rows COUNT (*): It returns the number of rows in null values.

MAX (EXPR): It returns maximum value of the SUM(N): It returns sum of values of n.

CONVERSION FUCTIONS

TO_NUMBER(CHAR): It converts the char value data type.

TO_CHAR(N,FMT): It converts a value of numb the optional format string. It accepts a number n and a numeric format fmt in which the number

has to appear. If fmt is omitted, n is converted to a char value exactly long enough to hold significant digits.

TO_CHAR(DATE, FMT): It converts a value of well as the format in which the date has to appear. Fmt must be a date format. If fmt is omitted,

date is the default date format.

DATE FUNCTIONS

SYSDATE : The sysdate is a pseudo column th no arguments when selected from the table dual and returns the current date.

ADD_MONTHS(D,N): It returnsnumberofmonthsdatespecified afterwiththe add function.

LAST_DAY(D): It returns the last date of th MONTHS_BETWEEN(D1,D2): It returns number of NEXT_DAY(DATE, CHAR): Itstweekreturnsdaynamedby charthe.char date must be a day of the week.

GROUP BY CLAUSE

The group by clause is another section of the select statement. This optional class tells oracle to group rows based on distinct values that exists for specified columns.

HAVING CLAUSE

The having clause can be used in conjunction with the group by clause. Having imposes a condition on the group by clause, which further filters the groups created by the group by clause.

SET OPERATIONS

UNION CLAUSE: Multiple queries can be put together and their output combined using the union clause. The union clause merges the output of two or more queries into a single set of rows and columns.

SET DIFFERENCE CLAUSE: Set difference returns all distinct rows selected only by the first query and not by the second.

INTERSECT CLAUSE: Multiple queries can be put together and their output can be combined using the intersect clause. The intersect clause outputs only rows produced by both the queries intersected. The output in an intersect clause will include only those rows that are retrieved by both the queries.

COMMANDS

CREATION OF TABLE

SQL> create table stud(sname varchar(15),sid varchar(5),sage number(5),sarea varchar(10),sdept varchar(10));

Table created.

INSERTION OF VALUES INTO THE TABLE

SQL> insert into stud values('&sname','&sid',&sage,'&sarea','&sdept'));

Enter value for sname: anu

Enter value for sid: 101

Enter value for sage: 19

Enter value for sarea: santhome

Enter value for sdept: cse

old 1: insert into stud values('&sname','&sid',&sage,'&sarea','&sdept')

new 1: insert into stud values('anu','101',19,'santhome','cse')

1 row created.

SQL> /

Enter value for sname: bala

Enter value for sid: 102

Enter value for sage: 18

Enter value for sarea: adayar

Enter value for sdept: marine

old 1: insert into stud values('&sname','&sid',&sage,'&sarea','&sdept')

new 1: insert into stud values('bala','102',18,'adayar','marine')

1 row created.

SQL> /

Enter value for sname: praveen

Enter value for sid: 103

Enter value for sage: 20

Enter value for sarea: santhome

Enter value for sdept: aerospace

old1: insert into stud values('&sname','&sid',&sage,'&sarea','&sdept')

new1: insert into stud values('praveen','103',20,'santhome','aerospace')

1 row created.

SQL> /

Enter value for sname: sabari

Enter value for sid: 104

Enter value for sage: 20

Enter value for sarea: tnagar

Enter value for sdept: civil

old 1: insert into stud values('&sname','&sid',&sage,'&sarea','&sdept')

new 1: insert into stud values('sabari','104',20,'tnagar','civil')

1 row created.

RENAMINGTHE TABLE STUD

SQL> rename stud to stud1;

Table renamed.

SQL> select * from stud1;

SNAMESIDSAGESAREASDEPT

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

anu10119santhomecse

bala10218adayarmarine

praveen10320santhomeaerospace

sabari10420tnagarcivil

ARITHMETIC OPERATION

SQL> select sname,sid+100 "stid" from stud1;

SNAMEstid

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

anu201

bala202

praveen203

sabari204

CONCATENATION OPERATOR

SQL> select sname || ' is a ' || sdept || ' engineer.' AS "PROFESSION" from stud1;

PROFESSION

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

anu is a cse engineer.

bala is a marine engineer.

praveen is a aerospace engineer.

sabari is a civil engineer.

DISPLAY ONLY DISTINCT VALUES

SQL> select distinct sarea from stud1;

SAREA

----------

adayar

santhome

tnagar

USING THE WHERE CLAUSE

SQL> select sname,sage from stud1 where sage select sname,sarea,sid from stud1 where sid between 102 and 104;

SNAMESAREASID

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

balaAdayar102

praveensanthome103

sabariTnagar104

IN PREDICATE

SQL> select sname,sarea,sid from stud1 where sid in(102,104);

SNAMESAREASID

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

balaAdayar102

sabariTnagar104

PATTERN MATCHING

SQL> select sname,sarea from stud1 where sarea like '%t%';

SNAMESAREA

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

anusanthome

praveensanthome

sabaritnagar

LOGICAL AND OPERATOR

SQL> select sname,sid from stud1 where sid>102 and sarea='santhome';

SNAMESID

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

praveen103

LOGICAL OR OPERATOR

SQL> select sname,sid from stud1 where sid>102 or sarea='santhome';

SNAMESID

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

anu101

praveen103

sabari104

NOT IN PREDICATE

SQL> select sname,sid from stud1 where sid not in(102,104);

SNAMESID

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

anu101

praveen103

UPDATING THE TABLE

SQL> alter table stud1 add(spocket varchar(5));

Table altered.

SQL> update stud1 set spocket=750 where sid=101;

1 row updated.

SQL> update stud1 set spocket=500 where sid=102;

1 row updated.

SQL> update stud1 set spocket=250 where sid=103;

1 row updated.

SQL> update stud1 set spocket=100 where sid=104;

1 row updated.

SQL> select * from stud1;

SNAMESIDSAGESAREASDEPTSPOCKET

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

anu10119santhomecse750

bala10218adayarmarine500

praveen10320santhomeaerospace250

sabari10420tnagarcivil100

AGGREGATE FUNCTIONS

SQL> select avg(spocket) result from stud1;

RESULT

----------

400

SQL> select min(spocket) result from stud1;

RESULT

-----

100

SQL> select count(spocket) result from stud1;

RESULT

----------

4

SQL> select count(*) result from stud1;

RESULT

----------

4

SQL> select count(spocket) result from stud1 where sarea='santhome';

RESULT

----------

2

SQL> select max(spocket) result from stud1;

RESULT

----------

750

SQL> select sum(spocket) result from stud1;

RESULT

----------

1600

NUMERIC FUNCTIONS

SQL> select abs(-20) result from dual;

RESULT

----------

20

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

RESULT

-----------

1024

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

RESULT

-----------

15.36

SQL> select sqrt(36) result from dual;

RESULT

----------

6

STRING FUNCTIONS

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

RESULT

-----------

oracle

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

RESULT

-----------

ORACLE

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

RESULT

----------

Oracle

SQL> select substr('oracle',2,5) result from dual;

RESULT

-----------

Oracle

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

RESULT

----------

####oracle

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

RESULT

----------

oracle$$$$

CONVERSION FUNCTIONS

SQL> update stud1 set sage=to_number(substr(118,2,3));

4 rows updated.

SQL> select * from stud1;

SNAMESIDSAGESAREASDEPTSPOCKET

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

anu10118santhomecse750

bala10218adayarmarine500

praveen10318santhomeaerospace 250

sabari10418tnagarcivil100

SQL> select to_char(17145,'099,999') result from dual;

RESULT

-----------

017,145

SQL> select to_char(sysdate,'dd-mon-yyyy') result from dual;

RESULT

-----------

03-mar-2012

DATE FUNCTIONS

SQL> select sysdate from dual;

SYSDATE

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

03-MAR-12

SQL> select sysdate,add_months(sysdate,4) result from dual;

SYSDATE RESULT

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

03-MAR-12 03-JUL-12

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

SYSDATE RESULT

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

03-MAR-12 31-MAR-12

SQL> select sysdate,next_day(sysdate,'sunday') result from dual;

SYSDATE RESULT

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

03-MAR-12 04-MAR-12

SQL> select months_between('09-aug-91','11-mar-90') result from dual;

RESULT

----------

16.9354839

GROUP BY CLAUSE

SQL> select sarea,sum(spocket) result from stud1 group by sarea;

SAREARESULT

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

adayar500

santhome1000

tnagar100

HAVING CLAUSE

SQL> select sarea,sum(spocket) result from stud1 group by sarea having sum(spocket) delete from stud1 where sid=101;

1 row deleted.

SQL> select * from stud1;

SNAMESIDSAGESAREASDEPTSPOCKET

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

bala10218adayarmarine500

praveen10318santhomeaerospace 250

sabari10418tnagarcivil100

SET OPERATIONS

TO CREATE PRODUCT TABLE

SQL> create table product(prodname varchar(10),prodno varchar(10));

Table created.

SQL> insert into product values('table',10001);

1 row created.

SQL> insert into product values('chair',10010);

1 row created.

SQL> insert into product values('desk',10110);

1 row created.

SQL> insert into product values('cot',11110); 1 row created.

SQL> insert into product values('sofa',10010); 1 row created.

SQL> insert into product values('tvstand',11010); 1 row created.

SQL> select * from product;

PRODNAME PRODNO

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

table10001

chair10010

desk10110

cot11110

sofa10010

tvstand11010

6 rows selected.

TO CREATE SALE TABLE

SQL> create table sale(prodname varchar(10),orderno number(5),prodno varchar(10)); Table created.

SQL> insert into sale values('&prodname',&orderno,'&prodno');

Enter value for prodname: table

Enter value for orderno: 801

Enter value for prodno: 10001

old 1: insert into sale values('&prodname',&orderno,'&prodno')

new 1: insert into sale values('table',801,'10001')

1 row created.

SQL> /

Enter value for prodname: chair

Enter value for orderno: 805

Enter value for prodno: 10010

old 1: insert into sale values('&prodname',&orderno,'&prodno')

new 1: insert into sale values('chair',805,'10010')

1 row created. SQL> /

Enter value for prodname: desk

Enter value for orderno: 809

Enter value for prodno: 10110

old 1: insert into sale values('&prodname',&orderno,'&prodno')

new 1: insert into sale values('desk',809,'10110')

1 row created. SQL> /

Enter value for prodname: cot

Enter value for orderno: 813

Enter value for prodno: 11110

old 1: insert into sale values('&prodname',&orderno,'&prodno')

new 1: insert into sale values('cot',813,'11110')

1 row created.

SQL> /

Enter value for prodname: sofa

Enter value for orderno: 817

Enter value for prodno: 10010

old 1: insert into sale values('&prodname',&orderno,'&prodno')

new 1: insert into sale values('sofa',817,'10010')

1 row created.

SQL> select * from sale;

PRODNAMEORDERNO PRODNO

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

table80110001

chair80510010

desk80910110

cot81311110

sofa81710010

SQL> select prodname from product where prodno=10010 union select prodname from sale where prodno=10010;

PRODNAME

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

chair

sofa

SQL> select prodname from product where prodno=11110 intersect select prodname from sale where prodno=11110;

PRODNAME

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

cot

SQL> select prodname from product where prodno=11010 minus select prodname from sale where prodno=11010;

PRODNAME

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

Tvstand

RESULT

Thus all the DML commands were executed and the output was verified.

EX No. 3INTEGRITY CONSTRAINTS

Date:

AIM:

To study the various constraints available in the SQL query language.

DESCRIPTION

INTEGRITY CONSTRAINTS

It is a mechanism used to prevent invalid data entry into table.

TYPES

1. Domain integrity constraints

2. Entity integrity constraints

3. Referential integrity constraints

DOMAIN INTEGRITY CONSTRAINTS

A domain is a set of values that may be assigned to an attribute. All values that appear in a column of a relation must be taken from the same domain.

TYPES

1. Not null constraint

2. Check constraint

NOT NULL CONSTRAINT:

It is used to enforce that the particular column will not accept null values.

CHECK CONSTRAINT:

It is used to specify the conditions that each row must satisfy.

Note: Not null and check constraints are column level constraints.

ENTITY INTEGRITY CONSTRAINTS

The entity integrity constraints states that no primary key value can be null. This is because the primary key value is used to identify individual tuples in a relation; having null values for the primary key implies that we cannot identify some tuples.

TYPES

1. Unique constraint

2. Primary key constraint

UNIQUE CONSTRAINT:

Unique constraint is used to prevent duplication of values, but it allows null value for the column.

PRIMARY KEY CONSTRAINT:

This is used to prevent duplication of values and it will not allow null value for the column.

REFERENTIAL INTEGRITY

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

This condition is called referential integrity.

Foreign key can be specified as part of the SQL creates table statement by using the foreign key values.

DOMAIN INTEGRITY CONSTRAINTS

NOT NULL CONSTRAINT

SQL> create table empl(ename varchar(15) not null,eid varchar(15) not null); Table created.

SQL> insert into empl values('anu',11); 1 row created.

SQL> insert into empl values('kumar',12); 1 row created.

SQL> insert into empl values('suda',null);

insert into empl values('suda',null)

*

ERROR at line 1:

ORA-01400: cannot insert NULL into ("SCOTT"."EMPL"."EID")

SQL> insert into empl values(null,13); insert into empl values(null,13)

*

ERROR at line 1:

ORA-01400: cannot insert NULL into ("SCOTT"."EMPL"."ENAME")

SQL> select * from empl;

ENAMEEID

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

anu11

kumar12

CHECK AS A COLUMN CONTRAINT

SQL> create table dept1(dname varchar(10) not null,did number(5) not null check(did insert into dept1 values('sales',9876); 1 row created.

SQL> insert into dept1 values('purchase',5432); 1 row created.

SQL> insert into dept1 values('accounts',78956); insert into dept1 values('accounts',78956)

*

ERROR at line 1:

ORA-02290: check constraint (SCOTT.SYS_C003013) violated

SQL> select * from dept1;

DNAMEDID

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

sales9876

purchase5432

CHECK AS A TABLE CONSTRAINT

SQL> create table airport(aname varchar(15) not null,aid number(5) not null,acity varchar(15),check(acity in('chennai','hyderabad','bangalore')));

Table created.

SQL> insert into airport values('national',100,'chennai'); 1 row created.

SQL> insert into airport values('gandhi',101,'hyderabad'); 1 row created.

SQL> insert into airport values('shiva',102,'bangalore'); 1 row created.

SQL> insert into airport values('keshav',103,'mumbai'); insert into airport values('keshav',103,'mumbai')

*

ERROR at line 1:

ORA-02290: check constraint (SCOTT.SYS_C003016) violated

SQL> select * from airport;

ANAMEAIDACITY

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

national100chennai

gandhi101hyderabad

shiva102bangalore

ENTITY INTEGRITY CONSTRAINTS

UNIQUE AS A COLUMN CONSTRAINT

SQL> create table book(bname varchar(15) not null,bid number(6) not null unique); Table created.

SQL> insert into book values('fairy tales',1000); 1 row created.

SQL> insert into book values('you can win',1001); 1 row created.

SQL> insert into book values('comics',1001); insert into book values('comics',1001)

*

ERROR at line 1:

ORA-00001: unique constraint (SCOTT.SYS_C003019) violated

SQL> select * from book;

BNAMEBID

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

fairy tales1000

you can win1001

UNIQUE AS A TABLE CONSTRAINT

SQL> create table orders(oname varchar(10) not null,oid number(10) not null,unique(oname,oid));

Table created.

SQL> insert into orders values('chair',2005); 1 row created.

SQL> insert into orders values('table',2006); 1 row created.

SQL> insert into orders values('chair',2007); 1 row created.

SQL> insert into orders values('chair',2005); insert into orders values('chair',2005)

*

ERROR at line 1:

ORA-00001: unique constraint (SCOTT.SYS_C003022) violated

SQL> select * from orders;

ONAMEOID

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

chair2005

table2006

chair2007

PRIMARY KEY AS A COLUMN CONSTRAINT

SQL> create table cust(cname varchar(10) not null,cid number(5) not null primary key);

Table created.

SQL> insert into cust values('jones',506);

1 row created.

SQL> insert into cust values('hayden',508);

1 row created.

SQL> insert into cust values('ricky',506);

insert into cust values('ricky',506)

*

ERROR at line 1:

ORA-00001: unique constraint (SCOTT.SYS_C003025) violated

SQL> select * from cust;

CNAMECID

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

jones506

hayden508

PRIMARY KEY AS A TABLE CONSTRAINT

SQL> create table branch(bname varchar(10) not null,bid number(5) not null, primary key(bname,bid));

Table created.

SQL> insert into branch values('santhome',1005); 1 row created.

SQL> insert into branch values('adyar',1006); 1 row created.

SQL> insert into branch values('santhome',1007); 1 row created.

SQL> insert into branch values('santhome',1005);

insert into branch values('santhome',1005)

*

ERROR at line 1:

ORA-00001: unique constraint (SCOTT.SYS_C003028) violated SQL> select * from branch;

BNAMEBID

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

santhome1005

adyar1006

santhome1007

REFERENTIAL INTEGRITY CONSTRAINTS

SQL> create table depts(city varchar(15),dno number(5) primary key); Table created.

SQL> insert into depts values('chennai',11); 1 row created.

SQL> insert into depts values('hyderabad',22); 1 row created.

SQL> create table semp(ename varchar(15),dno number(5) references depts(dno)); Table created.

SQL> insert into semp values('x',11); 1 row created.

SQL> insert into semp values('y',22); 1 row created.

SQL> select * from semp;

ENAMEDNO

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

x11

y22

SQL> alter table semp add(eaddress varchar(10));

Table altered.

SQL> update semp set eaddress='10 RK ROAD' where dno=11;

1 row updated.

SQL> update semp set eaddress='12 MG ROAD' where dno=22;

1 row updated.

SQL> select * from semp;

ENAMEDNOEADDRESS

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

x1110 RK ROAD

y2212 MG ROAD

SQL> select city,ename from depts,semp where depts.dno=semp.dno;

CITYENAME

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

chennaix

hyderabady

RESULT

Thus the various constraints were implemented and the tables were created using the respecting constraints. Hence the output was verified.

Ex.No.4NESTED QUERIES AND JOIN QUERIES

Date:

AIM:To study the nested queries and join queries.

DESCRIPTION:

Nested Query:Nested Queries are queries that contain another complete SELECT statements nested within it, that is, in the WHERE clause. The nested SELECT statement is called an inner query or an inner SELECT. The main query is called outer SELECT or outer query. Many nested queries are equivalent to a simple query using JOIN operation. The use of nested query in this case is to avoid explicit coding of JOIN which is a very expensive database operation and to improve query performance. However, in many cases, the use of nested queries is necessary and cannot be replaced by a JOIN operation. JoinA join is a query that combines rows from two or more tables, views, or materialized views. Oracle Database performs a join whenever multiple tables appear in the FROM clause of the query. The select list of the query can select any columns from any of these tables. If any two of these tables have a column name in common, then you must qualify all references to these columns throughout the query with table names to avoid ambiguity.

Types of Joins:

INNER JOIN/ NATURAL JOIN/ JOIN: It is a binary operation that allows us to combinecertain selections and a Cartesian product into one operation.

CROSS JOIN: It is a JOIN operation that produces the Cartesian product of two tables.

OUTER JOIN: It is an extension of join operation to deal with missing information.

Left Outer Join: It takes tuples in the left relation that did not match with anytuple in the right relation, pads the tuples with null values for all other attributes from the right relation and adds them to the result of the natural join.

Right Outer Join: It takes tuples in the right relation that did not match with anytuple in the left relation, pads the tuples with null values for all other attributes from the left relation and adds them to the result of the natural join.

Full Outer Join: It combines tuples from both the left and the right relation andpads the tuples with null values for the missing attributes and them to the result of thenatural join.

COMMANDS

NESTED QUERIES

SQL> create table empdetail (emp_id number primary key,emp_name varchar(15),phone_no number,job_id varchar(15),salary number);

Table created.

SQL> insert into empdetail values(&emp_id,'&emp_name',&phone_no,'&job_id',&salary); Enter value for emp_id: 100

Enter value for emp_name: steve Enter value for phone_no: 147895 Enter value for job_id: IT-PROG Enter value for salary: 9000

old 1: insert into empdetail values(&emp_id,'&emp_name',&phone_no,'&job_id',&salary) new 1: insert into empdetail values(100,'steve',147895,'IT-PROG',9000)

1 row created. SQL> /

Enter value for emp_id: 101 Enter value for emp_name: john Enter value for phone_no: 789542 Enter value for job_id: VP

Enter value for salary: 50000

old 1: insert into empdetail values(&emp_id,'&emp_name',&phone_no,'&job_id',&salary) new 1: insert into empdetail values(101,'john',789542,'VP',50000)

1 row created. SQL> /

Enter value for emp_id: 141 Enter value for emp_name: peter

Enter value for phone_no: 456321 Enter value for job_id: ST-CLERK Enter value for salary: 3500

old 1: insert into empdetail values(&emp_id,'&emp_name',&phone_no,'&job_id',&salary) new 1: insert into empdetail values(141,'peter',456321,'ST-CLERK',3500)

1 row created. SQL> /

Enter value for emp_id: 142 Enter value for emp_name: davies Enter value for phone_no: 741258

Enter value for job_id: ST-CLERK Enter value for salary: 3100

old 1: insert into empdetail values(&emp_id,'&emp_name',&phone_no,'&job_id',&salary) new 1: insert into empdetail values(142,'davies',741258,'ST-CLERK',3100)

1 row created. SQL> /

Enter value for emp_id: 143

Enter value for emp_name: william Enter value for phone_no: 632548 Enter value for job_id: ST-CLERK Enter value for salary: 2600

old 1: insert into empdetail values(&emp_id,'&emp_name',&phone_no,'&job_id',&salary) new 1: insert into empdetail values(143,'william',632548,'ST-CLERK',2600)

1 row created.

SQL> /

Enter value for emp_id: 144

Enter value for emp_name: michael

Enter value for phone_no: 325874

Enter value for job_id: SA-REP

Enter value for salary: 8600

old 1: insert into empdetail values(&emp_id,'&emp_name',&phone_no,'&job_id',&salary)

new 1: insert into empdetail values(144,'michael',325874,'SA-REP',8600)

1 row created.

SQL> SELECT * FROM EMPDETAIL;

EMP_ID EMP_NAMEPHONE_NOJOB_IDSALARY

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

100steve147895IT-PROG9000

101john789542VP50000

141peter456321ST-CLERK3500

142davies741258ST-CLERK3100

143william632548ST-CLERK2600

144michael325874SA-REP8600

6 rows selected.

Display the employee whose job id is the same as the employee 141.

SQL> select emp_name,job_id from empdetail where job_id=(select job_id from empdetail where emp_id=141);

EMP_NAMEJOB_ID

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

peterST-CLERK

daviesST-CLERK

williamST-CLERK

Display the employee whose job is same as that of employee 141 and whose salary is greater than that of 143.

SQL> select emp_name,job_id,salary from empdetail where job_id=(select job_id from empdetail where emp_id=141) and salary > (select salary from empdetail where emp_id=143);

EMP_NAMEJOB_IDSALARY

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

peterST-CLERK3500

daviesST-CLERK3100

JOINS

SQL> create table emp1(empname varchar(15),deptid number);

Table created.

SQL> insert into emp1 values('&empname',&deptid);

Enter value for empname: sita

Enter value for deptid: 1

old 1: insert into emp1 values('&empname',&deptid);

new 1: insert into emp1 values('sita',1)

1 row created. SQL> /

Enter value for empname: suda Enter value for deptid: 2

old 1: insert into emp1 values('&empname',&deptid);

new 1: insert into emp1 values('suda',2)

1 row created. SQL> /

Enter value for empname: kumar Enter value for deptid: 3

old 1: insert into emp1 values('&empname',&deptid); new 1: insert into emp1 values('kumar',3)

1 row created. SQL> /

Enter value for empname: john

Enter value for deptid: null

old 1: insert into emp1 values('&empname',&deptid);

new 1: insert into emp1 values('john',null)

1 row created.

SQL> /

Enter value for empname: smith

Enter value for deptid: 3

old 1: insert into emp1 values('&empname',&deptid);

new 1: insert into emp1 values('smith',3)

1 row created.

SQL> select * from emp1;

EMPNAMEDEPTID

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

sita1

suda2

kumar3

johnNULL

smith3

SQL> commit; Commit complete.

SQL> create table dept1(deptid number,deptname varchar(15)); Table created.

SQL> insert into dept1 values(&deptid,'&deptname'); Enter value for deptid: 1

Enter value for deptname: sales

old 1: insert into dept1 values(&deptid,'&deptname') new 1: insert into dept1 values(1,'sales')

1 row created.

SQL> /

Enter value for deptid: 2

Enter value for deptname: cse

old 1: insert into dept1 values(&deptid,'&deptname')

new 1: insert into dept1 values(2,'cse')

1 row created. SQL> /

Enter value for deptid: 3

Enter value for deptname: eee

old 1: insert into dept1 values(&deptid,'&deptname')

new 1: insert into dept1 values(3,'eee')

1 row created.

SQL> /

Enter value for deptid: 5

Enter value for deptname: civil

old 1: insert into dept1 values(&deptid,'&deptname')

new 1: insert into dept1 values(5,'civil')

1 row created.

SQL> select * from dept1;

DEPTIDDEPTNAME

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

1sales

2cse

3eee

5civil

SQL> commit;

Commit complete.

INNER JOIN

SQL> select * from emp1 INNER JOIN dept1 ON emp1.deptid=dept1.deptid;

EMPNAMEDEPTIDDEPTIDDEPTNAME

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

sita11sales

suda22cse

kumar33eee

smith33eee

NATURAL JOIN

SQL> select * from emp1 NATURAL JOIN dept1;

DEPTIDEMPNAMEDEPTNAME

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

1sitasales

2sudacse

3kumareee

3smitheee

CROSS JOIN

SQL> select * from emp1 CROSS JOIN dept1;

EMPNAMEDEPTIDDEPTIDDEPTNAME

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

sita11sales

suda21sales

kumar31sales

johnNULL1sales

smith31sales

sita12cse

suda22cse

kumar32cse

john2cseNULL

smith32cse

sita13eee

EMPNAMEDEPTIDDEPTIDDEPTNAME

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

suda23eee

kumar33eee

john3eeeNULL

smith33eee

sita15civil

suda25civil

kumar35civil

john5NULLcivil

smith35civil

20 rows selected.

OUTER JOIN

LEFT OUTER JOIN

SQL> select * from emp1 LEFT OUTER JOIN dept1 ON emp1.deptid=dept1.deptid;

EMPNAMEDEPTIDDEPTIDDEPTNAME

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

sita11sales

suda22cse

smith33eee

kumar33eee

johnNULLNULLNULL

RIGHT OUTER JOIN

SQL> select * from emp1 RIGHT OUTER JOIN dept1 ON emp1.deptid=dept1.deptid;

EMPNAMEDEPTIDDEPTIDDEPTNAME

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

sita11sales

suda22cse

kumar33eee

smith33eee

NULLNULL5civil

FULL OUTER JOIN

SQL> select * from emp1 FULL OUTER JOIN dept1 ON emp1.deptid=dept1.deptid;

EMPNAMEDEPTIDDEPTIDDEPTNAME

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

sita11sales

suda22cse

smith33eee

kumar33eee

johnNULLNULLNULL

NULLNULL5civil

6 rows selected.

RESULT

Thus the nested queries and join queries were implemented and the output was verified.

EX No: 5VIEWS

Date:

AIM:To create views for the table and perform operations on it.

DEFINITION

A view is an object that gives the user the logical view of data from the underlying table. Any relation that is not part of the logical model but is made visible to the user as a virtual relation is called a view. They are generally used to avoid duplication of data.

Views are created for the following reasons,

Data simplicity

To provide data security

Structural simplicity (because view contains only limited number of rows and colmns)

TYPES OF VIEWS

Updatable views Allow data manipulation

Read only views Do not allow data manipulation

CREATION OF VIEWS:

SYNTAX:

CREATE VIEW viewname as

SELECT columname,columnname

FROM tablename

WHERE columnname=expression list;

DESTROYING A VIEW

A view can be dropped by using the DROP VIEW command

SYNTAX:

DROP VIEW viewname;

TO CREATE THE TABLE FVIEWS

SQL> create table fviews( name varchar2(10),no number(5), sal number(5), dno number(5)); Table created.

SQL> insert into fviews values('abinav',1,19000,11); 1 row created.

SQL> insert into fviews values('ritu',2,19000,12); 1 row created.

SQL> insert into fviews values('kumar',3,40000,13); 1 row created.

SQL> select * from fviews;

NAMENOSALDNO

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

abinav11900011

ritu21900012

kumar34000013

TOCREATE THE TABLE DVIEWS

SQL> create table dviews( dno number(5), dname varchar(10));

Table created.

SQL> insert into dviews values(11,'arun');

1 row created.

SQL> insert into dviews values(12,'suda');

1 row created.

SQL> select * from dviews;

DNODNAME

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

11 arun

12 suda

CREATINGTHE IEWVIEW ONSVFVIEWS TABLE

SQL> create view sview as select name,no,sal,dno from fviews where dno=11; View created.

SQL> select * from sview;

NAMENOSALDNO

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

abinav11900011

UPDATES MADE ON THE VIEW ARE REFLECTED ONLY ON THE TABLE WHEN THE STRUTURE OF THE TABLE AND THE VIEW ARE NOT SIMILAR PROOF

SQL> insert into sview values ('raji',4,20000,14); 1 row created.

SQL> select * from sview;

NAMENOSALDNO

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

abinav11900011

SQL> select * from fviews;

NAMENOSALDNO

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

abinav11900011

ritu21900012

kumar34000013

raji42000014

UPDATES MADE ON THE VIEW ARE REFLECTED ON BOTH THE VIEW AND THE TABLE WHEN THE STRUTURE OF THE TABLE AND THE VIEW ARE SIMILAR PROOF

CREATINGA VIEW IVIEW FOR THE TABLE FVIEWS

SQL> create view iview as select * from fviews;

View created.

SQL> select * from iview;

NAMENOSALDNO

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

abinav11900011

ritu21900012

kumar34000013

raji42000014

PERFORMING UPDATE OPERATION

SQL> insert into iview values ('boni',5,30000,15);

1 row created.

SQL> select * from iview;

NAMENOSALDNO

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

abinav11900011

ritu21900012

kumar34000013

raji42000014

boni53000015

CREATEA NEW VIEW SSVIEW AND DROP THE VIEW

SQL> create view ssview( cusname,id) as select name, no from fviews where dno=12;

View created.

SQL> select * from ssview;

CUSNAMEID

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

ritu2

SQL> drop view ssview;

View dropped.

TO CREATE A VIEW COMBO USING BOTH THE TABLE DVIEWS

SQL> create view combo as select name,no,sal,dviews.dno,dname from fviews,dviews where fviews.dno=dviews.dno;

View created.

SQL> select * from combo;

NAMENOSALDNODNAME

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

abinav11900011arun

ritu21900012suda

TO PERFORM MANIPULATIONS ON THIS VIEW

SQL> insert into combo values('john',12,1000,13,'x'); insert into combo values('john',12,1000,13,'x')

*

ERROR at line 1:

ORA-01779: cannot modify a column which maps to a non key-preserved table

This shows that when a view is created from two different tables no manipulations can be performed using that view and the above error is displayed.

RESULTThus views were created, various operations were performed and the outputs were

verified.

Ex.No.6TRIGGERS

Date:

AIM:To study and implement the concept of triggers.

DEFINITION

A trigger is a statement that is executed automatically by the system as a sideeffect of a modification to the database. The parts of a trigger are,

Trigger statement: Specifies the DML statements and fires the trigger body. It alsospecifies the table to which the trigger is associated.

Trigger body or trigger action: It is a PL/SQL block that is executed when thetriggering statement is used.

Trigger restriction: Restrictions on the trigger can be achieved

The different uses of triggers are as follows,

To generate data automatically

To enforce complex integrity constraints

To customize complex securing authorizations

To maintain the replicate table

To audit data modifications

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

SYNTAXThe Syntax for creating a trigger is:

CREATE [OR REPLACE ] TRIGGER trigger_name {BEFORE | AFTER | INSTEAD OF }

{INSERT [OR] | UPDATE [OR] | DELETE} [OF col_name]

ON table_name

[REFERENCING OLD AS o NEW AS n] [FOR EACH ROW]

WHEN (condition) BEGIN--- sql statements

END;

CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a trigger withthe given name or overwrites an existing trigger with the same name.

{BEFORE | AFTER | INSTEAD OF }- This clause indicates at what time should thetrigger get fired. i.e for example: before or after updating a table. INSTEAD OF is used to create a trigger on a view. before and after cannot be used to create a trigger on a view. {INSERT [OR] | UPDATE [OR] | DELETE} - This clause determines the triggeringevent. More than one triggering events can be used together separated by OR keyword. The trigger gets fired at all the specified triggering event.

[OF col_name] - This clause is used with update triggers. This clause is used when youwant to trigger an event only when a specific column is updated.

CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a trigger withthe given name or overwrites an existing trigger with the same name.

[ON table_name] - This clause identifies the name of the table or view to which thetrigger is associated.

[REFERENCING OLD AS o NEW AS n] - This clause is used to reference the old andnew values of the data being changed. By default, you reference the values as :old.column_name or :new.column_name. The reference names can also be changed from old (or new) to any other user-defined name. You cannot reference old values when inserting a record, or new values when deleting a record, because they do not exist. [FOR EACH ROW] - This clause is used to determine whether a trigger must fire wheneach row gets affected ( i.e. a Row Level Trigger) or just once when the entire sql statement is executed(i.e.statement level Trigger).

WHEN (condition) - This clause is valid only for row level triggers. The trigger is firedonly for rows that satisfy the condition specified.

COMMANDS

SQL> create table trigsample(name varchar(10),eid number(3),salary number(10)); Table created.

SQL> insert into trigsample values('kelvin',101,12000); 1 row created.

SQL> insert into trigsample values('suda',102,13000); 1 row created.

SQL> insert into trigsample values('ritu',103,15500); 1 row created.

SQL> select * from trigsample;

NAMEEIDSALARY

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

kelvin10112000

suda10213000

ritu10315500

SQL> create trigger t1 before insert or update or delete on trigsample for each row

2 begin

3 raise_application_error(-20010,'You cannot do any manipulation');

4 end;

5 /

Trigger created.

SQL> insert into trigsample values('jaya',104,25000);

insert into trigsample values('jaya',104,25000)

*

ERROR at line 1:

ORA-20010: You cannot do any manipulation

ORA-06512: at "SCOTT.T1", line 2

ORA-04088: error during execution of trigger 'SCOTT.T1'

SQL> delete from trigsample where name='suda'; delete from trigsample where name='suda'

*

ERROR at line 1:

ORA-20010: You cannot do any manipulation

ORA-06512: at "SCOTT.T1", line 2

ORA-04088: error during execution of trigger 'SCOTT.T1'

SQL> update trigsample set eid=107 where name='suda';

update trigsample set eid=107 where name='suda'

*

ERROR at line 1:

ORA-20010: You cannot do any manipulation ORA-06512: at "SCOTT.T1", line 2

ORA-04088: error during execution of trigger 'SCOTT.T1'

RESULT

Thus the trigger commands are executed and output was verified.

Ex No.7PROCEDURAL LANGUAGE / STRUCTURED

Date:QUERY LANGUAGE

AIM:

To write PL/SQL programs that executes the concept of control structures, functions and procedures.

DEFINITION

A procedure or function is a logically grouped set of SQL and PL/SQL statements that perform a specific task. They are essentially sub-programs. Procedures and functions are made up of,

Declarative part

Executable part

Optional exception handling part

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. Paranthesis 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 its 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 its calling environment after

execution.

RETURN: It is the datatype of the functions return value because every function must return avalue, this clause is required.

PROCEDURES SYNTAX

create or replace procedure (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 (a variable declaration;

constant declaration; begin

PL/SQL subprogram body; exception

exception PL/SQL block; end;

SIMPLE PL/SQL PROGRAMS

GREATEST OF THREE NUMBERS

SQL> set serveroutput onSQL> declare

2 a number; 3 b number; 4 c number; 5 begin 6 a:=&a; 7 b:=&b; 8 c:=&c; 9 if a=b and b=c and c=a then 10 dbms_output.put_line('all are equal'); 11 elsif a>b and a>c then 12 dbms_output.put_line('a is greater'); 13 elsif b>c then 14 dbms_output.put_line('b is greater'); 15 else 16 dbms_output.put_line('c is greater'); 17 end if; 18 end; 19 /

Enter value for a: 5 old 6: a:=&a; new 6: a:=5; Enter value for b: 7 old 7: b:=&b; new 7: b:=7; Enter value for c: 2 old 8: c:=&c; new 8: c:=2;

b is greater

PL/SQL procedure successfully completed.

TO SWAP TWO NUMBERS

SQL> set serveroutput onSQL> declare2 a number(10); 3 b number(10); 4 begin 5 a:=&a; 6 b:=&b; 7 dbms_output.put_line(Values of a and b be 8 dbms_output.put_line(a); 9 dbms_output.put_line(b);

10 a:=a+b; 11 b:=a-b; 12 a:=a-b; 13 dbms_output.put_line('Values of a and b after swaping'); 14 dbms_output.put_line(a); 15 dbms_output.put_line(b); 16 end; 17 /

Enter value for a: 2 old 5: a:=&a; new 5: a:=2; Enter value for b: 3 old 6: b:=&b; new 6: b:=3;

Values of a and b before swaping 2 3

Values of a and b before swaping 3 2

PL/SQL procedure successfully completed.

TO CHECK WHETHER GIVEN NUMBER IS ARMSTRONG OR NOT

SQL> set serveroutput onSQL> declare2 a number; 3 t number; 4 arm number; 5 d number; 6 begin

7 a:=&a; 8 t:=a;

9 arm:=0;

10 while t>0 11 loop 12 d:=mod(t,10); 13 arm:=arm+power(d,3); 14 t:=trunc(t/10); 15 end loop; 16 if arm=a then 17 dbms_output.put_line('given no is an armstrong no'||a); 18 else

19 dbms_output.put_line('given no is not an armstrong no');

20 end if; 21 end; 22 /

Enter value for a: 6 old 7: a:=&a; new 7: a:=6;given no is not an armstrong no

PL/SQL procedure successfully completed. SQL> /

Enter value for a: 407 old 7: a:=&a;

new 7: a:=407;given no is an armstrong no407

PL/SQL procedure successfully completed.

TO FIND THE SUM OF THE DIGITS

SQL> set serveroutput onSQL> declare2 a number; 3 d number:=0; 4 sum1 number:=0; 5 begin 6 a:=&a; 7 while a>0 8 loop

9 d:=mod(a,10); 10 sum1:=sum1+d; 11 a:=trunc(a/10); 12 end loop;

13 dbms_output.put_line('sum is'||sum1); 14 end;

15 /

Enter value for a: 123 old 6: a:=&a;

new 6: a:=123; sum is6

PL/SQL procedure successfully completed. SQL> /

Enter value for a: 1023 old 6: a:=&a;

new 6: a:=1023; sum is6

PL/SQL procedure successfully completed.

TO REVERSE THE GIVEN NUMBER

SQL> set serveroutput onSQL> declare2 a number; 3 rev number; 4 d number; 5 begin 6 a:=&a; 7 rev:=0; 8 while a>0 9 loop 10 d:=mod(a,10); 11 rev:=(rev*10)+d; 12 a:=trunc(a/10); 13 end loop; 14 dbms_output.put_line('no is'||rev); 15 end; 16 /

Enter value for a: 876 old 6: a:=&a;

new 6: a:=876; no is678

PL/SQL procedure successfully completed.

PROCEDURES

CREATINGTHE TABLE ITITEMS AND DISPLAYING T

SQL> create table ititems(itemid number(3),actualprice number(5),ordid number(4),prodid number(4));

Table created.

SQL> insert into ititems values(101,2000,500,201); 1 row created.

SQL> insert into ititems values(102,3000,1600,202); 1 row created.

SQL> insert into ititems values(103,4000,600,202); 1 row created.

SQL> select * from ititems;

ITEMIDACTUALPRICEORDIDPRODID

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

1012000500201

10230001600202

1034000600202

PROGRAM FOR GENERAL PROCEDURE SELECTED RECORDSPRICE I 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;

ITEMIDACTUALPRICEORDIDPRODID

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

1012500500201

10230001600202

1034000600202

PROCEDURE FOR IN PARCREATION,METEREXECUTION

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.

SQL> exec yyy(103);

Actual price is 4000

PL/SQL procedure successfully completed.

PROCEDUREFOR OUTCREATION,PARAMETEREXECUTION

SQL> create procedure zzz1(a in number,b out number) is identity number;

2 begin

3 select ordid into identity from ititems where itemid=a;

4 if identity declare

2 a number ;

3 b number;

4 begin

5 zzz1(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.

PROCEDUREFOR INOUTCREATION,PARAMETEREXECUTION

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.

FUNCTIONS

CREATETHE TABLE ITTRAIN1 TO BE USED FOR FU

SQL> create table ittrain1(tno number(10),tfare number(10)); Table created.

SQL> insert into ittrain1 values(1001,550); 1 row created.

SQL> insert into ittrain1 values(1002,600); 1 row created.

SQL> select * from ittrain1; TNO TFARE

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

1001550

1002600

PROGRAM FOR FUNCTION AND ITS EXECUTION

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

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> set serverouptut on;

SQL> declare

2 total number;

3 begin

4 total:=f1(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 itfact1(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 itfact1;

13 /

Function created.

SQL> set serveroutput on;

SQL> declare

2 a number:=7;

3 f number(10);

4 begin

5 f:=itfact1(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

PL/SQL procedure successfully completed.

RESULT

Thus the PL/SQL programs were executed and their outputs were verified.

EX: NO:8FRONT END TOOLS

Date:

AIM:

To design a form using different tools in Visual Basic.

PROCEDURE

STEP 1: Start

STEP 2: Create the form with essential controls in tool box. STEP 3: Write the code for doing the appropriate functions. STEP 4: Save the forms and project.

STEP 5: Execute the form. STEP 6: Stop

CODING:

Private Sub Calendar1_Click()

Text3.Text = Calendar1.Value

End Sub

Private Sub Combo1_Change()

Combo1.AddItem "BSC"

Combo1.AddItem "MSC"

Combo1.AddItem "BE"

Combo1.AddItem "ME"

End Sub

Private Sub Command1_Click() List1.AddItem Text1.Text List1.AddItem Text2.Text

If Option1.Value = True Then gender = "male"

End If

If Option2.Value = True Then gender = "female"

End If

List1.AddItem gender List1.AddItem Text3.Text

If Check1.Value = 1 And Check2.Value = 1 Then area = "software Engineering & Networks"

End If

If Check1.Value = 0 And Check2.Value = 1 Then area = " Networks"

End If List1.AddItem area

List1.AddItem Text4.Text End Sub

Private Sub Command2_Click()

End

End Sub

Private Sub Command3_Click()

If List1.ListIndex 0 Then

List1.RemoveItem (0)

End If

End Sub

Private Sub Form_Load()

Label10.Caption = Date$

MsgBox "Welcome to Registration"

End Sub

Private Sub Option1_Click()

If (Option1.Value = True) Then MsgBox ("You have selected Male") ElseIf (Option2.Value = True) Then MsgBox ("You have selected Female") End If

End Sub

Private Sub Option2_Click()

If (Option1.Value = True) Then MsgBox ("You have selected Male") ElseIf (Option2.Value = True) Then MsgBox ("You have selected Female") End If

End Sub

RESULT: Thus the program has been loaded and executed successfully.

Ex No.9FORMS

Date:

AIM:

To design form for calculator program in VB

ALGORITHM

1. Open the form in VB.

2. Place five command buttons, give the name for command buttons as in the form and two text box in the form.

3. Click the button, it will display the code page.

4. Enter the code for corresponding button.

5. Execute the program by clicking run in menu.

CODING

Private Sub add_Click()

Dim a As Integer

a = Val(Text1.Text) + Val(Text2.Text) MsgBox ("Addition of two umbers is" + Str(a)) End Sub

Private Sub div_Click()

Dim d As Integer

d = Val(Text1.Text) / Val(Text2.Text) MsgBox ("Division of two umbers is" + Str(d)) End Sub

Private Sub end_Click()

End

End Sub

Private Sub mul_Click() Dim c As Integer

c = Val(Text1.Text) * Val(Text2.Text)

MsgBox ("Multiplication of two umbers is" + Str(c)) End Sub

Private Sub sub_Click() Dim b As Integer

b = Val(Text1.Text) - Val(Text2.Text)

MsgBox ("Subtraction of two umbers is" + Str(b)) End Sub

OUTPUT

RESULT

Thus the form design program for calculator was executed and output was verified

EX No.10MENU DESIGN

Date:

AIM:

To create menu design in visual basic.

ALGORITHM

1. A new standard EXE project is opened and the form, project files are saved.

2. The form is designed.

3. Select the menu editor fromFile,Font style,andtoolsFont. menu, cr

4. Select Microsoft Rich Textbox Control 6.0 and Microsoft Common Dialog Control 6. from components.

5. Enter the code for corresponding menu.

6. Execute the program by clicking run in menu.

CODING

Private Sub bg_Click()

CommonDialog1.Action = 3

RichTextBox1.BackColor = CommonDialog1.Color

End Sub

Private Sub farial_Click()

RichTextBox1.Font = "Arial"

End Sub

Private Sub fbold_Click()

RichTextBox1.SelBold = True

End Sub

Private Sub fexit_Click()

End

End Sub

Private Sub fitalic_Click()

RichTextBox1.SelItalic = True

End Sub

Private Sub fnew_Click()

RichTextBox1.Text = ""

RichTextBox1.SetFocus

End Sub

Private Sub fopen_Click() CommonDialog1.Action = 1

RichTextBox1.FileName = CommonDialog1.FileName End Sub

Private Sub fprint_Click()

CommonDialog1.Action = 5

End Sub

Private Sub fsave_Click() CommonDialog1.Action = 2

RichTextBox1.SaveFile CommonDialog1.FileName End Sub

Private Sub ftnr_Click() RichTextBox1.Font = "Times New Roman" End Sub

Private Sub funder_Click()

RichTextBox1.SelUnderline = True

End Sub

Private Sub mfg_Click() CommonDialog1.Action = 3

RichTextBox1.SelColor = CommonDialog1.Color End Sub

Private Sub msizw_Click() Dim size As Integer

size = InputBox("Enter the font size") RichTextBox1.SelFontSize = size End Sub

OUTPUT

RESULT

Thus the menu design program in VB was executed and output was verified.

EX No.11REPORTS

Date:

AIM:

To generate data report using visual basic as front end tool and oracle as back end tool.

ALGORITHM

1. A new standard EXE project is opened.

2. On the project menu, click Add Data Environment. If this item is not on the menu, click components. Click the designers tab, and choose Data Environment and click ok to add the designer to your menu.

3. In the Data Environment window right click the Connection1 tab and select properties. In the data link properties dialog box,select Microsoft OLE DB Provider for ODBC drivers. Click next to get the connection tab. Select data source name, enter the user name and password and click test connection button and then click ok.

4. Right click the connection1 tab and click add command to create a command1 tab. Right click tab and choose properties. Select database object as table and select the object name, ie the table name.

CREATING A DATA REPORT

On the project menu, click Add Data Report. If this item is not on the menu, click components.Click the designers tab,and choose Data Report and click ok to add the designer to our menu.

1. In the data report properties,give the data source and the data member.

2. There are five sections to the data report.a report header,a page footer and a report footer. The headers and footers contain information we want print in the report and on each page.

3. The detail section is used to layout the information that we want to print for each record in our database.

4. Save the file.

ACCESSING THE DATA REPORT

In the form, add a command button

1. Use the below code to view the report Private Sub Command1_Click ()

DataReport1.Show End Sub

2. Save the application and run it.

OUTPUT

RESULT:

Thus the data report was generated in visual basic and output was verified.

EX: NO: 12STUDENT MANAGEMENT SYSTEMDate:

AIM:

To develop the mini project of student management system and to design the relevant tables for this project.

SOFTWARE REQUIREMENTS:

Front end: visual basic 6.0

Back end : ms-access

PROCEDURE:

Step1: design the database and various tables for this project using the software access

Following tables are designed :

Table: student_details

FIELDDATA_TYPE

ROLLNONUMBER

CLASSTEXT

NAMETEXT

DOBDATE

DOJDATE

FATHERNAMETEXT

INCOMENUMBER

ADDRESSTEXT

PHONE NONUMBER

SEXTEXT

AGENUMBER

TABLE 2:student marks

FIELDDATA_TYPE

ROLL_NONUMBER

CLASSTEXT

SUBJECT1NUMBER

SUBJECT2NUMBER

SUBJECT3NUMBER

SUBJECT4NUMBER

SUBJECT5NUMBER

TOTALNUMBER

AVGNUMBER

STEP 2: CLICKStartPrograms visual basics 6.0Then design the form and relevant coding

CODING:Dim db As New ADODB.Connection

Dim rs As New ADODB.RecordsetDim s As Integer

Private Sub Combo1_Click()Call initEnd Sub

Private Sub Combo2_Click()

Set rs = db.Execute("select roll from student where(roll='" & Combo2.Text & "'and class='" & Combo1.Text & "')")

Text1.Text = rs.Fields(0) End Sub

Private Sub Command1_Click()

Set rs = db.Execute("select*from unit1 where(roll='" & Combo2.Text & "'and class='" & Combo1.Text & "')")

If rs.EOF = False Then Text2.Text = rs.Fields(1) Text3.Text = rs.Fields(2)

Text4.Text = rs.Fields(3) Text5.Text = rs.Fields(4) Text6.Text = rs.Fields(5) Text7.Text = rs.Fields(6) Else

Text2.Text = ""Text3.Text = ""Text4.Text = ""Text5.Text = ""Text6.Text = ""

Text7.Text = "" End If

s = 1 End Sub

Private Sub Command2_Click()

Set rs = db.Execute("select*from unit2 where(roll='" & Combo2.Text & "' and class='" & Combo1.Text & "')")

If rs.EOF = False Then Text2.Text = rs.Fields(1) Text3.Text = rs.Fields(2) Text4.Text = rs.Fields(3) Text5.Text = rs.Fields(4) Text6.Text = rs.Fields(5) Text7.Text = rs.Fields(6) Else

Text2.Text = ""Text3.Text = ""Text4.Text = ""Text5.Text = ""Text6.Text = ""

Text7.Text = "" End If

s = 2 End Sub

Private Sub Command3_Click()

Set rs = db.Execute("select*from cycle where(roll='" & Combo2.Text & "' and class='" & Combo1.Text & "')")

If rs.EOF = False Then Text2.Text = rs.Fields(1) Text3.Text = rs.Fields(2) Text4.Text = rs.Fields(3) Text5.Text = rs.Fields(4) Text6.Text = rs.Fields(5) Text7.Text = rs.Fields(6)

Else Text2.Text = "" Text3.Text = "" Text4.Text = "" Text5.Text = "" Text6.Text = "" Text7.Text = "" End If

s = 3 End Sub

Private Sub Command4_Click()

Set rs = db.Execute("select*from sem where(roll='" & Combo2.Text & "' and class='" & Combo1.Text & "')")

If rs.EOF = False Then Text2.Text = rs.Fields(1) Text3.Text = rs.Fields(2) Text4.Text = rs.Fields(3) Text5.Text = rs.Fields(4) Text6.Text = rs.Fields(5) Text7.Text = rs.Fields(6) Else

Text2.Text = ""Text3.Text = ""Text4.Text = ""Text5.Text = ""Text6.Text = ""

Text7.Text = "" End If

s = 4 End Sub

Private Sub Command5_Click() If s = 1 Then

Set rs = db.Execute("select*from unit1 where(roll='" & Combo2.Text & "'and class='" & Combo1.Text & "')")

If rs.EOF = False Then

Set rs = db.Execute("delete from unit1 where(roll='" & Combo2.Text & "'and class'" & Combo2.Text & "')")

Set rs = db.Execute("insert into unit1 values('" & Text1.Text & "','" & Text2.Text & "','" & Text3.Text & "','" & Text4.Text & "','" & Text5.Text & "','" & Text6.Text & "','" & Text7.Text & "','" & Combo1.Text & "')")

MsgBox "unit1" Else

Set rs = db.Execute("insert into unit1 values('" & Text1.Text & "','" & Text2.Text & "','" & Text3.Text & "','" & Text4.Text & "','" & Text5.Text & "','" & Text6.Text & "','" & Text7.Text

"','" & Combo1.Text & "')") MsgBox "unit1"

End If ElseIf s = 2 Then

Set rs = db.Execute("select*from unit2 where(roll='" & Combo2.Text & "' and class='" & Combo1.Text & "')")

If rs.EOF = False Then

Set rs = db.Execute("delete from unit2 where(roll='" & Combo2.Text & "' and class='" & Combo1.Text & "')")

Set rs = db.Execute("insert into unit2 values('" & Text1.Text & "','" & Text2.Text & "','" & Text3.Text & "','" & Text4.Text & "','" & Text5.Text & "','" & Text6.Text & "','" & Text7.Text "','" & Combo1.Text & "')")

MsgBox "unit2" Else

Set rs = db.Execute("insert into unit2 values('" & Text1.Text & "','" & Text2.Text & "','" & Text3.Text & "','" & Text4.Text & "','" & Text5.Text & "','" & Text6.Text & "','" & Text7.Text

"','" & Combo1.Text & "')") MsgBox "unit2"

End If ElseIf s = 3 Then

Set rs = db.Execute("select*from cycle where(roll='" & Combo2.Text & "'and class='" & Combo1.Text & "')")

If rs.EOF = False Then

Set rs = db.Execute("delete from cycle where(roll='" & Combo2.Text & "' and class='" & Combo1.Text & "')")

Set rs = db.Execute("insert into cycle values('" & Text1.Text & "','" & Text2.Text & "','" & Text3.Text & "','" & Text4.Text & "','" & Text5.Text & "','" & Text6.Text & "','" & Text7.Text "','" & Combo1.Text & "')")

MsgBox "cycle" Else

Set rs = db.Execute("insert into cycle values('" & Text1.Text & "','" & Text2.Text & "','" & Text3.Text & "','" & Text4.Text & "','" & Text5.Text & "','" & Text6.Text & "','" & Text7.Text

"','" & Combo1.Text & "')") MsgBox "cycle"

End If ElseIf s = 4 Then

Set rs = db.Execute("select*from sem where(roll='" & Combo2.Text & "'and class='" & Combo1.Text & "')")

If rs.EOF = False Then

Set rs = db.Execute("delete from sem where(roll='" & Combo2.Text & "'and class='" & Combo1.Text & "')")

Set rs = db.Execute("insert into sem values('" & Text1.Text & "','" & Text2.Text & "','" & Text3.Text & "','" & Text4.Text & "','" & Text5.Text & "','" & Text6.Text & "','" & Text7.Text "','" & Combo1.Text & "')")

MsgBox "semester" Else

Set rs = db.Execute("insert into sem values('" & Text1.Text & "','" & Text2.Text & "','" & Text3.Text & "','" & Text4.Text & "','" & Text5.Text & "','" & Text6.Text & "','" & Text7.Text & "','" & Combo1.Text & "')")

MsgBox "semester" End If

End If End Sub

Private Sub Command6_Click()

Text2.Text = ""Text3.Text = ""Text4.Text = ""Text5.Text = ""Text6.Text = ""Text7.Text = ""Text8.Text = ""Text9.Text = ""End Sub

Private Sub Command8_Click() If s = 1 Then

datareport1.Show 'elseif s=2 then 'datareport2.show 'elseif s=2 then 'datareport3.show 'elseif s=2 then 'datareport4.show EndEnd Sub

Private Sub Command9_Click()

EndEnd Sub

Private Sub Form_Load() db.ConnectionString = "DSN=rajesh kannan" db.Open

Text1.Locked = True s = 1

End Sub

Private Sub init() Dim i As Integer Combo2.Clear

Set rs = db.Execute("select count(roll)from student where(class='" & Combo1.Text & "')") i = rs.Fields(0)

Set rs = db.Execute("select roll from student where(class='" & Combo1.Text & "')") For j = 0 To i - 1

Combo2.AddItem rs.Fields(0) rs.MoveNext

Next j End SubPrivate Sub Text10_Change()

Text7.Text = Val(Text2.Text) + Val(Text3.Text) + Val(Text5.Text) + Val(Text6.Text) Text8.Text = Val(Text5.Text) / 5

If Val(Text2.Text) < "50" Or Val(Text3.Text) < "50" Or Val(Text4.Text) < "50" Or Val(Text5.Text) < "50" Or Val(Text6.Text) < "50" Then

Text9.Text = "fail" Else

Text9.Text = "pass" End If

End Sub

Private Sub Text2_Change()Text7.Text = Val(Text2.Text) + Val(Text3.Text) + Val(Text5.Text) + Val(Text6.Text)Text8.Text = Val(Text5.Text) / 5If Val(Text2.Text) < "50" Or Val(Text3.Text) < "50" Or Val(Text4.Text) < "50" OrVal(Text5.Text) < "50" Or Val(Text6.Text) < "50" ThenText9.Text = "fail"ElseText9.Text = "pass"End IfEnd Sub

Private Sub Text4_Change()Text7.Text = Val(Text2.Text) + Val(Text3.Text) + Val(Text5.Text) + Val(Text6.Text)Text8.Text = Val(Text5.Text) / 5If Val(Text2.Text) < "50" Or Val(Text3.Text) < "50" Or Val(Text4.Text) < "50" Or

Val(Text5.Text) < "50" Or Val(Text6.Text) < "50" ThenText9.Text = "fail"ElseText9.Text = "pass"End IfEnd Sub

Private Sub Text5_Change()

Text7.Text = Val(Text2.Text) + Val(Text3.Text) + Val(Text5.Text) + Val(Text6.Text) Text8.Text = Val(Text5.Text) / 5

If Val(Text2.Text) < "50" Or Val(Text3.Text) < "50" Or Val(Text4.Text) < "50" Or Val(Text5.Text) < "50" Or Val(Text6.Text) < "50" Then

Text9.Text = "fail"ElseText9.Text = "pass"End IfEnd Sub

Private Sub Text7_Change()

Text7.Text = Val(Text2.Text) + Val(Text3.Text) + Val(Text5.Text) + Val(Text6.Text)

Text8.Text = Val(Text5.Text) / 5If Val(Text2.Text) < "50" Or Val(Text3.Text) < "50" Or Val(Text4.Text) < "50" OrVal(Text5.Text) < "50" Or Val(Text6.Text) < "50" Then

Text9.Text = "fail"ElseText9.Text = "pass"End IfEnd Sub

Private Sub Text8_Change()

Text7.Text = Val(Text2.Text) + Val(Text3.Text) + Val(Text5.Text) + Val(Text6.Text)Text8.Text = Val(Text5.Text) / 5If Val(Text2.Text) < "50" Or Val(Text3.Text) < "50" Or Val(Text4.Text) < "50" OrVal(Text5.Text) < "50" Or Val(Text6.Text) < "50" ThenText9.Text = "fail"ElseText9.Text = "pass"End IfEnd Sub

Private Sub Text9_Change()

Text7.Text = Val(Text2.Text) + Val(Text3.Text) + Val(Text5.Text) + Val(Text6.Text)Text8.Text = Val(Text5.Text) / 5If Val(Text2.Text) < "50" Or Val(Text3.Text) < "50" Or Val(Text4.Text) < "50" OrVal(Text5.Text) < "50" Or Val(Text6.Text) < "50" ThenText9.Text = "fail"

ElseText9.Text = "pass"End IfEnd Sub

RESULT

Thus the students management system wasdesignedandoutputwasverified.