Sei sulla pagina 1di 56

CS 6312 DBMS LAB SYLLABUS

1. Creation of a database and writing SQL queries to retrieve information from the database.

2. Performing Insertion, Deletion, Modifying, Altering, Updating and Viewing records based on

conditions.

3. Creation of Views, Synonyms, Sequence, Indexes, Save point.

4. Creating an Employee database to set various constraints.

5. Creating relationship between the databases.

6. Study of PL/SQL block.

7. Write a PL/SQL block to satisfy some conditions by accepting input from the user.

8. Write a PL/SQL block that handles all types of exceptions.

9. Creation of Procedures.

10. Creation of database triggers and functions

11. Mini project (Application Development using Oracle/ Mysql )


1. Data Definition, Table Creation
AIM

To study and work with DDL Commands in Oracle

DESCRIPTION

CREATE
To create a table, the basic structure to hold user data, specifying this information:
 column definitions
 integrity constraints
 the table's tablespace
 storage characteristics
 an optional cluster
 data from an arbitrary query
Syntax

CREATE TABLE tablename (columnname datatype [constraint [constraint name]][,


columnname ......] [, constraints] );
Constraints:
 NOT NULL every record must have a value for the column
 UNIQUE value for each record must be distinct
 CHECK checks to make sure the condition is satisfied
 PRIMARY KEY defines the primary key of the table
 FOREIGN KEY (columname) REFERENCES tablename (columnname) defines the foreign key
of the table
ALTER

To alter the definition of a table in one of these ways:


 to add a column
 to add an integrity constraint
 to redefine a column (data type, size, default value)
 to explicitly allocate an extent
Syntax
ALTER TABLE tablename MODIFY (columnname [datatype] [constraint]);
ALTER TABLE tablename ADD (columnname datatype [constraint]);
DROP
This command is used todrop the table.
Syntax
DROP TABLE tablename;
RENAME
RENAME tablename to new-tablename;
TRUNCATE: Delete all the records in the table retaining its structure.
Syntax: Truncate table <table name>;
Example SQL> truncate table employee;
PROCEDURE
1. Create a table with the given fields
2. Display the structure of the table
3. Alter the size and datatype of the fields in the table
4. Rename the table names
5. Drop the tables

OUTPUT
SQL> create table custdt(cust_name varchar2(20),ac_num number(10),bal number(10),

ad varchar2(20));

Table created.

SQL>desc custdt;

Name Null? Type

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

CUST_NAME VARCHAR2(20)

AC_NUM NUMBER(10)
BAL NUMBER(10)

AD VARCHAR2(20)

SQL> alter table custdt add(phno number(10));


Table altered.

SQL> rename custdt to customer;


Table renamed.
SQL> drop table customer;
Table dropped.

RESULT:

Thus the DDL Commands were studied and worked out in Oracle.
2. Insert, Select Commands, Update & Delete Commands.
AIM:
To study about the Insert, Select Commands, Update & Delete Commands in Oracle.

DESCRIPTION:
1.INSERT:

Insert command insert one or more rows into a table.

Syntax:

INSERT INTO<table name> values (value1, value2, value3….);

Example: SQL>insert into emp1 values (7954,‘SMITH‘,‘CLERK‘, 7902,‘17-DEC-1980‘ ,


800,NULL,20); SQL> insert into emp1 values (&empno,‘&ename‘,‘&job‘,&mgr,‘&hiredate‘,&sal,
comm);

2. SIMPLE SELECT STATEMENT:

To view records from a table

Syntax:

SELECT * from <tablename> SELECT column1, column2 from <tablename>

Example

SQL>select * from emp1

SQL>select eno,ename from emp1

3.UPDATE :

The UPDATE command can be used to modify information contained within a table, either in
bulk or individually.

Syntax:

1.UPDATE tablename SET fieldname=new value;


2. UPDATE table name SET fieldname=new value where condition;

4. DELETE: To delete particular record from a table.

Syntax: Delete from <tablename> where <condition>

Example: SQL> Delete from emp1 where ename=‘john‘;

RESULT:

Thus the Insert, Select Commands, Update & Delete Commands were studied and worked
out in oracle.
3. Nested Queries & Join Queries
AIM:
To study about the Insert, Select Commands, Update & Delete Commands in Oracle.

DESCRIPTION:
CREATING TABLES FOR DOING JOIN AND NESTED QUERY OPERATIONS

TO CREATE SSTUD1 TABLE


SQL> create table sstud1 ( sname varchar2(20) , place varchar2(20));
Table created.
SQL> insert into sstud1 values ( 'prajan','chennai');
1 row created.
SQL> insert into sstud1 values ( 'anand','chennai');
1 row created.
SQL> insert into sstud1 values ( 'kumar','chennai');
1 row created.
SQL> insert into sstud1 values ( 'ravi','chennai');
1 row created.
SQL> select * from sstud1;
SNAME PLACE
-------------------- --------------------
prajan chennai
anand chennai
kumar chennai
ravi chennai
TO CREATE SSTUD2 TABLE
SQL> create table sstud2 ( sname varchar2(20), dept varchar2(10), marks number(10));
Table created.
SQL> insert into sstud2 values ('prajan','cse',700);
1 row created.
SQL> insert into sstud2 values ('anand','it',650);
1 row created.
SQL> insert into sstud2 values ('vasu','cse',680);
1 row created.
SQL> insert into sstud2 values ('ravi','it',600);
1 row created.
SQL> select * from sstud2;
SNAME DEPT MARKS
-------------------- ---------- ---------
prajan cse 700
anand it 650
vasu cse 680
ravi it 600
JOIN OPERATIONS

SQL> select sstud1.sname, dept from sstud1 inner join sstud2 on ( sstud1.sname= sstud2.sname);
SNAME DEPT
-------------------- ----------
anand it
prajan cse
ravi it
SQL> select sstud1.sname, dept from sstud1 join sstud2 on ( sstud1.sname= sstud2.sname);
SNAME DEPT
-------------------- ----------
anand it
prajan cse
ravi it
SQL> select sstud1.sname, dept from sstud1 left outer join sstud2 on ( sstud1.sname= sstud2.sname);
SNAME DEPT
-------------------- ----------
prajan cse
anand it
ravi it
kumar
SQL> select sstud1.sname, dept from sstud1 right outer join sstud2 on ( sstud1.sname=
sstud2.sname)
SNAME DEPT
-------------------- ----------
prajan cse
anand it
ravi it
cse
SQL> select sstud1.sname, dept from sstud1 full outer join sstud2 on ( sstud1.sname= sstud2.sname);
SNAME DEPT
-------------------- ----------
prajan cse
anand it
ravi it
kumar
cse

NESTED QUERIES

SQL> select sname from sstud1 where sstud1.sname in ( select sstud2.sname from
2 sstud2 );
SNAME
--------------------
anand
prajan
ravi
SQL> select sname from sstud1 where sstud1.sname not in ( select sstud2.sname from sstud2 );
SNAME
--------------------
kumar
SQL> select sname from sstud2 where marks > some(select marks from sstud2
2 where dept='cse');
SNAME
--------------------
prajan
SQL> select sname from sstud2 where marks >= some (select marks from sstud2
2 where dept='cse' );
SNAME
--------------------
prajan
vasu
SQL> select sname from sstud2 where marks > any ( select marks from sstud2 where dept='cse' );
SNAME
--------------------
prajan
SQL> select sname from sstud2 where marks >= any ( select marks from sstud2
2 where dept='cse' );
SNAME
--------------------
prajan
vasu
SQL> select sname from sstud2 where marks > all ( select marks from sstud2 where dept='cse' );
no rows selected
SQL> select sname from sstud2 where marks < all ( select marks from sstud2 where dept='cse' );
SNAME
--------------------
anand
ravi
SQL> select sname from sstud1 where exists ( select sstud2.sname from sstud2
2 where sstud1.sname=sstud2.sname );
SNAME
--------------------
prajan
anand
ravi
SQL> select sname from sstud1 where not exists ( select sstud2.sname from
2 sstud2 where sstud1.sname=sstud2.sname );
SNAME
--------------------
kumar

RESULT
Thus Nested query and Join queries were executed and the output was verified.
4A. VIEWS

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

CREATE TABLE HARISH1:


SQL> create table harish1(name varchar2(20),rno number(5),marks number(5),primary
key(rno));

Table created.

SQL> desc harish1;

Name Null? Type


----------------------------------------- -------- ----------------------
NAME VARCHAR2(20)
RNO NOT NULL NUMBER(5)
MARKS NUMBER(5)

SQL> insert into harish1 values('Narean',1001,350);

1 row created.

SQL> insert into harish1 values('Muzamil',1002,298);

1 row created.

SQL> insert into harish1 values('Raju',1003,375);

1 row created.

SQL> select*from harish1;


NAME RNO MARKS
-------------------- ---------- ----------
Narean 1001 350
Muzamil 1002 298
Raju 1003 375

CREATE TABLE HARISH2:

SQL> create table harish2(rollno number(5),attendance number(5),primary key(rollno));

Table created.

SQL> desc harish2;

Name Null? Type


----------------------------------------- -------- ----------------------
ROLLNO NOT NULL NUMBER(5)
ATTENDANCE NUMBER(5)

SQL> insert into harish2 values(1001,90);

1 row created.

SQL> insert into harish2 values(1002,75);

1 row created.

SQL> insert into harish2 values(1003,85);

1 row created.

SQL> select*from harish2;

ROLLNO ATTENDANCE
---------- ----------
1001 90
1002 75
1003 85

CREATE TABLE HARISHVIEW:

SQL> create view harishview as select name,rno,marks,attendance from harish1,harish2


where rollno=rno;

View created.

SQL> select*from harishview;

NAME RNO MARKS ATTENDANCE


-------------------- ---------- ---------- ----------
Narean 1001 350 90
Muzamil 1002 298 75
Raju 1003 375 85

SQL> select name,rno from harishview where rno=1001;

NAME RNO
-------------------- ----------
Narean 1001

SQL> update harishview set name='Ramesh' where name='Muzamil';

1 row updated.

SQL> select*from harishview;

NAME RNO MARKS ATTENDANCE


-------------------- ---------- ---------- ----------
Narean 1001 350 90
Ramesh 1002 298 75
Raju 1003 375 85

SQL> update harishview set marks=325 where name='Ramesh';

1 row updated.

SQL> select*from harishview;

NAME RNO MARKS ATTENDANCE


-------------------- ---------- ---------- ----------
Narean 1001 350 90
Ramesh 1002 325 75
Raju 1003 375 85

RESULT

Thus views were created, various operations were performed and the outputs were verified.
4B. Creation of Synonyms, Sequence, Indexes, Save point
Aim

To create Synonyms, Sequence, Indexes, and Save points.

Synonym

Synonym is an alternative name for a table, view, sequence, operator, procedure, stored
function, package, materialized view, Java class schema object, user-defined object type, or
another synonym. A synonym places a dependency on its target object and becomes invalid if the
target object is changed or dropped.

Public Synonym:

Specify PUBLIC to create a public synonym. Public synonyms are accessible to all users.
However each user must have appropriate privileges on the underlying object in order to use the
synonym.

CREATE SYNONYM:

Examples: To define the synonym offices for the table locations in the schema hr, issue the
following statement:

CREATE SYNONYM offices


FOR hr.locations;

To create a PUBLIC synonym for the employees table in the schema hr on the remote database,
you could issue the following statement:

CREATE PUBLIC SYNONYM emp_table


FOR hr.employees@remote.us.example.com;

A synonym may have the same name as the underlying object, provided the underlying object is
contained in another schema.

For example, the schemas oe and sh both contain tables named customers. In the next example,
user SYSTEM creates a PUBLIC synonym named customers for oe.customers:

CREATE PUBLIC SYNONYM customers FOR oe.customers;

If the user sh then issues the following statement, then the database returns the count of rows
from sh.customers:

SELECT COUNT(*) FROM customers;


To retrieve the count of rows from oe.customers, the user sh must preface customers with the
schema name. (The user sh must have select permission on oe.customers as well.)

SELECT COUNT(*) FROM oe.customers;

If the user hr's schema does not contain an object named customers, and if hr has select
permission on oe.customers, then hr can access the customers table in oe's schema by using
the public synonym customers:

SELECT COUNT(*) FROM customers;

Sequences (Autonumber)
Description
In Oracle, we can create an autonumber field by using sequences. A sequence is an object
in Oracle that is used to generate a number sequence. This can be useful when you need to create
a unique number to act as a primary key.

Create Sequence
We may wish to create a sequence in Oracle to handle an autonumber field.

Syntax

The syntax to create a sequence in Oracle is:

CREATE SEQUENCE sequence_name


MINVALUE value
MAXVALUE value
START WITH value
INCREMENT BY value
CACHE value;

Example

TO CREATE A SEQUENCE :

For example:

CREATE SEQUENCE supplier_seq


MINVALUE 1
MAXVALUE 999999999999999999999999999
START WITH 1
INCREMENT BY 1
CACHE 20;
This would create a sequence object called supplier_seq. The first sequence number that
it would use is 1 and each subsequent number would increment by 1 (ie: 2,3,4,...}. It will cache
up to 20 values for performance.

If we omit the MAXVALUE option, your sequence will automatically default to:

MAXVALUE 999999999999999999999999999

So you can simplify your CREATE SEQUENCE command as follows:

CREATE SEQUENCE supplier_seq


MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 20;

Now that we've created a sequence object to simulate an autonumber field, we'll cover how to
retrieve a value from this sequence object. To retrieve the next value in the sequence order, we
need to use nextval.

For example:

supplier_seq.NEXTVAL;

This would retrieve the next value from supplier_seq. The nextval statement needs to be used in
a SQL statement. For example:

INSERT INTO suppliers


(supplier_id, supplier_name)
VALUES
(supplier_seq.NEXTVAL, 'Kraft Foods');

This insert statement would insert a new record into the suppliers table. The supplier_id
field would be assigned the next number from the supplier_seq sequence. The supplier_name
field would be set to Kraft Foods.

Drop Sequence
Once we have created your sequence in Oracle, we might find that you need to remove it from
the database.

Syntax

The syntax to a drop a sequence in Oracle is:

DROP SEQUENCE sequence_name;

sequence_name is the name of the sequence that we wish to drop.


Example

Let's look at an example of how to drop a sequence in Oracle.

For example:

DROP SEQUENCE supplier_seq;

This example would drop the sequence called supplier_seq.

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

Indexes
 An index can be created in a table to find data more quickly and efficiently.
 The users cannot see the indexes, they are just used to speed up searches/queries.

SQL CREATE INDEX Syntax

Creates an index on a table. Duplicate values are allowed:

CREATE INDEX index_name


ON table_name (column_name)

CREATE INDEX Example

The SQL statement below creates an index named "PIndex" on the "LastName" column in the
"Persons" table:

CREATE INDEX PIndex


ON Persons (LastName)

If we want to create an index on a combination of columns, we can list the column names within
the parentheses, separated by commas:

CREATE INDEX PIndex


ON Persons (LastName, FirstName)

The DROP INDEX Statement

The DROP INDEX statement is used to delete an index in a table.


DROP INDEX Syntax for MS Access:

DROP INDEX index_name ON table_name

Transaction Control:

There are following commands used to control transactions:

 COMMIT: to save the changes.


 ROLLBACK: to rollback the changes.
 SAVEPOINT: creates points within groups of transactions in which to ROLLBACK
 SET TRANSACTION: Places a name on a transaction.

Transactional control commands are only used with the DML commands INSERT, UPDATE and
DELETE only. They can not be used while creating tables or dropping them because these
operations are automatically commited in the database.

The COMMIT Command:

The COMMIT command is the transactional command used to save changes invoked by a
transaction to the database.

The COMMIT command saves all transactions to the database since the last COMMIT or
ROLLBACK command.

The syntax for COMMIT command is as follows:

COMMIT;

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 the example which would delete records from the table having age = 25 and then
COMMIT the changes in the database.

SQL> DELETE FROM CUSTOMERS


WHERE AGE = 25;
SQL> COMMIT;

As a result, two rows from the table would be deleted and SELECT statement would produce the
following result:

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

The ROLLBACK Command:

The ROLLBACK command is the transactional command used to undo transactions that have
not already been saved to the database.

The ROLLBACK command can only be used to undo transactions since the last COMMIT or
ROLLBACK command was issued.

The syntax for ROLLBACK command is as follows:

ROLLBACK;

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 the example, which would delete records from the table having age = 25 and then
ROLLBACK the changes in the database.

SQL> DELETE FROM CUSTOMERS


WHERE AGE = 25;
SQL> ROLLBACK;

As a result, delete operation would not impact the table and SELECT statement would produce
the following result:

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

The SAVEPOINT Command:

A SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain
point without rolling back the entire transaction.

The syntax for SAVEPOINT command is as follows:

SAVEPOINT SAVEPOINT_NAME;

This command serves only in the creation of a SAVEPOINT among transactional statements. The
ROLLBACK command is used to undo a group of transactions.

The syntax for rolling back to a SAVEPOINT is as follows:

ROLLBACK TO SAVEPOINT_NAME;

Following is an example where you plan to delete the three different records from the
CUSTOMERS table. You want to create a SAVEPOINT before each delete, so that you can
ROLLBACK to any SAVEPOINT at any time to return the appropriate data to its original state:

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

Now, here is the series of operations:

SQL> SAVEPOINT SP1;


Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=1;
1 row deleted.
SQL> SAVEPOINT SP2;
Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=2;
1 row deleted.
SQL> SAVEPOINT SP3;
Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=3;
1 row deleted.

Now that the three deletions have taken place, then ROLLBACK to the SAVEPOINT that we
have identified as SP2. Because SP2 was created after the first deletion, the last two deletions are
undone:

SQL> ROLLBACK TO SP2;


Rollback complete.

Notice that only the first deletion took place since we rolled back to SP2:

SQL> SELECT * FROM CUSTOMERS;


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
6 rows selected.
The RELEASE SAVEPOINT Command:

The RELEASE SAVEPOINT command is used to remove a SAVEPOINT that you have created.

The syntax for RELEASE SAVEPOINT is as follows:

RELEASE SAVEPOINT SAVEPOINT_NAME;

Once a SAVEPOINT has been released, you can no longer use the ROLLBACK command to
undo transactions performed since the SAVEPOINT.

Result:

Thus the synonyms, sequences, indexes and save points were created and executed successfully.
5. CREATING TABLES WITH CONSTRAINTS
Aim:

To create Employee database with various constraints.

SQL CONSTRAINTS:

Constraints are the rules enforced on data columns on table. These are used to limit the type of
data that can go into a table. This ensures the accuracy and reliability of the data in the database.

Constraints could be column level or table level. Column level constraints are applied only to one
column, whereas table level constraints are applied to the whole table.

Following are commonly used constraints available in SQL.

 NOT NULL Constraint: Ensures that a column cannot have NULL value.

 DEFAULT Constraint: Provides a default value for a column when none is specified.

 UNIQUE Constraint: Ensures that all values in a column are different.

 PRIMARY Key: Uniquely identified each rows/records in a database table.

 FOREIGN Key: Uniquely identified a rows/records in any another database table.

 CHECK Constraint: The CHECK constraint ensures that all values in a column satisfy certain
conditions.

(NOT NULL)

SQL> CREATE TABLE EMPLOYEE(EMP_NO NUMBER(6) NOT NULL,NAME


VARCHAR2(10),BRANCH VARCHAR2(6));

Table created.

SQL> DESC EMPLOYEE;

Name Null? Type

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

EMP_NO NOT NULL NUMBER(6)

NAME VARCHAR2(10)
BRANCH VARCHAR2(6)

SQL> INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH');

Enter value for emp_no: 501

Enter value for name: ABHILASH

Enter value for branch: CHENNAI

old 1: INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH')

new 1: INSERT INTO EMPLOYEE VALUES(501,'ABHILASH', ‘CHENNAI’)

1 row created.

SQL> /

Enter value for emp_no: 502

Enter value for name: ABI

Enter value for branch: CHENNAI

old 1: INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH')

new 1: INSERT INTO EMPLOYEE VALUES(502,'ABI', ‘CHENNAI’)

1 row created.

SQL> SELECT * FROM EMPLOYEE;

EMP_NO NAME BRANCH

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

501 ABHILASH CHENNAI

502 ABI CHENNAI

SQL> INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH');


Enter value for emp_no:

Enter value for name: BHAVYA

Enter value for branch: CHENNAI

old 1: INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH')

new 1: INSERT INTO EMPLOYEE VALUES(,'BHAVYA', ‘CHENNAI’)

INSERT INTO EMPLOYEE VALUES(,'BHAVYA', ‘CHENNAI’)

ERROR:CANNOT INSERT NULL INTO("SCOTT", EMPLOYEE,EMP_NO)

(UNIQUE)

SQL> CREATE TABLE EMPLOYEE (EMP_NO NUMBER(6) UNIQUE ,NAME


VARCHAR2(10),BRANCH VARCHAR2(6));

Table created.

SQL> INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH');

Enter value for rollno: 501

Enter value for name: abhilash

Enter value for branch: chennai

old 1: INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH')

new 1: INSERT INTO EMPLOYEE VALUES(501,'abhilash', ‘CHENNAI’)

1 row created.

SQL> /

Enter value for emp_no: 502

Enter value for name: ABI

Enter value for branch: chennai

old 1: INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH')


new 1: INSERT INTO EMPLOYEE VALUES(502,'ABI',' CHENNAI ')

1 row created.

SQL> /

Enter value for emp_no: 502

Enter value for name: BHAVYA

Enter value for branch: chennai

old 1: INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH')

new 1: INSERT INTO EMPLOYEE VALUES(502,'BHAVYA','CSE')

INSERT INTO EMPLOYEE VALUES(502,'BHAVYA', ‘CHENNAI’)

ERROR at line 1:

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

(PRIMARY KEY)

SQL> CREATE TABLE EMPLOYEE (EMP_NO NUMBER(6) PRIMARY KEY ,NAME


VARCHAR2(10),BRANCH VARCHAR2(6));

Table created.

SQL> INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH');

Enter value for emp_no: 501

Enter value for name: abhilash

Enter value for branch: chennai

old 1: INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH')

new 1: INSERT INTO EMPLOYEE VALUES(501,'abhilash', ‘chennai’)

1 row created.
SQL> /

Enter value for emp_no: 502

Enter value for name: ABI

Enter value for branch: CHENNAI

old 1: INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH')

new 1: INSERT INTO EMPLOYEE VALUES(502,'ABI','CHENNAI')

1 row created.

SQL> /

Enter value for emp_no: 502

Enter value for name: BHAVYA

Enter value for branch: CHENNAI

old 1: INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH')

new 1: INSERT INTO EMPLOYEE VALUES(502,'BHAVYA', 'CHENNAI')

INSERT INTO EMPLOYEE VALUES(502,'BHAVYA', 'CHENNAI')

ERROR at line 1:

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

SQL> INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH');

Enter value for emp_no:

Enter value for name: BHAVYA

Enter value for branch: CHENNAI

old 1: INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH')

new 1: INSERT INTO EMPLOYEE VALUES(,'BHAVYA', 'CHENNAI')


INSERT INTO EMPLOYEE VALUES(,'BHAVYA', 'CHENNAI')

ERROR:CANNOT INSERT NULL INTO("SCOTT", EMPLOYEE,EMP_NO)

SQL> SELECT * FROM EMPLOYEE;

ROLLNO NAME BRANCH

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

501 ABHILASH CHENNAI

502 ABI CHENNAI

(CHECK)

SQL> create table EMPLOYEE (emp_no number(5),name varchar2(10),sal number(10) constraint no_ck
check(sal between 10000 and 30000));

Table created.

SQL> insert into EMPLOYEE values(&emp_no,'&name',&sal);

Enter value for rno: 567

Enter value for name: sachin

Enter value for sal: 29000

old 1: insert into EMPLOYEE values(&emp_no,'&name',&sal)

new 1: insert into EMPLOYEE values(567,'sachin',29000)

1 row created.

SQL> /

Enter value for emp_no: 565

Enter value for name: rohit


Enter value for sal: 35000

old 1: insert into EMPLOYEE values(&emp_no,'&name',&sal)

new 1: insert into EMPLOYEE values(565,'rohit',35000)

insert into EMPLOYEE values(565,'rohit',35000)

ERROR at line 1:

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

( FOREIGN KEY )

SOL>create table adm(emp_id number(6) constraint emp_id_pk primary key,ename varchar2(15),per


number(5));

Table created.

SQL> insert into adm values(&emp_id,'&ename',&per);

Enter value for emp_id: 1

Enter value for ename: abi

Enter value for per: 80

old 1: insert into adm values(&emp_id,'&ename',&per)

new 1: insert into adm values(1,'abi',80)

1 row created.

SQL> /

Enter value for emp_id: 2

Enter value for ename: rohit

Enter value for per: 89

old 1: insert into adm values(&emp_id,'&ename',&per)

new 1: insert into adm values(2,'rohit',89)

1 row created.
SQL> /

Enter value for emp_id: 3

Enter value for ename: sachin

Enter value for per: 99

old 1: insert into adm values(&emp_id,'&ename',&per)

new 1: insert into adm values(3,'sachin',99)

1 row created.

SQL> /

Enter value for emp_id: 4

Enter value for ename: naveen

Enter value for per: 70

old 1: insert into adm values(&emp_id,'&ename',&per)

new 1: insert into adm values(4,'naveen',70)

1 row created.

SQL> select * from adm;

EMP_ID ENAME PER

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

1 abi 80

2 rohit 89

3 sachin 99

4 naveen 70

SQL> create table department(emp_id number(6) constraint sid_fk references adm(emp_id),branch


varchar2(5),post_name varchar2(10));

Table created.
SQL> insert into department values(&emp_id,'&branch','&post_name’);

Enter value for emp_id: 1

Enter value for branch: cse

Enter value for post_name: a

old 1: insert into department values(&emp_id,'&branch','&post_name)

new 1: insert into department values(1,'cse','a')

1 row created.

SQL> /

Enter value for emp_id: 5

Enter value for branch: cse

Enter value for post_name: b

old 1: insert into department values(&emp_id,'&branch','&post_name)

new 1: insert into department values(5,'cse','b')

insert into department values(5,'cse','b')

ERROR at line 1:

ORA-02291: integrity constraint (SCOTT.SID_FK) violated - parent key not found

SQL> delete from adm where emp_id=1;

ERROR at line 1:

ORA-02292: integrity constraint (SCOTT.SID_FK) violated - child record found


SQL> delete from department where emp_id=1;

1 row deleted.

SQL> delete from adm where emp_id=1;

1 row deleted.

SQL>select * from adm;

EMP_ID ENAME PER

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

2 rohit 89

3 sachin 99

4 naveen 70

RESULT
Thus an Employee database with various constraints was Created and the outputs were verified.
6. Study of PL/SQL block
Aim:

To Study about PL/SQL block.

PL/SQL:

 PL/SQL stands for Procedural Language extension of SQL.


 PL/SQL is a combination of SQL along with the procedural features of programming
languages.

 It was developed by Oracle Corporation in the early 90’s to enhance the capabilities of
SQL.

A Simple PL/SQL Block:

Each PL/SQL program consists of SQL and PL/SQL statements which from a PL/SQL block.

PL/SQL Block consists of three sections:

 The Declaration section (optional).


 The Execution section (mandatory).
 The Exception (or Error) Handling section (optional).

Declaration Section:

The Declaration section of a PL/SQL Block starts with the reserved keyword DECLARE. This
section is optional and is used to declare any placeholders like variables, constants, records and
cursors, which are used to manipulate data in the execution section. Placeholders may be any of
Variables, Constants and Records, which stores data temporarily. Cursors are also declared in this
section.

Execution Section:

The Execution section of a PL/SQL Block starts with the reserved keyword BEGIN and ends
with END. This is a mandatory section and is the section where the program logic is written to
perform any task. The programmatic constructs like loops, conditional statement and SQL
statements form the part of execution section.

Exception Section:
The Exception section of a PL/SQL Block starts with the reserved keyword EXCEPTION. This
section is optional. Any errors in the program can be handled in this section, so that the PL/SQL
Blocks terminates gracefully. If the PL/SQL Block contains exceptions that cannot be handled,
the Block terminates abruptly with errors.

Every statement in the above three sections must end with a semicolon ; . PL/SQL blocks can be
nested within other PL/SQL blocks. Comments can be used to document code.

A Sample PL/SQL Block Looks like:

DECLARE

Variable declaration

BEGIN

Program Execution

EXCEPTION

Exception handling

END;

PL/SQL Block Structure

DECLARE

v_variable VARCHAR2(5);

BEGIN

SELECT column_name

INTO v_variable

FROM table_name;

EXCEPTION

WHEN exception_name THEN

...

END;
Block Types
1. Anonymous
[DECLARE]
BEGIN
--statements
[EXCEPTION]
END;

2. Procedure
PROCEDURE name
IS
BEGIN
--statements
[EXCEPTION]
END;
PROCEDURE name

3. Function
FUNCTION name
RETURN datatype
IS
BEGIN
--statements
RETURN value;
[EXCEPTION]
END;

Result:
Thus the PL/SQL blocks are studied.
EX: NO: 7 CONTROL STRCTURE
AIM
To write a PL/SQL block using different control (if, if else, for loop, while loop,…)
statements.
OBJECTIVE:
PL/SQL Control Structure provides conditional tests, loops, flow control and branches that
let to produce well-structured programs.

Addition of Two Numbers:


1. Write a PL/SQL Program for Addition of Two Numbers
PROCEDURE
STEP 1: Start
STEP 2: Initialize the necessary variables.
STEP 3: Develop the set of statements with the essential operational parameters.
STEP 4: Specify the Individual operation to be carried out.
STEP 5: Execute the statements.
STEP 6: Stop.

PL/ SQL General Syntax


SQL> DECLARE
<VARIABLE DECLARATION>;
BEGIN
<EXECUTABLE STATEMENT >;
END;

PL/SQL CODING FOR ADDITION OF TWO NUMBERS


SQL> declare
a number;
b number;
c number;
begin
a:=&a;
b:=&b;
c:=a+b;
dbms_output.put_line('sum of'||a||'and'||b||'is'||c);
end;
/
INPUT:
Enter value for a: 23
old 6: a:=&a;
new 6: a:=23;
Enter value for b: 12
old 7: b:=&b;
new 7: b:=12;

OUTPUT:
sum of23and12is35
PL/SQL procedure successfully completed.

PL/ SQL Program for IF Condition:


2. Write a PL/SQL Program using if condition

PROCEDURE
STEP 1: Start
STEP 2: Initialize the necessary variables.
STEP 3: invoke the if condition.
STEP 4: Execute the statements.
STEP 5: Stop.

PL/ SQL GENERAL SYNTAX FOR IF CONDITION:


SQL> DECLARE
<VARIABLE DECLARATION>;
BEGIN
IF(CONDITION)THEN
<EXECUTABLE STATEMENT >;
END;

Coding for If Statement:


DECLARE
b number;
c number;
BEGIN
B:=10;
C:=20;
if(C>B) THEN
dbms_output.put_line('C is maximum');
end if;
end;
/

OUTPUT:
C is maximum
PL/SQL procedure successfully completed.

PL/ SQL GENERAL SYNTAX FOR IF AND ELSECONDITION:


SQL> DECLARE
<VARIABLE DECLARATION>;
BEGIN
IF (TEST CONDITION) THEN
<STATEMENTS>;
ELSE
<STATEMENTS>;
ENDIF;
END;
******************Less then or Greater Using IF ELSE **********************
SQL> declare
n number;
begin
dbms_output. put_line('enter a number');
n:=&number;
if n<5 then
dbms_output.put_line('entered number is less than 5');
else
dbms_output.put_line('entered number is greater than 5');

end if;
end;
/
Input
Enter value for number: 2
old 5: n:=&number;
new 5: n:=2;

Output:
entered number is less than 5
PL/SQL procedure successfully completed.

PL/ SQL GENERAL SYNTAX FOR NESTED IF:


SQL> DECLARE
<VARIABLE DECLARATION>;
BEGIN
IF (TEST CONDITION) THEN
<STATEMENTS>;
ELSEIF (TEST CONDITION) THEN
<STATEMENTS>;
ELSE
<STATEMENTS>;
ENDIF;
END;

********** GREATEST OF THREE NUMBERS USING IF ELSEIF************


SQL> declare
a number;
b number;
c number;
d number;
begin
a:=&a;
b:=&b;
c:=&b;
if(a>b)and(a>c) then
dbms_output.put_line('A is maximum');
elsif(b>a)and(b>c)then
dbms_output.put_line('B is maximum');
else
dbms_output.put_line('C is maximum');
end if;
end;
/
INPUT:
Enter value for a: 21
old 7: a:=&a;
new 7: a:=21;
Enter value for b: 12
old 8: b:=&b;
new 8: b:=12;
Enter value for b: 45
old 9: c:=&b;
new 9: c:=45;

OUTPUT:
C is maximum
PL/SQL procedure successfully completed.

PL/ SQL GENERAL SYNTAX FOR LOOPING STATEMENT:


SQL> DECLARE
<VARIABLE DECLARATION>;
BEGIN
LOOP
<STATEMENT>;
END LOOP;
<EXECUTAVLE STATEMENT>;
END;

***********SUMMATION OF ODD NUMBERS USING FOR LOOP***********


SQL> declare
n number;
sum1 number default 0;
endvalue number;
begin
endvalue:=&endvalue;
n:=1;
for n in 1..endvalue
loop
if mod(n,2)=1
then
sum1:=sum1+n;
end if;
end loop;
dbms_output.put_line('sum ='||sum1);
end;
/
INPUT:
Enter value for endvalue: 4
old 6: endvalue:=&endvalue;
new 6: endvalue:=4;

OUTPUT:
sum =4
PL/SQL procedure successfully completed.

PL/ SQL GENERAL SYNTAX FOR LOOPING STATEMENT:


SQL> DECLARE
<VARIABLE DECLARATION>;
BEGIN
WHILE <condition>
LOOP
<STATEMENT>;
END LOOP;
<EXECUTAVLE STATEMENT>;
END;

*********SUMMATION OF ODD NUMBERS USING WHILE LOOP**********


SQL> declare
n number;
sum1 number default 0;
endvalue number;
begin
endvalue:=&endvalue;
n:=1;
while(n<endvalue)
loop
sum1:=sum1+n;
n:=n+2;
end loop;
dbms_output.put_line('sum of odd no. bt 1 and' ||endvalue||'is'||sum1);
end;
/
INPUT:
Enter value for endvalue: 4
old 6: endvalue:=&endvalue;
new 6: endvalue:=4;

OUTPUT:
sum of odd no. bt 1 and4is4
PL/SQL procedure successfully completed.

RESULT:
Thus the PL/SQL block for different controls are verified and executed.
8. PL/SQL Blocks with Exception Handling
Aim:

To Write a PL/SQL block that handles all types of exceptions.

Exception Handling:

PL/SQL provides a feature to handle the Exceptions which occur in a PL/SQL Block
known as exception Handling. Using Exception Handling we can test the code and avoid it from
exiting abruptly.

When an exception occurs a messages which explains its cause is recieved.


PL/SQL Exception message consists of three parts.
1) Type of Exception
2) An Error Code
3) A message

Structure of Exception Handling.

General Syntax for coding the exception section

DECLARE
Declaration section
BEGIN
Exception section
EXCEPTION
WHEN ex_name1 THEN
-Error handling statements
WHEN ex_name2 THEN
-Error handling statements
WHEN Others THEN
-Error handling statements
END;

Types of Exception.

There are 2 types of Exceptions.


a) System Exceptions
b) User-defined Exceptions

a) System Exceptions
System exceptions are automatically raised by Oracle, when a program violates a RDBMS rule.
There are some system exceptions which are raised frequently, so they are pre-defined and given
a name in Oracle which are known as Named System Exceptions.

For example: NO_DATA_FOUND and ZERO_DIVIDE are called Named System exceptions.

For Example: Suppose a NO_DATA_FOUND exception is raised in a proc, we can write a code
to handle the exception as given below.

BEGIN
Execution section
EXCEPTION
WHEN NO_DATA_FOUND THEN
dbms_output.put_line ('A SELECT...INTO did not return any row.');
END;

b) User-defined Exceptions

PL/SQL allows us to define our own exceptions according to the need of our program. A
user-defined exception must be declared and then raised explicitly, using a RAISE statement.

To define an exception we use EXCEPTION keyword as below:


EXCEPTION_NAME EXCEPTION;

To raise exception that we’ve defined to use the RAISE statement as follows:
RAISE EXCEPTION_NAME

Raising Exceptions

Exceptions are raised by the database server automatically whenever there is any internal
database error, but exceptions can be raised explicitly by the programmer by using the command
RAISE. Following is the simple syntax of raising an exception:

DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;

Program:
(The following example illustrates the programmer-defined exceptions. We get the salary of an
employee and check it with the job’s salary range. If the salary is below the range, we raise
exception BELOW_SALARY_RANGE. If the salary is above the range, we raise exception
ABOVE_SALARY_RANGE)

SET SERVEROUTPUT ON SIZE 100000;


DECLARE
-- define exceptions
BELOW_SALARY_RANGE EXCEPTION;
ABOVE_SALARY_RANGE EXCEPTION;
-- salary variables
n_salary employees.salary%TYPE;
n_min_salary employees.salary%TYPE;
n_max_salary employees.salary%TYPE;
-- input employee id
n_emp_id employees.employee_id%TYPE := &emp_id;
BEGIN
SELECT salary,
min_salary,
max_salary
INTO n_salary,
n_min_salary,
n_max_salary
FROM employees
INNER JOIN jobs ON jobs.job_id = employees.job_id
WHERE employee_id = n_emp_id;

IF n_salary < n_min_salary THEN


RAISE BELOW_SALARY_RANGE;
ELSIF n_salary > n_max_salary THEN
RAISE ABOVE_SALARY_RANGE;
END IF;

dbms_output.put_line('Employee ' || n_emp_id ||


' has salary $' || n_salary );

EXCEPTION
WHEN BELOW_SALARY_RANGE THEN
dbms_output.put_line('Employee ' || n_emp_id ||
' has salary below the salary range');
WHEN ABOVE_SALARY_RANGE THEN
dbms_output.put_line('Employee ' || n_emp_id ||
' has salary above the salary range');
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Employee ' || n_emp_id || ' not found');
END;
/
RESULT:
Thus a PL/SQL block that handles all type of exceptions was written, executed and
verified successfully.

EX: NO:9 PROCEDURES

AIM
To write a PL/SQL block to create a procedure.
ALGORITHM
STEP1:Start
STEP2:Create a table with table name stud_exam
STEP3:Insert the values into the table and Calculate total and average of each student
STEP4: Execute the procedure function the student who get above 60%.
STEP5: Display the total and average of student
STEP6: End

EXECUTION
SETTING SERVEROUTPUT ON:
SQL> SET SERVEROUTPUT ON

I) PROGRAM:
PROCEDURE USING POSITIONAL PARAMETERS:
SQL> SET SERVEROUTPUT ON
SQL> CREATE OR REPLACE PROCEDURE PROC1 AS
2 BEGIN
3 DBMS_OUTPUT.PUT_LINE('Hello from procedure...');
4 END;
5/
Output:
Procedure created.
SQL> EXECUTE PROC1
Hello from procedure...

PL/SQL procedure successfully completed.

II) PROGRAM:
PROCEDURE USING NOTATIONAL PARAMETERS:
SQL> CREATE OR REPLACE PROCEDURE PROC2
2 (N1 IN NUMBER,N2 IN NUMBER,TOT OUT NUMBER) IS
3 BEGIN
4 TOT := N1 + N2;
5 END;
6/
OUTPUT:
Procedure created.
SQL> VARIABLE T NUMBER
SQL> EXEC PROC2(33,66,:T)
PL/SQL procedure successfully completed.
SQL> PRINT T
T
----------
99

PROCEDURE FOR GCD NUMBERS


III) PROGRAM:
SQL> create or replace procedure pro
is
a number(3);
b number(3);
c number(3);
d number(3);
begin
a:=&a;
b:=&b;
if(a>b) then
c:=mod(a,b);
if(c=0) then
dbms_output.put_line('GCD is');
dbms_output.put_line(b);
else
dbms_output.put_line('GCD is');
dbms_output.put_line(c);
end if;
else
d:=mod(b,a);
if(d=0) then
dbms_output.put_line('GCD is');
dbms_output.put_line(a);
else
dbms_output.put_line('GCD is');
dbms_output.put_line(d);
end if;
end if;
end;
/
Enter value for a: 8
old 8: a:=&a;
new 8: a:=8;
Enter value for b: 16
old 9: b:=&b;
new 9: b:=16;
Procedure created.
SQL> set serveroutput on;
SQL> execute pro;
GCD is
8
PL/SQL procedure successfully completed.

PROCEDURE FOR CURSOR IMPLEMENATION


IV) PROGRAM:
SQL> create table student(regno number(4),name varchar2)20),mark1 number(3), mark2
number(3), mark3 number(3), mark4 number(3), mark5 number(3));
Table created
SQL> insert into student values (101,'priya', 78, 88,77,60,89);
1 row created.
SQL> insert into student values (102,'surya', 99,77,69,81,99);
1 row created.
SQL> insert into student values (103,'suryapriya', 100,90,97,89,91);
1 row created.
SQL> select * from student;
regno name mark1 mark2 mark3 mark4 mark5
--------------------------------------------------------------------
101 priya 78 88 77 60 89
102 surya 99 77 69 81 99
103 suryapriya 100 90 97 89 91
SQL> declare
ave number(5,2);
tot number(3);
cursor c_mark is select*from student where mark1>=40 and mark2>=40 and
mark3>=40 and mark4>=40 and mark5>=40;
begin
dbms_output.put_line('regno name mark1 mark2 mark3 mark4 mark4 mark5 total
average');
dbms_output.put_line('-------------------------------------------------------------');
for student in c_mark
loop
tot:=student.mark1+student.mark2+student.mark3+student.mark4+student.mark5;
ave:=tot/5;
dbms_output.put_line(student.regno||rpad(student.name,15)
||rpad(student.mark1,6)||rpad(student.mark2,6)||rpad(student.mark3,6)
||rpad(student.mark4,6)||rpad(student.mark5,6)||rpad(tot,8)||rpad(ave,5));
end loop;
end;
/

SAMPLE OUTPUT
regno name mark1 mark2 mark3 mark4 mark5 total average
--------------------------------------------------------------------
101 priya 78 88 77 60 89 393 79
102 surya 99 77 69 81 99 425 85
103 suryapriya 100 90 97 89 91 467 93
PL/SQL procedure successfully completed.

EXPLICIT CURSORS AND EXPLICIT CURSORS IMPLEMENTATION


CREATING A TABLE EMP IN ORACLE
V) PROGRAM
SQL> select * from EMP;
EMPNO ENAME JOB MGR HIREDATE SAL COMM
---------- ---------- --------- ---------- --------- ---------- ----------
DEPTNO
----------
7369 SMITH CLERK 7902 17-DEC-80 800
20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300
30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500
30
EMPNO ENAME JOB MGR HIREDATE SAL COMM
---------- ---------- --------- ---------- --------- ---------- ----------
DEPTNO
----------
7566 JONES MANAGER 7839 02-APR-81 2975
20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400
30
7698 BLAKE MANAGER 7839 01-MAY-81 2850
30
EMPNO ENAME JOB MGR HIREDATE SAL COMM
---------- ---------- --------- ---------- --------- ---------- ----------
DEPTNO
----------
7782 CLARK MANAGER 7839 09-JUN-81 2450
10
7788 SCOTT ANALYST 7566 09-DEC-82 3000

7839 KING PRESIDENT 17-NOV-81 5000


10
EMPNO ENAME JOB MGR HIREDATE SAL COMM
---------- ---------- --------- ---------- --------- ---------- ----------
DEPTNO
----------
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0
30
7876 ADAMS CLERK 7788 12-JAN-83 1100
20
7900 JAMES CLERK 7698 03-DEC-81 950
30
EMPNO ENAME JOB MGR HIREDATE SAL COMM
---------- ---------- --------- ---------- --------- ---------- ----------
DEPTNO
----------
7902 FORD ANALYST 7566 03-DEC-81 3000
20
7934 MILLER CLERK 7782 23-JAN-82 1300
10
14 rows selected.

Implicit curscors:
SQL> DECLARE
2 ena EMP.ENAME%TYPE;
3 esa EMP.SAL%TYPE;
4 BEGIN
5 SELECT ENAME,SAL INTO ENA,ESA FROM EMP
6 WHERE EMPNO = &EMPNO;
7 DBMS_OUTPUT.PUT_LINE('NAME :' || ENA);
8 DBMS_OUTPUT.PUT_LINE('SALARY :' || ESA);
9
10 EXCEPTION
11 WHEN NO_DATA_FOUND THEN
12 DBMS_OUTPUT.PUT_LINE('Employee no does not exits');
13 END;

14 /
Output:
Enter value for empno: 7844
old 6: WHERE EMPNO = &EMPNO;
new 6: WHERE EMPNO = 7844;
PL/SQL procedure successfully completed.

Explicit Cursors:
SQL> DECLARE
2 ena EMP.ENAME%TYPE;
3 esa EMP.SAL%TYPE;
4 CURSOR c1 IS SELECT ename,sal FROM EMP;
5 BEGIN
6 OPEN c1;
7 FETCH c1 INTO ena,esa;
8 DBMS_OUTPUT.PUT_LINE(ena || ' salry is $ ' || esa);
9
10 FETCH c1 INTO ena,esa;
11 DBMS_OUTPUT.PUT_LINE(ena || ' salry is $ ' || esa);
12
13 FETCH c1 INTO ena,esa;
14 DBMS_OUTPUT.PUT_LINE(ena || ' salry is $ ' || esa);
15 CLOSE c1;
16 END;
17 /
Output:
SMITH salry is $ 800
ALLEN salry is $ 1600
WARD salry is $ 1250

RESULT:
Thus the PL/SQL block to create procedure is executed and verified successfully.
EX: NO: 10A FUNCTIONS

AIM
To write Functional procedures.
PROCEDURE
STEP 1: Start
STEP 2: Create the table with essential attributes.
STEP 3: Initialize the Function to carryout the searching procedure..
STEP 4: Frame the searching procedure for both positive and negative searching.
STEP 5: Execute the Function for both positive and negative result .
STEP 6: Stop

EXECUTION
SETTING SERVEROUTPUT ON:
SQL> SET SERVEROUTPUT ON

IMPLEMENTATION OF FACTORIAL USING FUNCTION


I) PROGRAM:
SQL>create function fnfact(n number)
return number is
b number;
begin
b:=1;
for i in 1..n
loop
b:=b*i;
end loop;
return b;
end;
/

SQL>Declare
n number:=&n;
y number;
begin
y:=fnfact(n);
dbms_output.put_line(y);
end;
/

Function created.
Enter value for n: 5
old 2: n number:=&n;
new 2: n number:=5;
120
PL/SQL procedure successfully completed.

II) PROGRAM
SQL> create table phonebook (phone_no number (6) primary key,username
varchar2(30),doorno varchar2(10),
street varchar2(30),place varchar2(30),pincode char(6));
Table created.
SQL> insert into phonebook values(20312,'vijay','120/5D','bharathi street','NGO
colony','629002');
1 row created.
SQL> insert into phonebook values(29467,'vasanth','39D4','RK bhavan','sarakkal vilai','629002');
1 row created.
SQL> select * from phonebook;

PHONE_NO USERNAME DOORNO STREET PLACE PINCODE


------------------------------- ------------- ---------------- --------------------
20312 vijay 120/5D bharathi street NGO colony 629002
29467 vasanth 39D4 RK bhavan sarakkal vilai 629002
SQL> create or replace function findAddress(phone in number) return varchar2 as
address varchar2(100);

begin
select username||','||doorno ||','||street ||','||place||','||pincode into address from phonebook
where phone_no=phone;
return address;
exception
when no_data_found then return 'address not found';
end;
/
Function created.
SQL>declare
2 address varchar2(100);
3 begin
4 address:=findaddress(20312);
5 dbms_output.put_line(address);
6 end;
7/

OUTPUT 1:
Vijay,120/5D,bharathi street,NGO colony,629002
PL/SQL procedure successfully completed.
SQL> declare
2 address varchar2(100);
3 begin
4 address:=findaddress(23556);
5 dbms_output.put_line(address);
6 end;
7/

OUTPUT2:
Address not found
PL/SQL procedure successfully completed.

RESULT

Thus the functions were created, executed and their respective outputs were verified.
10B.TRIGGERS

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 also specifies
the table to which the trigger is associated.
 Trigger body or trigger action: It is a PL/SQL block that is executed when the triggering
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

TYPES OF TRIGGERS

The various types of triggers are as follows,


 Before: It fires the trigger before executing the trigger statement.
 After: It fires the trigger after executing the trigger statement.
 For each row: It specifies that the trigger fires once per row.
 For each statement: This is the default trigger that is invoked. It specifies that the trigger
fires once per statement.

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

SYNTAX

create or replace trigger triggername [before/after] {DML statements}


on [tablename] [for each row/statement]
begin
-------------------------
-------------------------
-------------------------
exception
end;

USER DEFINED ERROR MESSAGE

The package “raise_application_error” is used to issue the user defined error messages
Syntax: raise_application_error(error number,„error message„);
The error number can lie between -20000 and -20999.
The error message should be a character string.

TO CREATE THE TABLE ‘ITEMPLS’

SQL> create table itempls (ename varchar2(10), eid number(5), salary number(10));
Table created.
SQL> insert into itempls values('xxx',11,10000);
1 row created.
SQL> insert into itempls values('yyy',12,10500);
1 row created.
SQL> insert into itempls values('zzz',13,15500);
1 row created.
SQL> select * from itempls;
ENAME EID SALARY
---------- --------- ---------
xxx 11 10000
yyy 12 10500
zzz 13 15500

TO CREATE A SIMPLE TRIGGER THAT DOES NOT ALLOW INSERT UPDATE AND
DELETE OPERATIONS ON THE TABLE

SQL> create trigger ittrigg before insert or update or delete on itempls for each row
2 begin
3 raise_application_error(-20010,'You cannot do manipulation');
4 end;
5
6/
Trigger created.
SQL> insert into itempls values('aaa',14,34000);
insert into itempls values('aaa',14,34000)
*
ERROR at line 1:
ORA-20010: You cannot do manipulation
ORA-06512: at "STUDENT.ITTRIGG", line 2
ORA-04088: error during execution of trigger 'STUDENT.ITTRIGG'
SQL> delete from itempls where ename='xxx';
delete from itempls where ename='xxx'
*
ERROR at line 1:
ORA-20010: You cannot do manipulation
ORA-06512: at "STUDENT.ITTRIGG", line 2
ORA-04088: error during execution of trigger 'STUDENT.ITTRIGG'
SQL> update itempls set eid=15 where ename='yyy';
update itempls set eid=15 where ename='yyy'
*
ERROR at line 1:
ORA-20010: You cannot do manipulation
ORA-06512: at "STUDENT.ITTRIGG", line 2
ORA-04088: error during execution of trigger 'STUDENT.ITTRIGG'

TO DROP THE CREATED TRIGGER

SQL> drop trigger ittrigg;


Trigger dropped.

TO CREATE A TRIGGER THAT RAISES AN USER DEFINED ERROR MESSAGE AND


DOES NOT ALLOW UPDATION AND INSERTION

SQL> create trigger ittriggs before insert or update of salary on itempls for each row
2 declare
3 triggsal itempls.salary%type;
4 begin
5 select salary into triggsal from itempls where eid=12;
6 if(:new.salary>triggsal or :new.salary<triggsal) then
7 raise_application_error(-20100,'Salary has not been changed');
8 end if;
9 end;
10 /
Trigger created.
SQL> insert into itempls values ('bbb',16,45000);
insert into itempls values ('bbb',16,45000)
*
ERROR at line 1:
ORA-04098: trigger 'STUDENT.ITTRIGGS' is invalid and failed re-validation
SQL> update itempls set eid=18 where ename='zzz';
update itempls set eid=18 where ename='zzz'
*
ERROR at line 1:
ORA-04298: trigger 'STUDENT.ITTRIGGS' is invalid and failed re-validation
RESULT

Thus the triggers were created, executed and their respective outputs were verified.

Potrebbero piacerti anche