Вы находитесь на странице: 1из 42

(III SEM / II CSE)

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 )
a) Inventory Control System.
b) Material Requirement Processing.
c) Hospital Management System.
d) Railway Reservation System.
e) Personal Information System.
f) Web Based User Identification System.
g) Timetable Management System.
h) Hotel Management System
Total : 45 Hrs


TABLE OF CONTENTS
EX.NO LIST OF EXPERIMENTS
PAGE
NUMBER
1
DATA DEFINITION, TABLE CREATION AND
CONSTRAINTS
4
2
INSERT, DELETE AND UPDATE COMMANDS
8
3
VIEWS, SYNONYMS, SEQUENCE, INDEXES, SAVE
POINT
13
4
CREATING AN EMPLOYEE DATABASE TO SET
VARIOUS CONSTRAINTS
20
5
CREATING RELATIONSHIP BETWEEN THE
DATABASES
22
6
STUDY OF PL/SQL BLOCK
23
7
PL/SQL BLOCK TO SATISFY SOME CONDITIONS BY
ACCEPTING INPUT FROM THE USER
25
8 EXCEPTION HANDLING 28
9
PROCEDURE
30
10
TRIGGERS AND FUNCTIONS
33
11
MINI PROJECT
39



REQUIREMENTS

HARDWARE:
Standalone desktops 30 Nos.
(or)
Server supporting 30 terminals or more.

SOFTWARE:
1. Front end: VB/VC ++/JAVA or Equivalent
2. Back end: Oracle / SQL / MySQL/ PostGress / DB2 or Equivalent


EX.NO :1 DATA DEFINITION, TABLE CREATION AND
CONSTRAINTS


Aim:
To manipulate and control the flow of data in a table using various DDL commands in
DBMS.

Problem Statement:

To execute various DDL commands such as create, alter, truncate, drop and desc.

NAMING RULES

Table names and column names:
Must begin with a letter
Must be 130 characters long
Must contain only AZ, az, 09, _, $, and #
Must not duplicate the name of another object owned by the same user
Must not be an Oracle server reserved word

Syntax for the commands used:

SQL> CREATE TABLE [schema.]table (column datatype[DEFAULT expr][, ...]);

You specify:

Table name
Column name, column data type, and column size



Ex:

SQL> CREATE TABLE dept (deptno NUMBER(2), dname VARCHAR2(14),
loc VARCHAR2(13));

Table created.

Confirm table creation

SQL> DESCRIBE dept;


The ALTER TABLE Statement

Use the ALTER TABLE statement to:
Add a new column
Modify an existing column
Define a default value for the new column
Drop a column

TO CREATE TABLE

SQL> create table depart(dno number(10),dname varchar2(10),primary key(dno));

Table created.

SQL> desc depart;
Name Null? Type
----------------------------------------- -------- ----------------------------
DNO NOT NULL NUMBER(10)
DNAME VARCHAR2(10)

SQL> create table emp(eno number(10),ename varchar2(10),dno number(10),sal
number(10),jobid varchar2(10),mgrid varchar2(10),foreign key(dno) references
depart(dno));

Table created





SQL> desc emp;
Name Null? Type
----------------------------------------- -------- ----------------------------
ENO NUMBER(10)
ENAME VARCHAR2(10)
DNO NUMBER(10)
SAL NUMBER(10)
JOBID VARCHAR2(10)



TO ALTER TABLE


ALTER TABLE table ADD (column datatype [DEFAULT expr]
[, column datatype]...);

ALTER TABLE table MODIFY (column datatype [DEFAULT expr]
[, column datatype]...);

ALTER TABLE table DROP (column);


SQL> alter table empdet1 add(primary key(eno),addr varchar2(10));

Table altered.

SQL> desc emp;
Name Null? Type
----------------------------------------- -------- ----------------------------
ENO NOT NULL NUMBER(10)
ENAME VARCHAR2(10)
DNO NUMBER(10)
SAL NUMBER(10)
JOBID VARCHAR2(10)
ADDR VARCHAR2(10)

SQL> alter table empdet1 add(phno number(5));

Table altered.

SQL> desc emp;
Name Null? Type
----------------------------------------- -------- ----------------------------
ENO NOT NULL NUMBER(10)
ENAME VARCHAR2(10)
DNO NUMBER(10)
SAL NUMBER(10)
JOBID CHAR(20)
ADDR VARCHAR2(10)
PHNO NUMBER(5)
DROP

SQL> alter table emp drop(phno);
Table altered.

SQL> desc emp;
Name Null? Type
----------------------------------------- -------- ----------------------------
ENO NOT NULL NUMBER(10)
ENAME VARCHAR2(10)
DNO NUMBER(10)
SAL NUMBER(10)
JOBID CHAR(20)
MGRID VARCHAR2(10)
ADDR VARCHAR2(10)

SQL> alter table emp drop(addr);

Table altered.

SQL> desc emp;

Name Null? Type
----------------------------------------- -------- ----------------------------
ENO NOT NULL NUMBER(10)
ENAME VARCHAR2(10)
DNO NUMBER(10)
SAL NUMBER(10)
JOBID CHAR(20)
MGRID VARCHAR2(10)

TO DROP THE TABLE

SQL> drop table emp;

Table dropped.
SQL> desc emp;
ERROR:
ORA-04043: object emp does not exist

Result:
Thus the commands were executed and the results were verified.

EX. NO:2 INSERT, DELETE AND UPDATE COMMANDS
Aim:
To manipulate and control the flow of data in a table using various DML commands
in RDBMS.
Problem Statement:
To execute various DML commands such as insert, delete, update.
Data Manipulation Language
A DML statement is executed when you:
Add new rows to a table
Modify existing rows in a table
Remove existing rows from a table
A transaction consists of a collection of DML statements that form a logical unit of
work.
Syntax for commands used:
Add new rows to a table by using the INSERT statement.
Only one row is inserted at a time with this syntax.
INSERT INTO table [(column [, column...])] VALUES (value [, value...]);
Insert a new row containing values for each column.
List values in the default order of the columns in the table.
Enclose character and date values within single quotation marks
Modify existing rows with the UPDATE statement
UPDATE table SET column = value[, column = value, ...] [WHERE condition];
Update more than one row at a time, if required
Specific row or rows are modified if you specify the WHERE clause.
All rows in the table are modified if you omit the WHERE clause.


DELETE FROM "table_name"WHERE {condition}
To insert contents:
SQL > Create Table Custmer1(cname varchar2(15),cid number(5),caddr char(10),
caccno number(5),cacctype varchar2(10),cbalance float, Primary
key(cid),unique(cname),unique(caccno),check(cbalance>=1000));
table created.
SQL> desc cust;
Name Null? Type
----------------------------------------- -------- ----------------------------
CNAME VARCHAR2(15)
CID NOT NULL NUMBER(5)
CADDR CHAR(10)
CACCNO NUMBER(5)
CACCTYPE VARCHAR2(10)
CBALANCE FLOAT(126)



SQL> insert into custmer1 values('Anitha',01,'Chennai',1001,'savings',15000);

1 row created.

SQL> insert into custmer1 values('Shriram',02,'Pondy',1002,'savings',25000);

1 row created.

SQL> insert into custmer1 values('Chamundi',03,'Salem',1003,'fd',36200);
1 row created.



SQL> insert into custmer1
values('&cname',&cid,'&caddr',&caccno,'&cacctype',&cbalance);
Enter value for cname: Subha
Enter value for cid: 04
Enter value for caddr: Salem
Enter value for caccno: 1009
Enter value for cacctype: 5000
Enter value for cbalance: 5000
Old 1: insert into cust values('&cname',&cid,'&caddr',&caccno,'&cacctype',&cbalance)
New 1: insert into cust values('Subha',04,'Salem',1009,'RD',5000)

1 row created.

SQL> insert into custmer1
values('&cname',&cid,'&caddr',&caccno,'&cacctype',&cbalance);
Enter value for cname: Madhan
Enter value for cid: 4
Enter value for caddr: Salem
Enter value for caccno: 1004
Enter value for cacctype: checkings
Enter value for cbalance: 5000
old 1: insert into cust values('&cname',&cid,'&caddr',&caccno,'&cacctype',&cbalance)
new 1: insert into cust values('Madhan',4,'Salem',1004,'checkings',5000)

1 row created.

SQL> insert into cust
values('&cname',&cid,'&caddr',&caccno,'&cacctype',&cbalance);
Enter value for cname: Subha
Enter value for cid: 5
Enter value for caddr: Trichy
Enter value for caccno: 1005
Enter value for cacctype: checkings
Enter value for cbalance: 10000
old 1: insert into cust values('&cname',&cid,'&caddr',&caccno,'&cacctype',&cbalance)
new 1: insert into cust values('Subha',5,'Trichy',1005,'checkings',10000)

1 row created.


SQL> insert into cust
values('&cname',&cid,'&caddr',&caccno,'&cacctype',&cbalance);
Enter value for cname: Jayashree
Enter value for cid: 6
Enter value for caddr: Pondy
Enter value for caccno: 1006
Enter value for cacctype: fd
Enter value for cbalance: 15000
old 1: insert into cust values('&cname',&cid,'&caddr',&caccno,'&cacctype',&cbalance)
new 1: insert into cust values('Jayashree',6,'Pondy',1006,'fd',15000)

1 row created.
SQL> insert into cust
values('&cname',&cid,'&caddr',&caccno,'&cacctype',&cbalance);
Enter value for cname: Sridharan
Enter value for cid: 7
Enter value for caddr: Kanchi
Enter value for caccno: 1007
Enter value for cacctype: fd
Enter value for cbalance: 22000
old 1: insert into cust values('&cname',&cid,'&caddr',&caccno,'&cacctype',&cbalance)
new 1: insert into cust values('Sridharan',7,'Kanchi',1007,'fd',22000)


SQL> select * from custmer1;

CNAME CID CADDR CACCNO CACCTYPE CBALANCE
--------------- ---------- ---------- ---------- ---------- -----------------------------------
Anusha 1 Chennai 1001 savings 15000
Shriram 2 Pondy 1002 savings 25000
Chamundi 3 Salem 1003 fd 36200
Madhan 4 Salem 1004 checkings 5000
Subha 5 Trichy 1005 checkings 10000
Jayashree 6 Pondy 1006 fd 15000
Sridharan 7 Kanchi 1007 fd 22000

7 rows selected.

SQL>update custmer1 set caccno=1111 where cname='Chamundi';

1 row updated

SQL> select * from custmer1;

CNAME CID CADDR CACCNO CACCTYPE CBALANCE
--------------- ---------- ---------- ---------- ---------- --------------------------------------
Anusha 1 Chennai 1001 savings 15000
Shriram 2 Pondy 1002 savings 25000
Chamundi 3 Salem 1111 fd 36200
Madhan 4 Salem 1004 checkings 5000
Subha 5 Trichy 1005 checkings 10000
Jayashree 6 Pondy 1006 fd 15000
Sridharan 7 Kanchi 1007 fd 22000

7 rows selected.

SQL>delete from custmer1 where cacctype='fd';

3 rows deleted

SQL> select * from custmer1;

CNAME CID CADDR CACCNO CACCTYPE CBALANCE
--------------- ---------- ---------- ---------- ---------- -------------------------------------
Anusha 1 Chennai 1001 savings 15000
Shriram 2 Pondy 1002 savings 25000
Madhan 4 Salem 1004 checkings 5000
Subha 5 Trichy 1005 checkings 10000

4 rows selected.











Result: Thus the commands were executed and the results were verified.






Ex.No:3 VIEWS, SYNONYMS, SEQUENCE, INDEXES, SAVE
POINT

Aim:
To create different views and to visualize different flow of data using view command.
Problem Statement:

To execute and verify different types of views.
View:
Logically represents subsets of data from one or more tables

Syntax for commands used:
CREATE VIEW "VIEW_NAME" AS "SQL Statement"
Creating Single Table Basic View
SQL> CREATE TABLE personh11 (person_id NUMBER(3),first_name
VARCHAR2(25),last_name VARCHAR2(25),title_1 VARCHAR2(10),title_2 VARCH
AR2(10),socsecno VARCHAR2(11));

SQL> INSERT INTO personh11 VALUES (1, 'Dan', 'Morgan', 'BS', 'PhD', '123-54-0987');

SQL> INSERT INTO personh11 VALUES (1, 'Helen', 'Lofstrom', 'BA', 'MA', '987-03-
4793');

SQL> INSERT INTO personh11 VALUES (1,'Tara','Havemeyer','BA',NULL,'402-87-
1005');
SQL> COMMIT;

SQL> set linesize 141
SQL> SELECT * FROM personh11;

SQL> CREATE OR REPLACE VIEW personh11_view AS SELECT first_name AS
FNAME, last_name LNAME, socsecno FROM personh11;

SQL> SELECT * FROM personh11_view;
Creating Single Table view with where clause
SQL> CREATE OR REPLACE VIEW personh11_two_titles_view AS SELECT first_name,
last_name, socsecno FROM personh11 WHERE title_1 IS NOT NULL AND title_2 IS NOT
NULL;
SQL> SELECT * FROM personh11_two_titles_view;
Creating Single Table view with function in the select clause and column alias
SQL> CREATE OR REPLACE VIEW functionh11_view AS SELECT
UPPER(first_name), LOWER(last_name), socsecno FROM personh11;

ALIAS THE COLUMNS

SQL> CREATE OR REPLACE VIEW functionh11_view AS SELECT UPPER(first_name)
FIRST, LOWER(last_name) LAST, socsecno FROM personh11;

SQL> SELECT * FROM functionh11_view;
Creating Single Table view for Security
SQL> CREATE OR REPLACE VIEW personh11_security_view AS SELECT first_name ||
' ' || last_name NAME, '***-**-' || SUBSTR(socsecno,8) SSN FROM personh11;

SQL> SELECT * FROM personh11_security_view;
Creating Single Table View with function in the where clause
ALTER TABLE personh11
ADD (created_by VARCHAR2(30), created_dt DATE);

SQL> UPDATE personh11 SET created_by = 'UWCLASS', created_dt = SYSDATE
WHERE last_name = 'Morgan';

SQL> UPDATE personh11
SET created_by = 'IDS', created_dt = SYSDATE+2
WHERE last_name = 'Lofstrom';

SQL> UPDATE personh11
SET created_by = 'UWCLASS', created_dt = SYSDATE-10
WHERE last_name = 'Havemeyer';

SQL> CREATE OR REPLACE VIEW user_view AS SELECT first_name, last_name,
title_1, title_2 FROM personh11 WHERE created_by = USER;


SQL> SELECT * FROM user_view;

SQL> CREATE OR REPLACE VIEW date_view AS SELECT first_name, last_name,
title_1, title_2 FROM personh11 WHERE created_dt > SYSDATE-1;

SQL> SELECT * FROM date_view;
Updatable View
SQL> CREATE TABLE demo_tab11 (person_id NUMBER(3), first_name
VARCHAR2(20), last_name VARCHAR2(20));

SQL> CREATE OR REPLACE VIEW upd_view AS SELECT * FROM demo_tab11;

SQL> INSERT INTO demo_tab11 (person_id, first_name, last_name) VALUES (1, 'Daniel',
'Morgan');

SQL> INSERT INTO demo_tab11(person_id, first_name, last_name) VALUES (2, 'Helen',
'Lofstrom');

SQL> COMMIT;

SQL> SELECT * FROM upd_view;

SQL> UPDATE upd_view SET person_id = person_id * 10;

SQL> SELECT * FROM upd_view;

desc user_updatable_columns
SQL> SELECT table_name, column_name, updatable, insertable, deletable FROM
user_updatable_columns WHERE table_name IN ( SELECT view_name FROM
user_views);






Non Updatable View
SQL> CREATE OR REPLACE VIEW nonupd_view AS SELECT DISTINCT * FROM
demo_tab11;

SQL> SELECT table_name, column_name, updatable, insertable, deletable FROM
user_updatable_columns WHERE table_name = 'NONUPD_VIEW';

SQL> SELECT * FROM nonupd_view;
SQL> UPDATE nonupd_view SET person_id = person_id * 10;
Primary Key on a view
SQL> CREATE OR REPLACE VIEW personh11_pk_view (person_id, last_name
UNIQUE RELY DISABLE NOVALIDATE, CONSTRAINT pk_personh11_view
PRIMARY KEY (person_id) RELY DISABLE NOVALIDATE) AS SELECT person_id,
last_name FROM personh11;

SELECT constraint_name, constraint_type FROM user_constraints WHERE table_name =
'PERSONh11_PK_VIEW';
Dropping Views
SELECT view_name FROM user_views;

DROP VIEW date_view;











SEQUENCE
Sql> CREATE SEQUENCE sequence
[INCREMENT BY n]
[START WITH n]
[{MAXVALUE n | NOMAXVALUE}]
[{MINVALUE n | NOMINVALUE}]
[{CYCLE | NOCYCLE}]
[{CACHE n | NOCACHE}];
SQL> CREATE SEQUENCE dept_deptid_seq
INCREMENT BY 10
START WITH 120
MAXVALUE 9999
NOCACHE
NOCYCLE;
Sequence created.

Confirming Sequences
SYNTAX:
Sql> SELECT sequence_name, min_value, max_value,
increment_by, last_number FROM user_sequences;
INDEX:
An index:
Is a schema object
Is used by the Oracle server to speed up the retrieval of rows by using a pointer
Can reduce disk I/O by using a rapid path access method to locate data quickly
Is independent of the table it indexes

Is used and maintained automatically by the Oracle server
How index are created ?
Automatically: A unique index is created automatically when you define a PRIMARY
KEY or UNIQUE constraint in a table definition.
Manually: Users can create nonunique indexes on columns to speed up access to the
rows.
Create an index on one or more columns.
Syntax:
CREATE INDEX index ON table(column[, column]...);
Ex:
SQL> CREATE INDEX emp_last_name_idx ON employees(last_name);
Improve the speed of query access to the LAST_NAME column in the EMPLOYEES
table.
Remove an index from the data dictionary by using the DROP INDEX command.
SQL> DROP INDEX index;











SYNONYMS

Simplify access to objects by creating a synonym (another name for an object). With
synonyms, you can:
Ease referring to a table owned by another user
Shorten lengthy object names
Syntax:
CREATE [PUBLIC] SYNONYM synonym FOR object;
EX:
SQL> CREATE SYNONYM d_sum FOR dept_sum_vu;
Synonym Created.
Drop a synonym.
Syntax: SQL> DROP SYNONYM d_sum;









Result:
Thus the commands were executed and the results were verified.


EX.NO :4. CREATING AN EMPLOYEE DATABASE TO SET
VARIOUS CONSTRAINTS.

What are Constraints?

Constraints enforce rules at the table level.
Constraints prevent the deletion of a table if there are dependencies.
The following constraint types are valid:
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK


CREATE TABLE [schema.]table (column datatype [DEFAULT expr]
[column_constraint],
...
[table_constraint][,...]);

Ex: CREATE TABLE employees(
employee_id NUMBER(6),
first_name VARCHAR2(20),
...
job_id VARCHAR2(10) NOT NULL,
CONSTRAINT emp_emp_id_pk
PRIMARY KEY (EMPLOYEE_ID));

The NOT NULL Constraint:

SQL> CREATE TABLE employees(
employee_id NUMBER(6),
last_name VARCHAR2(25) NOT NULL,
salary NUMBER(8,2),
commission_pct NUMBER(2,2),
hire_date DATE
CONSTRAINT emp_hire_date_nn
NOT NULL);




The UNIQUE Constraint:

SQL> CREATE TABLE employees( employee_id NUMBER(6), last_name
VARCHAR2(25) NOT NULL, email VARCHAR2(25), salary
NUMBER(8,2),
commission_pct NUMBER(2,2), hire_date DATE NOT NULL
CONSTRAINT emp_email_uk UNIQUE(email));

The PRIMARY KEY Constraint:

Ex:

SQL> CREATE TABLE departments( department_id NUMBER(4),
department_name VARCHAR2(30) CONSTRAINT dept_name_nn
NOT
NULL, manager_id NUMBER(6), location_id NUMBER(4),
CONSTRAINT dept_id_pk PRIMARY KEY(department_id));


The FOREIGN KEY Constraint:

Ex:
Sql> CREATE TABLE employees(
employee_id NUMBER(6), last_name VARCHAR2(25) NOT NULL,
email VARCHAR2(25), salary NUMBER(8,2),
commission_pct NUMBER(2,2), hire_date DATE NOT NULL,
department_id NUMBER(4), CONSTRAINT emp_dept_fk FOREIGN KEY
(department_id) REFERENCES departments(department_id),
CONSTRAINT emp_email_uk UNIQUE(email));

The CHECK Constraint:

SQL> CREATE TABLE employees(
employee_id NUMBER(6), last_name VARCHAR2(25) NOT NULL,
email VARCHAR2(25),CONSTRAINT emp_salary_min
CHECK (salary > 0));




Result:
Thus the commands were executed and the results were verified.

EX.NO :5 CREATING RELATIONSHIP BETWEEN THE
DATABASES.

SQL PRIMARY KEY Constraint
The PRIMARY KEY constraint uniquely identifies each record in a database table.
Primary keys must contain unique values.
A primary key column cannot contain NULL values.
Each table should have a primary key, and each table can have only ONE primary
key.
A foreign key is a way to enforce referential integrity within your Oracle database. A foreign
key means that values in one table must also appear in another table.
The referenced table is called the parent table while the table with the foreign key is called
the child table. The foreign key in the child table will generally reference a primary key in the
parent table.
A foreign key can be defined in either a CREATE TABLE statement or an ALTER TABLE
statement.
The PRIMARY KEY Constraint:

Ex:

Sql> CREATE TABLE departments( department_id NUMBER(4),
department_name VARCHAR2(30) CONSTRAINT dept_name_nn
NOT
NULL, manager_id NUMBER(6), location_id NUMBER(4),
CONSTRAINT dept_id_pk PRIMARY KEY(department_id));


The FOREIGN KEY Constraint:

Ex:
Sql> CREATE TABLE employees(
employee_id NUMBER(6), last_name VARCHAR2(25) NOT NULL,
email VARCHAR2(25), salary NUMBER(8,2),
commission_pct NUMBER(2,2), hire_date DATE NOT NULL,
department_id NUMBER(4), CONSTRAINT emp_dept_fk FOREIGN
KEY
(department_id) REFERENCES departments(department_id),
CONSTRAINT emp_email_uk UNIQUE(email));
Result:
Thus the commands were executed and the results were verified.
EX.NO 6 : STUDY OF PL/SQL BLOCK.

PL/SQL Blocks
PL/SQL Block Structure
DECLARE -- Declarative part (optional)
-- Declarations of local types, variables, & subprograms

BEGIN -- Executable part (required)
-- Statements (which can use items declared in declarative part)

[EXCEPTION -- Exception-handling part (optional)
-- Exception handlers for exceptions raised in executable part]
END;


Example 1:


SQL> set serveroutput on
SQL> declare
2 begin
3 for i in 1..10
4 loop
5 dbms_output.put_line(to_char(i));
6 end loop;
7* end;
8 /




Output:
1
2
3
4
5
6
7
8
9
10


Example 2: Using SELECT INTO to Assign Values to Variables
SQL> DECLARE
2 bonus NUMBER(8,2);
3 emp_id NUMBER(6) := 100;
4 BEGIN
5 SELECT salary * 0.10 INTO bonus
6 FROM employees
7 WHERE employee_id = emp_id;
8 END;
9 /

PL/SQL procedure successfully completed.

SQL>














Result: Thus the commands were executed and the results were verified




EX.NO 7: PL/SQL BLOCK TO SATISFY SOME CONDITIONS
BY
ACCEPTING INPUT FROM THE USER.

PL/SQL block structured language divide into three logical blocks. BEGIN block and
END (This not a block only keyword to end of block) are compulsory, and other two block
DECLARE and EXCEPTION is optional block.

1. The declaration section allows you to define data types, structures, and variables.
You often declare variables in the declaration section by giving them names, data
types and initial values.
2. The execution section is required in a block structure and it must have at least one
statement. The execution section is the place where you put the execution code or
business logic code. You can use both procedural and SQL statements inside the
execution section.
3. The exception handling section is starting with the EXCEPTION keyword. The
exception section is where you put the code to handle exceptions. You can either
catch or handle exceptions in the exception section.













Program:
SQL> set serveroutput on;
SQL> declare
2 a number;
3 b number;
4 c number;
5 d number;
6 begin
7 dbms_output.put_line('enter a:');
8 a:=&a;
9 dbms_output.put_line('enter b:');
10 b:=&b;
11 dbms_output.put_line('enter c:');
12 c:=&b;
13 if(a>b)and(a>c) then
14 dbms_output.put_line('A is maximum');
15 elsif(b>a)and(b>c)then
16 dbms_output.put_line('B is maximum');
17 else
18 dbms_output.put_line('C is maximum');
19 end if;
20* end;
21 /












Output:
Enter value for a: 9
old 8: a:=&a;
new 8: a:=9;
Enter value for b: 6
old 10: b:=&b;
new 10: b:=6;
Enter value for c: 10
old 12: c:=&b;
new 12: c:=10;
enter a:
enter b:
enter c:
C is maximum

PL/SQL procedure successfully completed.










Result: Thus the commands were executed and the results were verified
EX.NO :8 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 received.
PL/SQL Exception message consists of three parts.
1) Type of Exception
2) An Error Code
3) A message
General Syntax for coding the exception section
DECLARE
Declaration section
BEGI N
Exception section
EXCEPTI ON
WHEN ex_name1 THEN
-Error handling statements
WHEN ex_name2 THEN
-Error handling statements
WHEN Others THEN
-Error handling statements
END;
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;


Example:

sql> DECLARE
2 v_lname VARCHAR2 (15);
3 BEGIN
4 SELECT last_name INTO v_lname
5 FROM employees
6 WHERE first_name = 'John';
7 DBMS_OUTPUT.PUT_LINE ('Last name is :' || v_lname);
8 EXCEPTION
9 WHEN TOO_MANY_ROWS THEN
10. DBMS_OUTPUT.PUT_LINE (' Your SELECT statement retrieved multiple
rows. Consider using a cursor.');
11 END;
/
Your SELECT statement retrieved multiple rows. Consider using a cursor.

PL/SQL procedure successfully completed.




Result: Thus the commands were executed and the results were verified

EX.NO: 9 PROCEDURE
CREATE PROCEDURE
Purpose
Use the CREATE PROCEDURE statement to create a standalone stored procedure or a call
specification.
A procedure is a group of PL/SQL statements that you can call by name. A call
specification (sometimes called call spec) declares a Java method or a third-generation
language (3GL) routine so that it can be called from SQL and PL/SQL. The call spec tells
Oracle Database which Java method to invoke when a call is made. It also tells the database
what type conversions to make for the arguments and return value.
Stored procedures offer advantages in the areas of development, integrity, security,
performance, and memory allocation.
IN Specify IN to indicate that you must supply a value for the argument when calling the
procedure.
OUT Specify OUT to indicate that the procedure passes a value for this argument back to its
calling environment after execution.
IN OUT Specify IN OUT to indicate that you must supply a value for the argument when
calling the procedure and that the procedure passes a value back to its calling environment
after execution.
If you omit IN, OUT, and IN OUT, then the argument defaults to IN.



















Syntax :

SQL> create or replace procedure <procedure name> (argument
{in,out,inout} datatype ) {is,as} variable declaration;
constant
declaration
; begin
PL/SQL subprogram body;
exception
exception PL/SQL block;
end;

PROGRAM FOR GENERAL PROCEDURE SELECTED RECORDS PRICE IS
INCREMENTED BY 500 , EXECUTING THE PROCEDURE CREATED AND
DISPLAYING THE UPDATED TABLE

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

SQL> exec itsum(101, 500);
PL/SQL procedure successfully completed.

SQL> select * from ititems;
ITEMID ACTUALPRICE ORDID PRODID
--------- ----------- --------- ---------
101 2500 500 201
102 3000 1600 202
103 4000 600 202






PROCEDURE FOR IN PARAMETER CREATION, EXECUTION

SQL> set serveroutput on;

SQL> create procedure yyy (a IN number) is price number;
2 begin
3 select actualprice into price from ititems where itemid=a;
4 dbms_output.put_line('Actual price is ' || price);
5 if price is null then
6 dbms_output.put_line('price is null');
7 end if;
8 end;
9 /
Procedure created.

SQL> exec yyy(103);

Actual price is 4000
PL/SQL procedure successfully completed.









Result: Thus the commands were executed and the results were verified








EX.NO : 10 TRIGGERS AND FUNCTIONS

OBJECTIVE (AIM) OF THE EXPERIMENT
To create triggers for various events such as insertion, updation, etc.,

PL/SQL Syntax:

TRIGGER A Trigger is a stored procedure that defines an action that the database
automatically take when some database-related event such as Insert, Update or Delete occur

TRIGGER VS. PROCEDURE VS CURSOR

TRIGGER PROCEDURES CURSORS
These are named
PL/SQL blocks.


These are named
PL/SQL blocks.


These are named
PL/SQL blocks.

These are invoked
automatically.


User as per need
invokes these.


These can be created
both explicitly and
implicitly.

These cant take
parameters.


These can take
parameters.


These can take
parameters.

These are stored in
database.


These are stored in
database.


These are not stored in
database.

Syntax:
Create or replace trigger <trg_name> Before /After Insert/Update/Delete [of column_name,
column_name.]
on <table_name>
[for each row]
[when condition]
Begin
---statement
end;
Q1: Create a trigger that insert current user into a username column of an existing table c)
Procedure for doing the experiment:

Step no. Details of the step
1
Create a table itstudent4 with name and
username as arguments
2
Create a trigger for each row that insert
the current user as user name into a table
3
Execute the trigger by inserting value
into the table

Program:
SQL> create table itstudent4(name varchar2(15),username varchar2(15));

Table created.

SQL> create or replace trigger itstudent4 before insert on itstudent4 for each row
2 declare
3 name varchar2(20);
4 begin
5 select user into name from dual;
6 :new.username:=name;
7 end;
8 /

Trigger created.
Output:
SQL> insert into itstudent4 values('&name','&username');
Enter value for name: akbar
Enter value for username: ranjani
old 1: insert into itstudent4 values('&name','&username')
new 1: insert into itstudent4 values('akbar','ranjani')
1 row created.

SQL> /
Enter value for name: suji Enter value for username: priya
old 1: insert into itstudent4 values('&name','&username')
new 1: insert into itstudent4 values('suji','priya')
1 row created.
SQL> select * from itstudent4;
NAME USERNAME
---------- ----- ---------------
akbar SCOTT
suji SCOTT

Q2: Create a Simple Trigger that does not allow Insert Update and Delete Operations on the
Table d) Program:
Table used:

SQL> select * from itempls;
ENAME EID SALARY
---------- --------- ---------
xxx 11 10000
yyy 12 10500
zzz 13 15500

Trigger:

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 /
Trigger created






FUNCTIONS

There are two types of functions in Oracle.
1) Single Row Functions: Single row or Scalar functions return a value for every row
that is processed in a query.

2) Group Functions: These functions group the rows of data based on the values
returned by the query. This is discussed in SQL GROUP Functions. The group functions
are used to calculate aggregate values like total or average, which return just one total or
one average value after processing a group of rows.

There are four types of single row functions. They are:

1) Numeric Functions: These are functions that accept numeric input and return
numeric values.

2) Character or Text Functions: These are functions that accept character input and
can return both character and number values.

3) Date Functions: These are functions that take values that are of datatype DATE as
input and return values of datatype DATE, except for the MONTHS_BETWEEN
function, which returns a number.

4) Conversion Functions: These are functions that help us to convert a value in one
form to another form. For Example: a null value into an actual value, or a value from one
datatype to another datatype like NVL, TO_CHAR, TO_NUMBER, TO_DATE etc.
You can combine more than one function together in an expression. This is known as
nesting of functions.

A stored function (also called a user function or user-defined function) is a set of PL/SQL
statements you can call by name. Stored functions are very similar to procedures, except that
a function returns a value to the environment in which it is called. User functions can be used
as part of a SQL expression.






SQL>select * from ittrain;
TNO TFARE
--------- ------------
1001 550
1002 600
PROGRAM FOR FUNCTION AND ITS EXECUTION

SQL> create function trainfn (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> declare
2 total number;
3 begin
4 total:=trainfn (1001);
5 dbms_output.put_line('Train fare is Rs. '||total);
6 end;
7 /
Train fare is Rs.550
PL/SQL procedure successfully completed







FACTORIAL OF A NUMBER USING FUNCTION PROGRAM AND EXECUTION

SQL> create function itfact (a number) return number is
2 fact number:=1;
3 b number;
4 begin
5 b:=a;
6 while b>0
7 loop
8 fact:=fact*b;
9 b:=b-1;
10 end loop;
11 return(fact);
12 end;
13 /
Function created.

SQL> declare
2 a number:=7;
3 f number(10);
4 begin
5 f:=itfact(a);
6 dbms_output.put_line(The factorial of the given number is||f);
7 end;
8 /
The factorial of the given number is 5040


Result: Thus the commands were executed and the results were verified


EX.NO :11 MINI PROJECT

a) CUSTOMER SALE SCENARIO
Customer(Cust id : integer, cust_name: string)
Item(item_id: integer, item_name: string, price: integer)
Sale(bill_no: integer, bill_data: date, cust_id: integer, item_id: integer, qty_sold: integer)

For the above schema, perform the following
a) Create the tables with the appropriate integrity constraints
b) Insert around 10 records in each of the tables
c) List all the bills for the current date with the customer names and item numbers
d) List the total Bill details with the quantity sold, price of the item and the final amount
e) List the details of the customer who have bought a product which has a price>200
f) Give a count of how many products have been bought by each customer
g) Give a list of products bought by a customer having cust_id as 5
h) List the item details which are sold as of today
i) Create a view which lists out the bill_no, bill_date, cust_id, item_id, price, qty_sold,
amount
j) Create a view which lists the daily sales date wise for the last one week


Aim: Create the tables with the appropriate integrity constraints and Insert around 10 records
in each of the tables
SQL> create table customer1 (cust_id number(5) primary key, cust_name varchar2(15));
Output: Table created.
SQL> desc customer1;
Output:
Name Null? Type
----------------------------------------- -------- ----------------
CUST_ID NOT NULL NUMBER(5)
CUST_NAME VARCHAR2(15)


Valid Test Data
SQL> insert into customer1 values(&custid,'&custname');
SQL> select * from customer1;
Output:
CUST_ID CUST_NAME
---------- ---------------
100 ramu
101 kamal
102 raju
103 raju sundaram
104 lawrence
SQL> create table item(item_id number(4) primary key,
item_name varchar2(15),price number(6,2));
SQL> dsec item;
Output:
Name Null? Type

Cust_id NOT NULL NUMBER(4)


Item_name VARCHAR2(15)
PRICE NUMBER(6,2)
SQL>insert into item values(&item_id,&item_name,&price);











SQL> select * from item;

Output:
ITEM_ID ITEM_NAME PRICE
..
2334 geera 6.25
4532 corn soup 34.65
2124 lays chips 20
4531 setwet 99.99
2319 duracell 45.5

SQL>create table sale(bill_no number(5) primary key,bill_date date, cust_id number(5)
references customer(cust_id), item_id number(4) references item(item_id),qty_sold
number(4));
Out put: Table Created.
SQL>dsec sale
Output:
Name Null? Type
..
BILL_NO NOT NULL NUMBER(4)
BILL_DATE DATE
CUST_ID NUMBER(5)
ITEM_ID NUMBER(4)
QTY_SOLD NUMBER(4)

SQL>insert into Sale values(&bill_no, &bill_date, &cust_id, &item_id, &qty_sold);


SQL>select * from sale;

Output:
BILL_NO BILL_DATE CUST_ID ITEM_ID QTY_SOLD

...
1450 04-JAN-06 100 2124 2
1451 04-JAN-06 101 2319 1
1452 04-JAN-06 103 4531 2
1453 04-JAN-06 102 2334 3
1454 04-JAN-06 104 4532 3
a) List all the bills for the current date with the customer names and item numbers
SQL> select c.custname, i.itemid, s.billno from customer c, item I, sale s
where c.custid=s.custid and s.billdate=to_char(sysdate);
CUSTNAME ITEMID BILLNO
------------- --------- ---------
John 5001 332
b) List the total Bill details with the quantity sold, price of the item and the final amount

SQL> select i.price, s.qty,(i.price*s.qty) total from item I, sale s where i.itemid=s.itemid;
PRICE QTY TOTAL
------- ----- --------
120 2 240
20 3 60
5 2 10
10 1 10
350 4 1400

c) List the details of the customer who have bought a product which has a price>200
SQL> select c.custid, c.custname from customer c, sale s, item i where i.price>200 and
c.custid=s.custid and i.itemid=s.itemid;

CUSTID CUSTNAME
--------- --------------
4 duffy

d) Give a count of how many products have been bought by each customer

SQL> select custid, count(itemid) from sale group by custid;

CUSTID COUNT(ITEMID)
---------- ---------------------
1 2
3 1
4 1
5 1

e) Give a list of products bought by a customer having cust_id as 5
SQL> select i.itemname from item i, sale s where s.custid=5 and i.itemid-s.itemid;
ITEMNAME
--------------
Pens
f) List the item details which are sold as of today
SQL> select i.itemid, i.itemname from item I, sale s where i.itemid=s.itemid
and s.billdate=to_char(sysdate);
ITEMID ITEMNAME
--------- -------------
1234 pencil





i) Create a view which lists out the bill_no, bill_date, cust_id, item_id, price, qty_sold,
amount

SQL>create view cust as (select s.billno, s.billdate, c.custid, i. iitemid, i.price, s.qty
from customer c,sale s item I where c.custid=s.custid and i.iemid=s.itemid);
view created.
SQL>select * from cust;
BILLNO BILLDATE CUSTID ITEMID PRICE QTY

3432 12-JAN-06 3 3244 120 2
4424 20-FEB-06 1 3456 20 3
332 13-MAR-06 1 1234 5 2
2343 10-MAR 5 5001 10 1
1331 11-MAR-06 4 7677 350 4











Result: Thus the commands were executed and the results were verified

Вам также может понравиться