0% found this document useful (0 votes)
149 views71 pages

Dbms Lab Record

1. The document describes experiments performed on database management systems concepts like data definition language, data manipulation language, table creation commands, data insertion, updating and deletion. 2. Key commands covered include creating tables with constraints, inserting single and multiple rows of data, updating, deleting rows, and adding/dropping constraints. 3. The experiments help students learn fundamental SQL commands for defining, manipulating and managing database tables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
149 views71 pages

Dbms Lab Record

1. The document describes experiments performed on database management systems concepts like data definition language, data manipulation language, table creation commands, data insertion, updating and deletion. 2. Key commands covered include creating tables with constraints, inserting single and multiple rows of data, updating, deleting rows, and adding/dropping constraints. 3. The experiments help students learn fundamental SQL commands for defining, manipulating and managing database tables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 71

Department of Computer Science and

Engineering

DATABASE MANAGEMENT
SYSTEMS
(Integrated Course) Lab Manual
(INT18R371)

StudentName :

RegisterNumber :

Section :

1
TABLE OF CONTENTS

S.No Topic Page No.

1 Bonafide Certificate

2 Experiment Evaluation Summary

Experiments

3 DATA DEFINITION LANGUAGE

4 DATA MANIPULATION LANGUAGE

5 TCL & DCL COMMANDS

6 USAGE OF SET OPERATORS AND SUBQUERIES

7 USAGE OF SET OPERATORS AND SUBQUERIES

8 BUILDIN FUNCTIONS

9 PL / SQL BASIC PROGRAMS

10 PROCEDURES AND FUNCTIONS.

11 CURSORS

12 TRIGGERS

13 EXCEPTION HANDLING

2
SCHOOL OF COMPUTING

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

BONAFIDE CERTIFICATE

Bonafide record of workdoneby


of Btech CSE-2nd year in Kalasalingam Academy of
Research and Education during even/odd semester in academic year
____________

StaffIn-charge HeadoftheDepartment

Submitted to the practical Examination held at Kalasalingam University, Krishnankoil


on

REGISTER NUMBER

InternalExaminer ExternalExaminer
3
EXPERIMENT EVALUATION SUMMARY

Name: RegNo:

Class: Faculty:

Marks Faculty
S.No Date Experiment (100) Signature
1 DATA DEFINITION LANGUAGE
2 DATA MANIPULATION LANGUAGE
3 TCL & DCL COMMANDS
USAGE OF SET OPERATORS AND
4.a SUBQUERIES

4.b BUILDIN FUNCTIONS

USAGE OF SET OPERATORS AND


5 SUBQUERIES

PL / SQL BASIC PROGRAMS


6

7 PROCEDURES AND FUNCTIONS.

CURSORS
8

TRIGGERS
9

10 EXCEPTION HANDLING

4
Ex. No.: 1
DATA DEFINITION LANGUAGE
Date:

COMMANDS
1)Implementing NOT NULL and primaray key
SQL> create table customer_details2(
2 cust_id number(5) CONSTRAINT Nnull1 NOT NULL,
3 cust_last_name varchar2(20) CONSTRAINT Nnull2 NOT NULL,
4 cust_mid_name varchar2(4),
5 cust_first_name varchar2(20),
6 account_no number(5) CONSTRAINT Pkey10 PRIMARY KEY,
7 acccount_type varchar2(10) CONSTRAINT Nnull3 NOT NULL,
8 bank_branch varchar2(25) CONSTRAINT Nnull4 NOT NULL,
9 cust_email varchar2(30)
10 );
Table created.

2)Implementing composite primary key

SQL> create table customer_details3(


2 cust_id number(5) CONSTRAINT Nnull7 NOT NULL,
3 cust_last_name varchar2(20) CONSTRAINT Nnull8 NOT NULL,
4 cust_mid_name varchar2(4),
5 cust_first_name varchar2(20),
6 account_no number(5) CONSTRAINT Pkey10 PRIMARY KEY,
7 acccount_type varchar2(10) CONSTRAINT Nnull3 NOT NULL,
8 bank_branch varchar2(25) CONSTRAINT Nnull4 NOT NULL,
9 cust_email varchar2(30)
10 );
Table created.

3)Implementation of unique constaint


SQL> create table customer_details2(
2 ecode number(5) CONSTRAINT Pkey10 PRIMARY KEY,
3 ename varchar2(10) CONSTRAINT Nnull8 NOT NULL,
4 email varchar2(30) CONSTRAINT unql unique
5 );
Table created.

4)Implementation of primary key and foreign key

5
SQL> create table project5(
2 project_id number(3) CONSTRAINT Pkey11 PRIMARY KEY,
3 project_name varchar2(20),
4 project_location varchar2(22)
5 );
Table created.
SQL> create table employee5(
2 employee_id number(6) CONSTRAINT Pkey12 PRIMARY KEY,
3 employee_first_name varchar2(20),
4 employee_email varchar2(35),
5 grade number(2),
6 project_no number(3) CONSTRAINT Fkey13 references project5(project-ID)
7 );
Table created.

5)Alter
SQL> ALTER TABLE customer_details2
2 ADD phone_no char(10);
Table altered.

SQL> ALTER TABLE customer_details2


2 MODIFY phone_no char(12);
Table altered.

SQL> ALTER TABLE customer_details2


2 DROP (phone_no);
Table altered.

6)ADD/DROP primary key

SQL> ALTER TABLE customer_details2


2 ADD CONSTRAINT Pkey10 PRIMARY KEY(account_no);
Table altered.

SQL> ALTER TABLE customer_details2


2 DROP constraint pkey10;
Table Altered.

7)Drop table

SQL>Drop table customer_details2;


Table Droped.

8)Truncate table
SQL>Truncate table customer_details2;
Table truncated.

6
Ex. No.:2
DATA MANIPULATION LANGUAGE
Date:

Command
1)Single row insert with values for all columns
SQL> insert into customer_details2
values(55,'roshan','s','abilesh',6548,'savings','tsi','ahfhfhggh',9790625551);
1 row created.
2)Inserting one row,few columns at a time
SQL>insert into customer_details2(cust_id,cust_last_name,cust_mid_name,cust_first_name)
values (107,’Robert’,’b’,’Dan’);
1 row created.
3)Inserting NULL value into a column
SQL> insert into customer_details(customer_id,cust_last_name) values(108,NULL);
1 row created.
4)Inserting many rows form a different table
SQL>insert into old
cust_dtails(account_no,transaction_date,total_available_balance_in_dollars)select
account_no,transaction_date,total_available_balance from customer_transaction where
total_available_balance>1000;
1 row created.
5)Deleting all rows
SQL>delete form customer_details2;
Table deleted.
6)Deleting a specific rows
SQL> DELETE FROM customer_details2 WHERE cust_id=55;
1 row deleted.
7)Updating all rows
SQL> UPDATE customer_details2 SET phone_no=9991112872;
1 row updated.

8)Updating a particular row


SQL> UPDATE customer_details2 SET phone_no=9991112872 WHERE cust_id=102;
1 row updated.
9)Updating multiple columns
SQL> UPDATE customer_fixed_deposit SET
cust_email=’[email protected]’,rate_of_interest=7.3 WHERE cust_id=102;
1 row updated.
10)Get the selected colums
SQL> select cust_id,account_no from customer_details2;
CUST_ID ACCOUNT_NO
-------------------------------------- ----------

7
102 2312

11)Get all the selected columns


SQL> select * from customer_details2;

CUST_ID CUST_LAST_NAME CUST CUST_FIRST_NAME ACCOUNT_NO


ACCCOUNT_T
--------- ---------------- ---- -------------------- ----------
-----------------------------------------------------------
BANK_BRANCH CUST_EMAIL PHONE_NO
------------------------- ------------------------------ ---------------------------
102 asdsad d sad 2312 savings
indus bank [email protected] 9991112872

8
Ex. No.: 3
TCL & DCL COMMANDS
Date:

1. create a table library with the following fields


book_name,author_name,access_no,price,publisher,edition

SQL> create table library(b_name varchar(20),a_name varchar2(20),access_no


number(10),price_no numbe
r(6),publisher varchar2(30),edition varchar2(25));

Table created.
2. add constraints,(a) primary key for access_no (b)unique for book_name (c)check for
price>100

SQL> alter table library add constraint keyp1 primary key (access_no);

Table altered.

SQL> alter table library add constraint keyp2 unique(b_name);

Table altered.

SQL> alter table library add constraint keyp3 check(price_no >100);

Table altered.

SQL> desc library;


Name Null? Type
------------------------------- -------- ----
B_NAME VARCHAR2(20)
A_NAME VARCHAR2(20)
ACCESS_NO NOT NULL NUMBER(10)
PRICE_NO NUMBER(6)
PUBLISHER VARCHAR2(30)
EDITION VARCHAR2(25)

3. Insert values into library using multiple row insertion(3-4)

SQL>insert into
library(b_name,a_name,access_no,price_no,publisher,edition)values('&b_name','&a_nam
e',&access_no,'&price_no','&publisher','&edition');
Enter value for b_name: visualjava++
Enter value for a_name: veningston

9
Enter value for access_no: 112233
Enter value for price_no: 500
Enter value for publisher: janet
Enter value for edition: 3rd
old 1: insert into
library(b_name,a_name,access_no,price_no,publisher,edition)values('&b_name','&a
new 1: insert into
library(b_name,a_name,access_no,price_no,publisher,edition)values('visualjava++
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C00592) violated

1 row created.

SQL> /
Enter value for b_name: visualc++
Enter value for a_name: beningston
Enter value for access_no: 223344
Enter value for price_no: 400
Enter value for publisher: nirmal
Enter value for edition: 3rd
old 1: insert into
library(b_name,a_name,access_no,price_no,publisher,edition)values('&b_name','&a
new 1: insert into
library(b_name,a_name,access_no,price_no,publisher,edition)values('visualc++','
ERROR at line 1:
ORA-00001: not null constraint(SCOTT.SYS_C00592) violated

1 row created.

SQL> /
Enter value for b_name: java++
Enter value for a_name: viningston
Enter value for access_no: 334455
Enter value for price_no: 490
Enter value for publisher: vinu
Enter value for edition: 1st
old 1: insert into
library(b_name,a_name,access_no,price_no,publisher,edition)values('&b_name','&a
new 1: insert into library(b_name,a_name,access_no,price_no,publisher,edition)values('java+
+','vin
ERROR at line 1:
ORA-02290: check constraint (SCOTT.SYS_C00593) violated
1 row created.

4. Count the number of books in library

10
SQL>select count(book_name)from library;
COUNT(BOOK_NAME)
----------------
3
5. Display the highest and the lowest price book

SQL> select max(price) from library;

MAX(PRICE)
----------
500

SQL> select min(price) from library;

MIN(PRICE)
----------
400

6. Commit the work you have done

SQL> commit;

Commit complete.

7. Display the details of the library table

SQL> select * from library;

B_NAME A_NAME ACCESS_NO PRICE_NO PUBLISHER


-------------------- -------------------- --------- --------- ------------------------------
EDITION
-------------------------
visualjava++ SUCHIT 112233 500 janet
3rd

visualc++ SINDHU 223344 400 nirmal


3rd

java++ SUFFI 334455 490 vinu


1st

8. Create a savepoint in the transaction

SQL> savepoint vvv;

11
Savepoint created.

9.Delete all the books and display the contents

SQL> delete from library where book_name='VISUALJAVA ++';

1 row deleted.

SQL> select * from library;

BOOK_NAME AUTHOR_NAME ACCESS_NO PRICE PUBLISHER


-------------------- -------------------- --------- --------- ------------
EDITION
-------------------------
visualjava++ veningston 112233 500 janet
3rd

corejava sethu 443355 300 samy


3rd

ANSI C++ Arumugam 993378 348 ram


31st

10.Allow the user “iiicseb45” to view the library table.

SQL> grant select on library to iiicseb45;


Grant succeeded.

11.View the table of the user “iiicseb45”.

SQL>select * from iiicseb45,vamshilibrary;

BOOKNAME AUTHORNAME ACCESSNO PRICE PUBLISHER


------------------- ---------------------- ---------------- ---------- -----------------
EDITION
-------------
SQL>cpp james 1 123 chand
2
Java henry 12 300 naveen
2
Dbms micheal 23 250 universe
1

12.Remove select on library from iiicse45;


Revoke succeeded.

12
Ex. No.: 4.a)
Usage of set operators and subqueries
Date:

1) create a table staff_details with the following fields enrollment_no


designation,salary,house_no

SQL> create table staffdetails(enrollment_no varchar2(10),designation varchar2(15),salary


number(5),
house_no number(3));
Table created.

2) Create a table student_details with the following fields


enrollment_no,house_no,year,CGPA,id

SQL> create table studentdetails(enrollment_no varchar2(10),house_no number(3),year


number(4),cgpa number(4),id varchar2(9));
Table created.

3)Insert atleast 4 rows of values in staff_details and student_details


SQL> insert into staffdetails values('a001','lecturer',18000,80);
1 row created.

SQL> insert into staffdetails values('a002','lecturer',18000,18);


1 row created.

SQL> insert into staffdetails values('a003','seniorlecturer',32000,20);


1 row created.

SQL> insert into staffdetails values('a004','seniorlecturer',38000,30);


1 row created.

SQL> insert into staffdetails values('s0001','lecturer',30000,18);


1 row created.

SQL> insert into studentdetails values('s0001',18,1985,10,'03f608');


1 row created.

SQL> insert into studentdetails values('s0002',40,1986,7,'03f115');


1 row created.

SQL> insert into studentdetails values('s0003',80,1985,7,'03f610');

13
1 row created.

SQL> insert into studentdetails values('s0004',70,1982,7,'03f619');


1 row created.

SQL> insert into studentdetails values('a0001',80,1985,7,'03f610');


1 row created.
4)1.)Display the staff_details contents

SQL> select * from staffdetails;

ENROLLMENT DESIGNATION SALARY HOUSE_NO


-------------------------------------------------------------------------------
a0001 lecturer 18000 80
a0002 lecturer 18000 18
a0003 lecturer 32000 20
a0004 senior lecturer 38000 30
4)2.)Display the student_details contents
SQL> select * from studentdetails;

ENROLLMENT HOUSE_NO YEAR CGPA ID


-----------------------------------------------------------------------
s0001 18 1985 10 07u07
s0002 14 1989 9 07v46
s0003 23 1995 9 07t35
s0004 24 1998 8 07u61
5)List out the enrollment_no & house_no together in staff_details & student_details
SQL> select enrollment_no,house_no from staffdetails union select enrollment_no,house_no
from studentdetails;

ENROLLMENT HOUSE_NO
---------- ---------
a0001 80
a0002 18
a0003 20
a0004 30
s0001 18
s0002 14
s0003 23
s0004 24
8 rows selected.
6)List out the enrollment_no & phone_no which are in student_details but not in
staff_details.
SQL> select enrollment_no,house_no from studentdetails minus select enrollment_no,house_no
from staf
fdetails;

14
ENROLLMENT HOUSE_NO
---------- ---------
s0001 18
s0002 14
s0003 23
s0004 24

7)List out the enrollment_no & phone_no which are in staff_details but not in
student_details:
SQL> select enrollment_no,house_no from staffdetails minus select enrollment_no,house_no
from stude
ntdetails;

ENROLLMENT HOUSE_NO
---------- ---------
a0001 80
a0002 18
a0003 20
a0004 30

8)List out the house_no which are present both in staff & student_details.
SQL> select house_no from staffdetails intersect select house_no from studentdetails;

HOUSE_NO
---------
18

9)List out the student house_no and enrollement who are participating in MTA and NSS
activity

SQL> select house_no,enrollment_no from studentdetails where enrollment_no not in(select


enrollment
_no from activity where activity='MTA'and activity='NSS');

HOUSE_NO ENROLLMENT
---------------------------------------
18 s0001
14 s0002
23 s0003
24 s0004
10)give the unique house_no,enrollment of the students participating in NSS

SQL> select distinct house_no,enrollment_no from studentdetails where enrollment_no in(select


enrol
lment_no from activity where activity='NSS');

15
HOUSE_NO ENROLLMENT
--------- ----------
18 s0001
23 s0003

11)Give the enrollment_no of the students who are in MTA but not in NSS
SQL> select enrollment_no from studentdetails where enrollment_no in(select enrollment_no
from activ
ity where activity not in'NSS'and activity in 'MTA');

ENROLLMENT
----------
s0002

12) Give the enrollment_no of the students who are in KALAI


SQL> select enrollment_no from studentdetails where enrollment_no in(select enrollment_no
from activ
ity where activity not in'KALAI');

ENROLLMENT
----------
s0001
s0002
s0003

13)List out enrollment_no of the students who are final years having CGPA>8

SQL> select enrollment_no from studentdetails where CGPA>8;

ENROLLMENT
----------
s0001
s0002
s0003

16
Ex. No.: 4.b)
Usage of set operators and subqueries
Date:

EXERCISE:
1. create a tablestaff_details with the following fields
enrollment_nodesignation,salary,house_no.  
    CREATE TABLE staff_details (
     enrollment_no INTEGER PRIMARY KEY,
     designation TEXT NOT NULL,
     salary TEXT NOT NULL,
      TEXT NOT NULL,
     phone_no TEXT NOT NULL
   );
              

 2 Create a table student_details with the following fields


enrollment_no,house_no,,CGPA,Year,id
        CREATE TABLE student_details (
           studentId INTEGER PRIMARY KEY,
           enrollment_no  TEXT NOT NULL,
            house_no TEXT NOT NULL,
            year  TEXT NOT NULL,
           CGPA TEXT NOT NULL
       );

           
   3.Insert at least 4 rows of values in staff_details and student_details.
i.
INSERT INTO staff_details VALUES (200000001, 'staff manager', '150000', '45-
A22gv','90000404256');
INSERT INTO staff_details VALUES (300000002, 'accountant',    '100000','54-
B33hc' ,'90004000678');

17
INSERT INTO staff_details VALUES (400000003, 'vice chairman', '250000','12-
Df45f','98765434333');
INSERT INTO staff_details VALUES (600000003, ' chairman', '550000','12-
D44eg','98765443233');
INSERT INTO staff_details VALUES (900000006, 'account manager', '200000','42-
D45as','98765432222');

ii.

INSERT INTO student_details VALUES (20000001, '2345678886', '6-ab654c','I','8');


INSERT INTO student_details VALUES (30000002, '4577893335', '5-cgtf67','II','9');
INSERT INTO student_details VALUES (40000003, '5788988894', '9-afrt67','I','7');
INSERT INTO student_details VALUES (50000004, '7775554433', '7-dr56gg','III','8');
INSERT INTO student_details VALUES (60000005, '9876543322', '6-cgt56f','IV','9');

  4.i)Display the staff_details contents.


    SELECT * FROM staff_details;

  ii)Display the student_details contents


  SELECT * FROM student_details;
         

18
           

5)List out the enrollment_no & house_no together in staff_details & student_details (union)
    SELECT enrollment_no,house_no FROM staff_details where salary > 100000 UNION SELECT 
enrollment_no,house_no FROM student_details where cgpa >= 7;
            

               

               

6)List out the enrollment_no & phone_no which are in student_details but not in staff_details.(USING
Minus)
SELECT enrollment_no,phone_no from staff_details WHERE phone_no not in (SELECT
enrollment_no
FROM staff_details);

      
7) List out the enrollment_no & phone_no which are in staff_details but not in Student_details:
    SELECT enrollment_no, house_no FROM staff_details WHERE phone_no not in (SELECT
enrollment_no
FROM staff_details);

  

19
           
8)List out the house_no which are present both in staff & student_details. (intersect)
SELECT house_no FROM staff_details WHERE house_no in (SELECT house_no FROM
student_details); 

ff &   
****output is empty because no common house_no in staf &student_details.******

9)List out the student house_no and enrollement who are participating in MTA and NSS activity (sub query)
select distinct house_no,enrollment_no from student_details where enrollment_no in (select *
from nss) and (enrollment_no in (select * from mta));

     
Output:
Enrollment_no
______________________
10)give the unique house_no,enrollment of the students participating in NSS(sub query)
select distinct house_no,enrollment_no from student_details where enrollment_no in (select *
from nss);

    

Output:
Enrollment_no
______________________

20
Ex. No.: 5
Buildin functions
Date:

SQL has many built-in functions for performing processing on string or numeric data. Following is the list of all useful SQL
built-in functions –

 SQL COUNT Function - The SQL COUNT aggregate function is used to count the number of rows in a database
table.
 SQL MAX Function - The SQL MAX aggregate function allows us to select the highest (maximum) value for a
certain column.
 SQL MIN Function - The SQL MIN aggregate function allows us to select the lowest (minimum) value for a certain
column.
 SQL AVG Function - The SQL AVG aggregate function selects the average value for certain table column.
 SQL SUM Function - The SQL SUM aggregate function allows selecting the total for a numeric column.
 SQL SQRT Functions - This is used to generate a square root of a given number.
 SQL RAND Function - This is used to generate a random number using SQL command.
 SQL CONCAT Function - This is used to concatenate any string inside any SQL command.

SQL COUNT function:

Syntax:

SELECT COUNT(column_name)
FROM table_name
WHERE condition;

SQL MAX Function:

Syntax:

SELECT MAX(column_name)
FROM table_name
WHERE condition;

21
SQL MIN Function :

Syntax:

SELECT MIN(column_name)
FROM table_name
WHERE condition;

SQL AVG Function:

Syntax:

SELECT AVG(column_name)
FROM table_name
WHERE condition;

22
SQL SUM Function:

Syntax:

SELECT SUM(column_name)
FROM table_name
WHERE condition;

SQL SQRT Functions:

Syntax:

SELECT SQRT(64);

SQL RAND Function :

Syntax:

SELECT RAND();

23
SQL CONCAT Function  :

Syntax:

CONCAT(string1, string2, ...., string_n)

24
PL/SQL
What is 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.
Oracle PL/SQL is an extension of SQL language, designed for seamless processing of
SQL statements enhancing the security, portability, and robustness of the database. This
PL/SQL online programming course explains some important aspect of PL SQL
language like block structure, data types, packages, triggers, exception handling, etc.
PL/SQL is not case sensitive so you are free to use lower case letters or upper case
letters except within string and character literals. 

Following are the different type of PL/SQL units.

 Anonymous Block
 Function
 Library
 Procedure

25
 Package Body
 Package Specification
 Trigger
 Type
 Type Body

Features & Advantages of PL/SQL


1. Better performance, as SQL is executed in bulk rather than a single statement
2. High Productivity
3. Tight integration with SQL
4. Full Portability
5. Tight Security
6. Supports Object Oriented Programming concepts.
7. Scalability and Manageability
8. Supports Web Application Development
9. Supports Server Page Development

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 Handling (or Error) 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:

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

How a Sample PL/SQL Block Looks

DECLARE
     Variable declaration
BEGIN
     Program Execution
EXCEPTION
     Exception handling
END;

DBMS_OUTPUT :

The DBMS_OUTPUT is a built-in package that enables you to display output,


debugging information, and send messages from PL/SQL blocks, subprograms,
packages, and triggers.

Eg:

dbms_output.put_line('Hello Reader!');

27
PL/SQL Variables
A variable is a meaningful name which facilitates a programmer to store data temporarily during
the execution of code. It helps you to manipulate data in PL/SQL programs. It is nothing except
a name given to a storage area. Each variable in the PL/SQL has a specific data type which
defines the size and layout of the variable's memory.

A variable should not exceed 30 characters. Its letter optionally followed by more letters, dollar
signs, numerals, underscore etc.

How to declare variable in PL/SQL


You must declare the PL/SQL variable in the declaration section or in a package as a
global variable. After the declaration, PL/SQL allocates memory for the variable's value
and the storage location is identified by the variable name.

Syntax for declaring variable:

Following is the syntax for declaring variable:

variable_name  datatype := value;
Example:

Radius Number := 5;

Date_of_birth date;

Declaration Restrictions:

In PL/SQL while declaring the variable some restrictions hold.

o Forward references are not allowed i.e. you must declare a constant or
variable before referencing it in another statement even if it is a declarative
statement.
val number := Total - 200;
Total number := 1000;

28
o
The first declaration is illegal because the TOTAL variable must be declared
before using it in an assignment expression.
o Variables belonging to the same datatype cannot be declared in the same
statement.
N1, N2, N3 Number;
It is an illegal declaration.

Naming rules for PL/SQL variables


The variable in PL/SQL must follow some naming rules like other programming
languages.

o The variable_name should not exceed 30 characters.


o Variable name should not be the same as the table table's column of that block.
o The name of the variable must begin with ASCII letter. The PL/SQL is not case
sensitive so it could be either lowercase or uppercase. For example: v_data and
V_DATA refer to the same variables.
o You should make your variable easy to read and understand, after the first
character, it may be any number, underscore (_) or dollar sign ($).
o NOT NULL is an optional specification on the variable.

Initializing Variables in PL/SQL


Evertime you declare a variable, PL/SQL defines a default value NULL to it. If you want to
initialize a variable with other value than NULL value, you can do so during the
declaration, by using any one of the following methods.

o The DEFAULT keyword


o The assignment operator

1. counter binary_integer := 0;  
2. greetings varchar2(20) DEFAULT 'Hello JavaTpoint'; 

29
Example:
DECLARE  
   a integer := 30;  
   b integer := 40;  
   c integer;  
   f real;  
BEGIN  
   c := a + b;  
   dbms_output.put_line('Value of c: ' || c);  
   f := 100.0/3.0;  
   dbms_output.put_line('Value of f: ' || f);  
END;  

After the execution, this will produce the following result:

Value of c: 70
Value of f: 33.333333333333333333

PL/SQL procedure successfully completed.

PL/SQL Constants
A constant is a value used in a PL/SQL block that remains unchanged throughout the program.
It is a user-defined literal value. It can be declared and used instead of actual values.

Syntax to declare a constant:

1. constant_name CONSTANT datatype := VALUE;  
o Constant_name:it is the name of constant just like variable name. The constant
word is a reserved word and its value does not change.
o VALUE: it is a value which is assigned to a constant when it is declared. It can not
be assigned later.

30
Example of PL/SQL constant
Let's take an example to explain it well:

1. DECLARE  
2.    -- constant declaration  
3.    pi constant number := 3.141592654;  
4.    -- other declarations  
5.    radius number(5,2);   
6.    dia number(5,2);   
7.    circumference number(7, 2);  
8.    area number (10, 2);  
9. BEGIN   
10.    -- processing  
11.    radius := 9.5;   
12.    dia := radius * 2;   
13.    circumference := 2.0 * pi * radius;  
14.    area := pi * radius * radius;  
15.    -- output  
16.    dbms_output.put_line('Radius: ' || radius);  
17.    dbms_output.put_line('Diameter: ' || dia);  
18.    dbms_output.put_line('Circumference: ' || circumference);  
19.    dbms_output.put_line('Area: ' || area);  
20. END;  
21. /  

After the execution of the above code at SQL prompt, it will produce the following
result:.

Radius: 9.5  
Diameter: 19  
Circumference: 59.69  
Area: 283.53  
  
Pl/SQL procedure successfully completed. 

31
Control Statements
PL/SQL If
PL/SQL supports the programming language features like conditional statements and iterative
statements. Its programming constructs are similar to how you use in programming languages
like Java and C++.

Syntax for IF Statement:

There are different syntaxes for the IF-THEN-ELSE statement.

Syntax: (IF-THEN statement):

1. IF condition   
2. THEN   
3. Statement: {It is executed when condition is true}  
4. END IF;  

This syntax is used when you want to execute statements only when condition is TRUE.

Syntax: (IF-THEN-ELSE statement):

1. IF condition   
2. THEN  
3.    {...statements to execute when condition is TRUE...}  
4. ELSE  
5.    {...statements to execute when condition is FALSE...}  
6. END IF;   

This syntax is used when you want to execute one set of statements when condition is TRUE or a
different set of statements when condition is FALSE.

Syntax: (IF-THEN-ELSIF statement):

1. IF condition1   
2. THEN  
3.    {...statements to execute when condition1 is TRUE...}  
4. ELSIF condition2   
5. THEN  
6.    {...statements to execute when condition2 is TRUE...}  

32
7. END IF;  

This syntax is used when you want to execute one set of statements when condition1 is TRUE or
a different set of statements when condition2 is TRUE.

Syntax: (IF-THEN-ELSIF-ELSE statement):

1. IF condition1   
2. THEN  
3.    {...statements to execute when condition1 is TRUE...}  
4. ELSIF condition2   
5. THEN  
6.    {...statements to execute when condition2 is TRUE...}  
7. ELSE  
8.    {...statements to execute when both condition1 and condition2 are FALSE...}  
9. END IF;  

Example of PL/SQL If Statement


Let's take an example to see the whole concept:

1. DECLARE  
2.    a number(3) := 500;  
3. BEGIN  
4.    -- check the boolean condition using if statement   
5.    IF( a < 20 ) THEN  
6.       -- if condition is true then print the following    
7.       dbms_output.put_line('a is less than 20 ' );  
8.    ELSE  
9.       dbms_output.put_line('a is not less than 20 ' );  
10.    END IF;  
11.    dbms_output.put_line('value of a is : ' || a);  
12. END;  

a is not less than 20


value of a is : 500
PL/SQL procedure successfully completed.

33
PL/SQL Case Statement
The PL/SQL CASE statement facilitates you to execute a sequence of satatements based on a
selector. A selector can be anything such as variable, function or an expression that the CASE
statement checks to a boolean value.

The CASE statement works like the IF statement, only using the keyword WHEN. A CASE
statement is evaluated from top to bottom. If it get the condition TRUE, then the corresponding
THEN calause is executed and the execution goes to the END CASE clause.

Syntax for the CASE Statement:

1. CASE [ expression ]  
2. WHEN condition_1 THEN result_1  
3.    WHEN condition_2 THEN result_2  
4.    ...  
5.    WHEN condition_n THEN result_n  
6.  ELSE result  
7. END   case

Example of PL/SQL case statement


Let's take an example to make it clear:

1. DECLARE  
2.    grade char(1) := 'A';  
3. BEGIN  
4.    CASE grade  
5.       when 'A' then dbms_output.put_line('Excellent');  
6.       when 'B' then dbms_output.put_line('Very good');  
7.       when 'C' then dbms_output.put_line('Good');  
8.       when 'D' then dbms_output.put_line('Average');  
9.       when 'F' then dbms_output.put_line('Passed with Grace');  
10.       else dbms_output.put_line('Failed');  
11.    END CASE;  
12. END;  

After the execution of above code, you will get the following result:

Excellent
PL/SQL procedure successfully completed.

34
PL/SQL Loop
The PL/SQL loops are used to repeat the execution of one or more statements for
specified number of times. These are also known as iterative control statements.

Syntax for a basic loop:

1. LOOP  
2.   Sequence of statements;  
3. END LOOP;  

Types of PL/SQL Loops


There are 4 types of PL/SQL Loops.

1. Basic Loop / Exit Loop


2. While Loop
3. For Loop
4. Cursor For Loop

PL/SQL Exit Loop (Basic Loop)


PL/SQL exit loop is used when a set of statements is to be executed at least once before the
termination of the loop. There must be an EXIT condition specified in the loop, otherwise the
loop will get into an infinite number of iterations. After the occurrence of EXIT condition, the
process exits the loop.

Syntax of basic loop:

1. LOOP  
2.   Sequence of statements;  
3. END LOOP;  

Syntax of exit loop:

1. LOOP   
2.    statements;   
3.    EXIT;   
4.    {or EXIT WHEN condition;}  
5. END LOOP;  

35
Example of PL/SQL EXIT Loop
Let's take a simple example to explain it well:

1. DECLARE  
2. i NUMBER := 1;  
3. BEGIN  
4. LOOP  
5. EXIT WHEN i>10;  
6. DBMS_OUTPUT.PUT_LINE(i);  
7. i := i+1;  
8. END LOOP;  
9. END;  

After the execution of the above code, you will get the following result:

1
2
3
4
5
6
7
8
9
10

Note: You must follow these steps while using PL/SQL Exit Loop.

o Initialize a variable before the loop body


o Increment the variable in the loop.
o You should use EXIT WHEN statement to exit from the Loop. Otherwise the EXIT
statement without WHEN condition, the statements in the Loop is executed only
once.

PL/SQL While Loop


PL/SQL while loop is used when a set of statements has to be executed as long as a condition is
true, the While loop is used. The condition is decided at the beginning of each iteration and
continues until the condition becomes false.

36
Syntax of while loop:

1. WHILE <condition>   
2.  LOOP statements;   
3. END LOOP;  

Example of PL/SQL While Loop

Let's see a simple example of PL/SQL WHILE loop.

1. DECLARE  
2. i INTEGER := 1;  
3. BEGIN  
4. WHILE i <= 10 
5. LOOP  
6. DBMS_OUTPUT.PUT_LINE(i);  
7. i := i+1;  
8. END LOOP;  
9. END;  

After the execution of the above code, you will get the following result:

1
2
3
4
5
6
7
8
9
10

PL/SQL FOR Loop

PL/SQL for loop is used when when you want to execute a set of statements
for a predetermined number of times. The loop is iterated between the start
and end integer values. The counter is always incremented by 1 and once
the counter reaches the value of end integer, the loop ends.
37
Syntax of for loop:

1. FOR counter IN initial_value .. final_value 
2. LOOP  
3.   LOOP statements;   
4. END LOOP;  
o initial_value : Start integer value

o final_value : End integer value

PL/SQL For Loop Example 1


Let's see a simple example of PL/SQL FOR loop.

1. BEGIN  
2. FOR k IN 1..10 LOOP  
3. -- note that k was not declared  
4. DBMS_OUTPUT.PUT_LINE(k);  
5. END LOOP;  
6. END;   

After the execution of the above code, you will get the following result:

1
2
3
4
5
6
7
8
9
10

Note: You must follow these steps while using PL/SQL WHILE Loop.

o You don't need to declare the counter variable explicitly because it is declared implicitly in the declaration section.
o The counter variable is incremented by 1 and does not need to be incremented explicitly.
o You can use EXIT WHEN statements and EXIT statements in FOR Loops but it is not done often.

PL/SQL For Loop Example 2

1. DECLARE   
2. VAR1 NUMBER;  
3. BEGIN   

38
4. VAR1:=10;  
5. FOR VAR2 IN 1..10  
6. LOOP  
7. DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);  
8. END LOOP;  
9. END;  

Output:

10
20
30
40
50
60
70
80
90
100

PL/SQL For Loop REVERSE Example 3


Let's see an example of PL/SQL for loop where we are using REVERSE keyword.

1. DECLARE   
2. VAR1 NUMBER;  
3. BEGIN   
4. VAR1:=10;  
5. FOR VAR2 IN REVERSE 1..10  
6. LOOP  
7. DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);  
8. END LOOP;  
9. END;  

Output:

100
90
80
70
60
50
40
30
20
10

39
PL/SQL Procedure
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one or
more specific tasks. It is just like procedures in other programming languages.

The procedure contains a header and a body.

o Header: The header contains the name of the procedure and the parameters or
variables passed to the procedure.
o Body: The body contains a declaration section, execution section and exception
section similar to a general PL/SQL block.

How to pass parameters in procedure:


When you want to create a procedure or function, you have to define parameters .There is three
ways to pass parameters in procedure:

1. IN parameters: The IN parameter can be referenced by the procedure or


function. The value of the parameter cannot be overwritten by the procedure or
the function.
2. OUT parameters: The OUT parameter cannot be referenced by the procedure or
function, but the value of the parameter can be overwritten by the procedure or
function.
3. INOUT parameters: The INOUT parameter can be referenced by the procedure
or function and the value of the parameter can be overwritten by the procedure
or function.

A procedure may or may not return any value.

PL/SQL Create Procedure


Syntax for creating procedure:

1. CREATE OR REPLACE PROCEDURE procedure_name  
2.     [ (parameter [,parameter]) ]  
3. IS  
4.     [declaration_section]  
5. BEGIN  

40
6.     executable_section  
7. [EXCEPTION  
8.     exception_section]  
9. END [procedure_name];  

Create procedure example


In this example, we are going to insert record in user table. So you need to create user table
first.

Table creation:

1. create table user(id number(10) primary key,name varchar2(100));  

Now write the procedure code to insert record in user table.

Procedure Code:

1. create or replace procedure "INSERTUSER" (id IN NUMBER,    name IN VARCHAR2)    
2. is    
3. begin    
4. insert into user values(id,name);    
5. end;    
6. /       

Output:

Procedure created.

PL/SQL program to call procedure


Let's see the code to call above created procedure.

1. BEGIN    
2.    insertuser(101,'Rahul');  
3.    dbms_output.put_line('record inserted successfully');    
4. END;    
5. /    

Now, see the "USER" table, you will see one record is inserted.

41
ID Name

101 Rahul

PL/SQL Drop Procedure


Syntax for drop procedure

1. DROP PROCEDURE procedure_name;   

Example of drop procedure

DROP PROCEDURE pro1; 

Ex: 6
1. a)create a table “billcalculator” containing
house_no,c_name,previous_reading,current_reading,unit,amount.
b)calculate and update the field units and amount with pl/sql as follows.
Calculate the units by using formulas.
i)if the unit >150 then amount is 100+unit*1.5.
ii)if the unit >50 and unit <50 then amount is 50+unit*0.5
else unit is multiplied with factor 0.5
Write a procedure which updates unit and amount.

PL/SQL Function
The PL/SQL Function is very similar to PL/SQL Procedure. The main difference
between procedure and a function is, a function must always return a value, and
on the other hand a procedure may or may not return a value. Except this, all the
other things of PL/SQL procedure are true for PL/SQL function too.

Syntax to create a function:

1. CREATE [OR REPLACE] FUNCTION function_name [parameters]  
2. [(parameter_name [IN | OUT | IN OUT] type [, ...])]  
3. RETURN return_datatype  
4. {IS | AS}  
5. BEGIN  
6.    < function_body >  
7. END [function_name];  

42
Here:

o Function_name: specifies the name of the function.


o [OR REPLACE] option allows modifying an existing function.
o The optional parameter list contains name, mode and types of the parameters.
o IN represents that value will be passed from outside and OUT represents that this
parameter will be used to return a value outside of the procedure.

The function must contain a return statement.


o RETURN clause specifies that data type you are going to return from the function.
o Function_body contains the executable part.
o The AS keyword is used instead of the IS keyword for creating a standalone
function.

PL/SQL Function Example

Let's see a simple example to create a function.

1. create or replace function adder(n1 in number, n2 in number)    
2. return number    
3. is     
4. n3 number(8);    
5. begin    
6. n3 :=n1+n2;    
7. return n3;    
8. end;    
9. /    

Now write another program to call the function.

1. DECLARE    
2.    x number(2);    
3. BEGIN    
4.    x := adder(11,22);    
5.    dbms_output.put_line('Addition is: ' || x);    
6. END;    
7. /    

Output:

Addition is: 33

43
Statement processed.
0.05 seconds

Another PL/SQL Function Example

Let's take an example to demonstrate Declaring, Defining and Invoking a simple PL/SQL
function which will compute and return the maximum of two values.

1. DECLARE  
2.    a number;  
3.    b number;  
4.    c number;  
5. FUNCTION findMax(x IN number, y IN number)   
6. RETURN number  
7. IS  
8.     z number;  
9. BEGIN  
10.    IF x > y THEN  
11.       z:= x;  
12.    ELSE  
13.       Z:= y;  
14.    END IF;  
15.   
16.    RETURN z;  
17. END;   
18. BEGIN  
19.    a:= 23;  
20.    b:= 45;  
21.   
22.    c := findMax(a, b);  
23.    dbms_output.put_line(' Maximum of (23,45): ' || c);  
24. END;  
25. /  

Output:

44
Maximum of (23,45): 45
Statement processed.
0.02 seconds

PL/SQL function example using table

Let's take a customer table. This example illustrates creating and calling a standalone
function. This function will return the total number of CUSTOMERS in the customers
table.

Create customers table and have records in it.

Customers

Id Name Department Salary

1 alex web developer 35000

2 ricky program developer 45000

3 mohan web designer 35000

4 dilshad database manager 44000

Create Function:

1. CREATE OR REPLACE FUNCTION totalCustomers  
2. RETURN number
3.  IS  
4.    total number(2) := 0;  
5. BEGIN  
6.    SELECT count(*) into total  FROM customers;  
7.     RETURN total;  
8. END;  
9. /  

After the execution of above code, you will get the following result.

Function created.

Calling PL/SQL Function:

45
While creating a function, you have to give a definition of what the function has to do. To use a function, you will have to call
that function to perform the defined task. Once the function is called, the program control is transferred to the called
function.

After the successful completion of the defined task, the call function returns program control back to the main program.

To call a function you have to pass the required parameters along with function name and if function returns a value then
you can store returned value. Following program calls the function totalCustomers from an anonymous block:

1. DECLARE  
2.    c number(2);  
3. BEGIN  
4.    c := totalCustomers();  
5.    dbms_output.put_line('Total no. of Customers: ' || c);  
6. END;  
7. /  

After the execution of above code in SQL prompt, you will get the following result.

Total no. of Customers: 4


PL/SQL procedure successfully completed.

46
Ex. No.: 6
PL / SQL basic programs
Date:

Exercises:
1. WRITE A PL/SQL PROGRAM TO SWAP TWO NUMBERS WITH OUT
TAKING THIRD VARIABLE
2. WRITE A PL/SQL PROGRAM TO FIND THE LARGEST OF TWO NUMBERS
3. WRITE A PL/SQL PROGRAM TO FIND THE TOTAL AND AVERAGE OF 6
SUBJECTS AND DISPLAY THE GRADE.
4. WRITE A PL/SQL PROGRAM TO CHECK WHETHER THE GIVEN
NUMBER IS AN ARMSTRONG NUMBER OR NOT
5. WRITE A PL/SQL PROGRAM TO FIND THE SUM OF DIGITS IN A GIVEN
NUMBER.
6. WRITE A PL/SQL PROGRAM TO DISPLAY THE NUMBER IN REVERSE
ORDER.
7. WRITE A PL/SQL PROGRAM TO CHECK WHETHER THE GIVEN
NUMBER IS PRIME OR NOT
8. WRITE A PL/SQL PROGRAM TO FIND THE FACTORIAL OF A GIVEN
NUMBER
9. WRITE A PL/SQL PROGRAM TO GENERATE FIBONACCI SERIES
10. WRITE A PL/SQL CODE BLOCK TO CALCULATE THE AREA OF A CIRCLE
FOR A VALUE OF RADIUS VARYING FROM 3 TO 7.
STORE THE RADIUS AND THE CORRESPONDING VALUES OF CALCULATED
AREA IN AN EMPTY TABLE NAMED AREAS ,CONSISTING OF TWO COLUMNS
RADIUS & AREA

QUERIES:

1)
declare
a NUMBER;
b NUMBER;
begin
a := 100;
b := 300;
dbms_output.Put_line('Before');
dbms_output.Put_line('a= ' || a ||' b = ' || b);
a := a + b;
b := a - b;
a := a - b;
dbms_output.Put_line('After');

47
dbms_output.Put_line(' a = ' || a ||' b = ' || b);
End;

2) 

DECLARE 
a NUMBER :=40 ; 
b NUMBER := 20; 
BEGIN 

if(a>b) then 
dbms_output.Put_line('max number is '||a); 
else 
dbms_output.Put_line('max number is '||b); 
end if; 
END;

3) 
DECLARE 

sub1 NUMBER := 29; 


sub2 NUMBER := 30; 
sub3 NUMBER := 36; 
sub4 NUMBER := 40; 
sub5 NUMBER := 45; 

48
sub6 NUMBER := 50; 

sumOf6 NUMBER; 

avgOf6 NUMBER; 

grade char(1); 

BEGIN 

sumOf6 := sub1+sub2+sub3+sub4+sub5+sub6; 

avgOf6 := sumOf6 / 6; 

if(sub1<20 or sub2<20 or sub3<20 or sub4<20 or sub5<20 or sub6<20) then grade :=


'Fail'; 
elsif(avgOf6>=50) then grade := 'A+'; 
elsif(avgOf6>=40) then grade := 'A';
elsif(avgOf6>=30) then grade := 'B'; 
elsif(avgOf6>=20) then grade := 'C'; 
else 
grade := 'D'; 
end if; 

dbms_output.Put_line('Sum = ' ||sumOf6); 

dbms_output.Put_line('Average = ' ||avgOf6); 

dbms_output.Put_line('grade = ' ||grade); 

END; 

4) 
declare 
n number:=407; 

49
s number:=0; 
r number; 
len number; 
m number; 
begin 
m:=n;
len:=length(to_char(n)); 

while n>0 
loop 
r:=mod(n,10); 
s:=s+power(r,len); 
n:=trunc(n/10); 
end loop; 

if m=s 
then 
dbms_output.put_line('armstrong number'); 
else 
dbms_output.put_line('not armstrong number'); 
end if; 

End; 

5) 

DECLARE 

n INTEGER; 
temp_sum INTEGER; 
r INTEGER; 

BEGIN 
n := 123456; 
temp_sum := 0;
WHILE n <> 0 LOOP 

50
r := MOD(n, 10); 
temp_sum := temp_sum + r; 
n := Trunc(n / 10); 

END LOOP; 

dbms_output.Put_line('sum of digits = ' || temp_sum); 

END; 

6) 

DECLARE 
num number; 
reverse_num number:=0; 

begin 
num:=98765; 
while num>0 
loop 
reverse_num:=(reverse_num*10) + mod(num,10); 
num:=trunc(num/10); 
end loop; 

dbms_output.put_line(' Reversed number is : '|| reverse_num);


end; 

51
7) 

declare 
n number; 
i number; 
temp number; 

begin 
n := 13; 
i := 2; 
temp := 1; 

for i in 2..n/2 

loop 

if mod(n, i) = 0 
then 
temp := 0; 

exit; 
end if; 

end loop; 

if temp = 1
then 

dbms_output.put_line('prime'); 

else 

dbms_output.put_line('not prime'); 

end if; 

End; 

52
8) 

declare 
num number := 5; 
fact number := 1; 
temp number; 

begin 
temp := num; 
while( temp>0) 
loop 
fact := fact*temp; 
temp := temp-1; 

end loop;
dbms_output.Put_line('factorial of ' || num || ' is ' || fact); 
end; 

9) 

declare 
a number :=0; 
b number :=1; 
temp number; 
n number := 10; 

53
i number; 

begin 
dbms_output.Put_line('fibonacci series is : '); 
dbms_output.Put_line(a); 
dbms_output.Put_line(b); 
for i in 2..n 
loop 
temp := a+b; 
a := b; 
b := temp; 
dbms_output.Put_line(temp); 
end loop; 
End;

10) 

create table circle(radius number(5),area number(10)); 

Declare

radius number;

area number; 

begin 
for radius in 3..7 
loop
 area :=3.14*radius*radius; 
insert into circle(radius,area)values(radius,area);
end
loop; 

54
end; 

select * from circle;

55
Ex. No.: 7
PROCEDURES AND FUNCTIONS.
Date:

1.)create a table “billcalculator” containing


house_no,c_name,previous_reading,current_reading,unit,amount.

SQL> create table bill_calc(house_no number(5),c_name varchar2(20),prev_rding


number(5),curr_rding n
umber(5),unit number(10),amount number(20));

Table created.

SQL> desc bill_calc;


Name Null? Type
------------------------------- -------- ----
HOUSE_NO NUMBER(5)
C_NAME VARCHAR2(20)
PREV_RDING NUMBER(5)
CURR_RDING NUMBER(5)
UNIT NUMBER(10)
AMOUNT NUMBER(20)

SQL> insert into bill_calc


values('&house_no','&c_name','&prev_rding','&curr_rding','&unit','&amou
t');
Enter value for house_no: 10
Enter value for c_name: ram
Enter value for prev_rding: 1
Enter value for curr_rding: 44
Enter value for unit:
Enter value for amount:
old 1: insert into bill_calc
values('&house_no','&c_name','&prev_rding','&curr_rding','&unit','&
new 1: insert into bill_calc values('10','ram','1','44','','')

1 row created.

SQL> /
Enter value for house_no: 20
Enter value for c_name: raj
Enter value for prev_rding: 50
Enter value for curr_rding: 250
Enter value for unit:

56
Enter value for amount:
old 1: insert into bill_calc
values('&house_no','&c_name','&prev_rding','&curr_rding','&unit','&
new 1: insert into bill_calc values('20','raj','50','250','','')

1 row created.

SQL> select * from bill_calc;

HOUSE_NO C_NAME PREV_RDING CURR_RDING UNIT AMOUNT


--------- -------------------- ---------- ---------- --------- -------------------------------------------
10 ram 1 44
20 raj 50 250

2.)a)calculate and update the field units and amount with pl/sql as follows.
Calculate the units by using formulas.
i)if the unit >150 then amount is 100+unit*1.5.
ii)if the unit >50 and unit <50 then amount is 50+unit*0.5
else unit is multiplied with factor 0.5
Write a procedure which updates unit and amount.

SQL> create or replace procedure calculate(h_no number,p_rding number,c_rding number)


2 is
3 unitt number;
4 amt number(8,2);
5 begin
6 unitt:=c_rding-p_rding;
7 if(unitt>150)then
8 amt:=100+unitt*1.5;
9 else if(unitt>50 and unitt<100)then
10 amt:=50+unitt*0.5;
11 else
12 amt:=unitt*0.5;
13 end if;
14 end if;
15 update bill_calc set amount=amt where house_no=h_no;
16 update bill_calc set unit=unitt where house_no=h_no;
17 end;
18 /
Procedure created.
SQL> declare
2 cursor c1 is select house_no,prev_rding,curr_rding from bill_calc;
3 d c1%rowtype;
4 begin
5 for d in c1
6 loop

57
7 calculate(d.house_no,d.prev_rding,d.curr_rding);
8 end loop;
9 end;
10 /

PL/SQL procedure successfully completed.

SQL> select * from bill_calc;

HOUSE_NO C_NAME PREV_RDING CURR_RDING UNIT AMOUNT


--------- -------------------- ---------- ---------- --------- -------------------------------------------
10 ram 1 44 43 22
20 raj 50 250 200 400

Enter value for item_id: 1


Enter value for item_desc: hamam
Enter value for bal_stock: 100
old 1: insert into item_master values('&item_id','&item_desc','&bal
new 1: insert into item_master values('1','hamam','100')
1 row created.

SQL> /
Enter value for item_id: 2
Enter value for item_desc: colgate
Enter value for bal_stock: 200
old 1: insert into item_master values('&item_id','&item_desc','&bal
new 1: insert into item_master values('2','colgate','200')
1 row created.

b) Write a function to find an “itembuyed” is present in the “itemmaster” based on the


return values the item is updated with totalstock or is it inserted as a new item.

SQL> select *from item_master;

ITEM_ID ITEM_DESC BAL_STOCK


--------- -------------------- ------------------------------
1 hamam 100
2 colgate 200

SQL> create table item_buyed(item_id number(5),item_desc varchar2(20),quantity number(5));


Table created.

SQL> insert into item_buyed values('&item_id','&item_desc','&quantity');


Enter value for item_id: 1
Enter value for item_desc: hamam

58
Enter value for quantity: 23
old 1: insert into item_buyed values('&item_id','&item_desc','&quantity')
new 1: insert into item_buyed values('1','hamam','23')

1 row created.

SQL> /
Enter value for item_id: 2
Enter value for item_desc: colgate
Enter value for quantity: 78
old 1: insert into item_buyed values('&item_id','&item_desc','&quantity')
new 1: insert into item_buyed values('2','colgate','78')

1 row created.

SQL> /
Enter value for item_id: 3
Enter value for item_desc: ponds
Enter value for quantity: 45
old 1: insert into item_buyed values('&item_id','&item_desc','&quantity')
new 1: insert into item_buyed values('3','ponds','45')

1 row created.

SQL> /
Enter value for item_id: 4
Enter value for item_desc: lizol
Enter value for quantity: 12
old 1: insert into item_buyed values('&item_id','&item_desc','&quantity')
new 1: insert into item_buyed values('4','lizol','12')

1 row created.

SQL> select * from item_buyed;

ITEM_ID ITEM_DESC QUANTITY


--------- -------------------- ---------
1 hamam 23
2 colgate 78
3 ponds 45
4 lizol 12

59
SQL> create or replace function iii(itemsid varchar2) return number
2 is
3 cursor c1 is select item_id from item_master;
4 d c1%rowtype;
5 begin
6 for d in c1
7 loop
8 if(d.item_id=itemsid)then
9 return 0;
10 end if;
11 end loop;
12 return 1;
13 end;
14 /

Function created.

declare
itid item_master.item_id%type;
iteid item_buyed.item_id%type;
balst item_master.bal_stock%type;
quant item_buyed.quantity%type;
itemdesc item_buyed.item_desc%type;
itemdeesc item_master.item_desc%type;
cursor c is select item_id,item_desc,bal_stock from item_master;
cursor d is select item_id,item_desc,quantity from item_buyed;
retval number;
begin
retval:=0;
open d;
open c;
fetch c into itid,itemdeesc,balst;
loop
fetch d into iteid,itemdesc,quant;
retval:=iii(iteid);
if(retval=0)then
update item_master set bal_stock=balst+quant where item_id=iteid;
else if(retval=1)then
insert into item_master values(iteid,itemdesc,quant);
end if;
end if;
exit when(d% notfound);
end loop;

60
close d;
close c;
end;
/

PL/SQL procedure successfully completed.

SQL> select * from item_master;

ITEM_ID ITEM_DESC BAL_STOCK


--------- -------------------- ---------
1 hamam 123
2 colgate 178
3 ponds 45
4 lizol 112

61
Ex. No.: 8
Cursors
Date:

PL/SQL Cursor

When an SQL statement is processed, Oracle creates a memory area known as context area. A
cursor is a pointer to this context area. It contains all information needed for processing the
statement. In PL/SQL, the context area is controlled by Cursor. A cursor contains information on
a select statement and the rows of data accessed by it.

Use of Cursor:
The major function of a cursor is to retrieve data, one row at a time, from a result set, unlike
the SQL commands which operate on all the rows in the result set at one time. Cursors are used
when the user needs to update records in a singleton fashion or in a row by row manner, in a
database table.

A cursor is used to referred to a program to fetch and process the rows returned by the SQL
statement, one at a time. There are two types of cursors:

o Implicit Cursors
o Explicit Cursors

1) PL/SQL Implicit Cursors

The implicit cursors are automatically generated by Oracle while an SQL statement is executed,
if you don't use an explicit cursor for the statement.

These are created by default to process the statements when DML statements like INSERT,
UPDATE, DELETE etc. are executed.

Orcale provides some attributes known as Implicit cursor's attributes to check the status of DML
operations. Some of them are: %FOUND, %NOTFOUND, %ROWCOUNT and %ISOPEN.

For example: When you execute the SQL statements like INSERT, UPDATE, DELETE then the
cursor attributes tell whether any rows are affected and how many have been affected. If you run
a SELECT INTO statement in PL/SQL block, the implicit cursor attribute can be used to find out
whether any row has been returned by the SELECT statement. It will return an error if there no
data is selected.

The following table specifies the status of the cursor with each of its attribute.

62
Attribute Description

%FOUND Its return value is TRUE if DML statements like


INSERT, DELETE and UPDATE affect at least one
row or more rows or a SELECT INTO statement
returned one or more rows. Otherwise it returns
FALSE.
%NOTFOUND Its return value is TRUE if DML statements like
INSERT, DELETE and UPDATE affect no row, or a
SELECT INTO statement return no rows. Otherwise it
returns FALSE. It is a just opposite of %FOUND.
%ISOPEN It always returns FALSE for implicit cursors, because
the SQL cursor is automatically closed after executing
its associated SQL statements.
%ROWCOUN It returns the number of rows affected by DML
T statements like INSERT, DELETE, and UPDATE or
returned by a SELECT INTO statement.
Syntax:
DECLARE
CURSOR <cursor_name> IS <SELECT statement^>
<cursor_variable declaration>
BEGIN
OPEN <cursor_name>;
FETCH <cursor_name> INTO <cursor_variable>;
.
.
CLOSE <cursor_name>;
END;

PL/SQL Implicit Cursor Example

Create customers table and have records:

ID NAME AGE ADDRESS SALARY

1 Ramesh 23 Allahabad 20000


2 Suresh 22 Kanpur 22000
3 Mahesh 24 Ghaziabad 24000
4 Chandan 25 Noida 26000

63
5 Alex 21 Paris 28000
6 Sunita 20 Delhi 30000

Let's execute the following program to update the table and increase salary of each customer by
5000. Here, SQL%ROWCOUNT attribute is used to determine the number of rows affected:

Create procedure:

1. DECLARE   
2.    total_rows number(2);  
3. BEGIN  
4.    UPDATE  customers  
5.    SET salary = salary + 5000;  
6.    IF sql%notfound THEN  
7.       dbms_output.put_line('no customers updated');  
8.    ELSIF sql%found THEN  
9.       total_rows := sql%rowcount;  
10.       dbms_output.put_line( total_rows || ' customers updated ');  
11.    END IF;   
12. END;  
13. /  

Output:

6 customers updated
PL/SQL procedure successfully completed.

Now, if you check the records in customer table, you will find that the rows are updated.

1. select * from customers;  
ID NAME AGE ADDRESS SALARY

1 Ramesh 23 Allahabad 25000

64
2 Suresh 22 Kanpur 27000
3 Mahesh 24 Ghaziabad 29000
4 Chandan 25 Noida 31000
5 Alex 21 Paris 33000
6 Sunita 20 Delhi 35000

2) PL/SQL Explicit Cursors

The Explicit cursors are defined by the programmers to gain more control over the context area.
These cursors should be defined in the declaration section of the PL/SQL block. It is created on a
SELECT statement which returns more than one row.

Following is the syntax to create an explicit cursor:

Syntax of explicit cursor

Following is the syntax to create an explicit cursor:

CURSOR cursor_name IS select_statement;;  

Steps:

You must follow these steps while working with an explicit cursor.

1. Declare the cursor to initialize in the memory.


2. Open the cursor to allocate memory.
3. Fetch the cursor to retrieve data.
4. Close the cursor to release allocated memory.

1) Declare the cursor:

It defines the cursor with a name and the associated SELECT statement.

Syntax for explicit cursor decleration

1. CURSOR name IS  
2.  SELECT statement;   

65
2) Open the cursor:

It is used to allocate memory for the cursor and make it easy to fetch the rows returned by the
SQL statements into it.

Syntax for cursor open:

1. OPEN cursor_name;  

3) Fetch the cursor:

It is used to access one row at a time. You can fetch rows from the above-opened cursor as
follows:

Syntax for cursor fetch:

FETCH cursor_name INTO variable_list;  

4) Close the cursor:

It is used to release the allocated memory. The following syntax is used to close the above-
opened cursors.

Syntax for cursor close:

Close cursor_name;  

PL/SQL Explicit Cursor Example

Explicit cursors are defined by programmers to gain more control over the context area. It is
defined in the declaration section of the PL/SQL block. It is created on a SELECT statement
which returns more than one row.

Let's take an example to demonstrate the use of explicit cursor. In this example, we are using the
already created CUSTOMERS table.

Create customers table and have records:

ID NAME AGE ADDRESS SALARY

1 Ramesh 23 Allahabad 20000

2 Suresh 22 Kanpur 22000

3 Mahesh 24 Ghaziabad 24000

4 Chandan 25 Noida 26000

66
5 Alex 21 Paris 28000

6 Sunita 20 Delhi 30000

Create procedure:

Execute the following program to retrieve the customer name and address.

1. DECLARE  
2.    c_id customers.id%type;  
3.    c_name customers.name%type;  
4.    c_addr customers.address%type;  
5.    CURSOR c_customers  is  
6.       SELECT id, name, address FROM customers;  
7. BEGIN  
8.    OPEN c_customers;  
9.    LOOP  
10.       FETCH c_customers into c_id, c_name, c_addr;  
11.       EXIT WHEN c_customers%notfound;  
12.       dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);  
13.    END LOOP;  
14.    CLOSE c_customers;  
15. END;  
16. /  

Output:

1 Ramesh Allahabad
2 Suresh Kanpur
3 Mahesh Ghaziabad
4 Chandan Noida
5 Alex Paris
6 Sunita Delhi
PL/SQL procedure successfully completed.

67
Ex. No.: 9
Triggers
Date:

Triggers in PL/SQL. Triggers are stored programs, which are automatically executed or fired
when some events occur. Triggers are, in fact, written to be executed in response to any of the
following events −
 A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
 A database definition (DDL) statement (CREATE, ALTER, or DROP).
 A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the event is
associated.
Benefits of Triggers
Triggers can be written for the following purposes −

 Generating some derived column values automatically


 Enforcing referential integrity
 Event logging and storing information on table access
 Auditing
 Synchronous replication of tables
 Imposing security authorizations
 Preventing invalid transactions

Creating Triggers

The 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)
DECLARE
Declaration-statements
BEGIN
Executable-statements

68
EXCEPTION
Exception-handling-statements
END;
Where,
 CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing
trigger with the trigger_name.
 {BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be executed.
The INSTEAD OF clause is used for creating trigger on a view.
 {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
 [OF col_name] − This specifies the column name that will be updated.
 [ON table_name] − This specifies the name of the table associated with the trigger.
 [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old values
for various DML statements, such as INSERT, UPDATE, and DELETE.
 [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be executed
for each row being affected. Otherwise the trigger will execute just once when the SQL
statement is executed, which is called a table level trigger.
 WHEN (condition) − This provides a condition for rows for which the trigger would fire.
This clause is valid only for row-level triggers.
Example: 1
create or replace trigger trig1 after insert on item_master for each row
declare
begin
dbms_output.put_line('***User has created a row***');
end;
/

Trigger created.
Example 2
To start with, we will be using the CUSTOMERS table we had created and used in the previous
chapters −
Select * from customers;

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

69
| 6 | Komal | 22 | MP | 4500.00 |

The following program creates a row-level trigger for the customers table that would fire for
INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This
trigger will display the salary difference between the old values and new values −
CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/

Ex. No.: 10
EXCEPTION HANDLING

70
An exception is an error which disrupts the normal flow of program instructions.
PL/SQL provides us the exception block which raises the exception thus
helping the programmer to find out the fault and resolve it.
There are two types of exceptions defined in PL/SQL
1. User defined exception.
2. System defined exceptions.

QUERY:

CREATE TABLE customers 



id number(10)NOT NULL, 
name varchar(50)NOT NULL, 
address varchar(50) not null 
)
insert into customers values(1,'srija','hyd')
insert into customers values(2,'kavya','assom')
insert into customers values(3,'sindhu','shimla')
select*from customers

DECLARE   
   c_id customers.id%type := 6;   
   c_name  customers.name%type;   
   c_addr customers.address%type;   
BEGIN   
   SELECT  name, address INTO  c_name, c_addr   
   FROM customers   
   WHERE id = c_id;   
DBMS_OUTPUT.PUT_LINE ('Name: '||  c_name);   
 DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);   
EXCEPTION   
   WHEN no_data_found THEN   
      dbms_output.put_line('No such customer!');   
   WHEN others THEN   
      dbms_output.put_line('Error!');   
END; 

71

You might also like