Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
184 views96 pages

Dbms Lab Manual

This document outlines the lab manual for the Database Management System (DBMS) lab course at Kalasalingam University. It includes details such as the course objectives, pre-requisites, experiments to be conducted, evaluation criteria, and topics to be covered. The topics include working with data definition and manipulation commands in SQL, building PL/SQL programs using functions, procedures, triggers and cursors, embedded SQL, and database connectivity using ODBC. Students will be evaluated based on their performance on 10 experiments over the semester.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
184 views96 pages

Dbms Lab Manual

This document outlines the lab manual for the Database Management System (DBMS) lab course at Kalasalingam University. It includes details such as the course objectives, pre-requisites, experiments to be conducted, evaluation criteria, and topics to be covered. The topics include working with data definition and manipulation commands in SQL, building PL/SQL programs using functions, procedures, triggers and cursors, embedded SQL, and database connectivity using ODBC. Students will be evaluated based on their performance on 10 experiments over the semester.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 96

SCHOOL OF COMPUTING

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LAB MANUAL

INT18R371 – DATABASE MANAGEMENT SYSTEM LAB


SCHOOL OF COMPUTING

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

BONAFIDE CERTIFICATE

Bonafide record of work done by


of _ in
during even/odd semester in academic year

Staff In-charge Head of the Department

Submitted to the practical Examination held at Kalasalingam University, Krishnankoil on

________________________________

REGISTER NUMBER

Internal Examiner External Examiner


EXPERIMENT EVALUATION SUMMARY

Name: Reg No :

Class : Faculty : Dr. R. Mohandas

Marks Faculty
S.No Date Experiment
(100) Signature

1 Working with DDL commands

2 Working with DML and DCL


Commands

3 Working with Built-in functions of


SQL

4 Simple PL/SQL programs

5 PL/SQL programs using cursor

6 PL/SQL programs using Functions

7 PL/SQL programs using Procedures

8 PL/SQL programs using Triggers

9 Embedded SQL

10 Database Connectivity using ODBC


TABLE OF CONTENTS

S.No Topic Page


No

1. Working with DDL commands

2. Working with DML and DCL commands

3. Working with Built-in functions of SQL

4. Simple PL/SQL programs

5. PL/SQL programs using cursor

6. PL/SQL programs using Functions

7. PL/SQL programs using Procedures

8. PL/SQL programs using Triggers

9. Embedded SQL

10. Database Connectivity using ODBC


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
ODD SEMESTER 2018-2019

LABORATORY COURSE PLAN

Subject with code DBMS Lab /INT18R371


Course B.Tech (CSE)
Semester / Sec IV
Course Credit 4
Course Coordinator Mr.R.Nirmalan
Module Coordinator Dr. R. Murugeswari
Programme Coordinator Dr.N.C.Brindha

PRE-REQUISITE:

General understanding of programming concepts and some programming experience in C


language.

COURSE DESCRIPTION:

The major objective of this lab is to provide a strong foundation in database concepts, technology
and practice to the participants to groom them into database application developers.

COURSE OBJECTIVES:

To give a good foundation on the relation model of data.


To impart systematic database design approaches covering conceptual, logical and physical design.
To present the concepts and techniques relating to query processing by SQL and ODBC.

PROGRAM EDUCATIONAL OBJECTIVES COMPONENTS (PEOS)

PEO1: Technical Proficiency:


The graduates are trained to gain employment as an it professional and higher studies to cater the global
needs.
PEO2: Professional Growth:
The graduates could comprehend, analyze, design and create novel products and
technologies that provide solution to real world problems.
PEO3: Management Skills:
The graduates acquire multidisciplinary knowledge with ethical standards, effective communication skills
and management skills to work as part of teams on all diverse professional environments.
PROGRAMME OUTCOMES (POS)

PO1: Ability to apply knowledge of mathematics, science and computer engineering to solve computational
problems.

PO2: Ability to identify, formulates, analyze and derive conclusions in complex computing problems.

PO3: Capability to design and develop computing systems to meet the requirement of industry and society with
due consideration for public health, safety and environment.

PO4: Ability to apply the knowledge of design of experiment and data analysis to derive solutions in complex
computing problems.

PO5: Ability to develop and apply modeling, simulation and prediction tools and techniques to engineering
problems.

PO6: Ability to assess and understand the professional, legal, security and societal responsibilities relevant to
computer engineering practice.

PO7: Ability to understand the impact of computing solutions in economic, environmental and societal context
for sustainable development.

PO8: Applying ethical principles and commitment to ethics of IT and software profession.

PO9: Ability to work effectively as an individual as well as in teams.

PO10: Ability to communicate effectively with technical community and with society.

PO11: Demonstrating and applying the knowledge of computer engineering and management principles in
software project development and in multidisciplinary areas.

PO12: Understanding the need for technological changes and engage in life-long learning.

PROGRAMME SPECIFIC OBJECTIVES (PSO)

A graduate of the Computer Science and Engineering Program will have

PSO1: Problem-Solving Skills: The ability to apply mathematics, science and computer engineering knowledge to
analyze, design and develop cost effective computing solutions for complex problems with environmental
considerations.

PSO2: Professional Skills: The ability to apply modern tools and strategies in software project development using
modern programming environments to deliver a quality product for business accomplishment.

PSO3: Communication and Team Skill: The ability to exhibit proficiency in oral and written communication as
individual or as part of a team to work effectively with professional behaviors and ethics.

PSO 4 : Successful Career and Entrepreneurship : The ability to create a inventive career path by applying
innovative project management techniques to become a successful software professional, an entrepreneur or zest for
higher studies
Mapping of the Program’s Student Outcomes (PSOs) with the ABET Student outcomes
(ASOs)

S. ABET-CAC Student Program Student Outcome (PSOs) /PO


No outcomes (CSOs)/CO 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
CSO1 – Analyze a
complex computing
problem and to apply
1 principles of X X X X X X X
computing and other
relevant disciplines to
identify solutions.
CSO2 – Design,
implement, and
evaluates a computing-
based solution to meet
2 a given set of X X X X X
computing
requirements in the
context of the
program’s discipline.
CSO3 -- Communicate
effectively in a variety
3 X X
of professional
contexts.
CSO4 – Recognize
professional
responsibilities and
make informed
4 X X X X
judgments in
computing practice
based on legal and
ethical principles.
CSO5 – Function
effectively as a member
or leader of a team
engaged in activities
appropriate to Function
5 X X
effectively as a member
or leader of a team
engaged in activities
appropriate to the
program’s discipline.
S. ABET-CAC Student Program Student Outcome (PSOs) /PO
No outcomes (CSOs)/CO 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
CSO6 -- Apply
Computer Science X
theory and software
6 development X X X X X
fundamentals to
producePO computing-
based solutions.
Over all mapping X X X X X X X X X X X X X X X X

Mapping of the Program’s Student Outcomes (PSOs) with the ABET Student Outcomes
(ESOs)

S. ABET-EAC Student Program Student Outcome (PSOs)


No outcomes (CSOs) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
ESO1 -Ability to identify,
formulate and solve
complex engineering
1 X X X X
problems by applying
principles of Engineering,
Science, and Mathematics.
ESO2 -Ability to apply
engineering design to
produce solutions that
meet specified needs with
consideration of public
2 X X X X X
health, safety, and
welfare, as well as global,
cultural, social,
environmental, and
economic factors.
ESO3 - An ability to
3 communicate effectively X X
with a range of audiences
ESO4 -Ability to
recognize ethical and
professional
4 X X X X X
responsibilities in
engineering situations and
make informed
S. ABET-EAC Student Program Student Outcome (PSOs)
No outcomes (CSOs) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
judgments, which must
consider the impact of
engineering solutions in
global, economic,
environmental, and
societal contexts.
ESO5 -Ability to function
effectively on a team
whose members together
provide leadership, create
5 X X X
a collaborative and
inclusive environment,
establish goals, plan tasks,
and meet objectives.
ESO6 -Ability to develop
and conduct appropriate
experimentation, analyze
6 X X
and interpret data, and
use engineering judgment
to draw conclusions.
ESO7 -Ability to acquire
and apply new knowledge X
7 as needed, using X X
appropriate learning
strategies.
Overall mapping X X X X X X X X X X X X X X X X
COURSE OUTCOMES:
CO1: Design and build a database schema for a given problem domain.
CO2: Populate and query a database using SQL DML/DDL commands.
CO3: Programming PL/SQL including stored procedure, stored functions,
and cursors.

CO and PO Mapping
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3 PSO4
CO1 S M M S
CO2 S S S S S S S M L
CO3 S S S L
S- Strong Correlation M- Medium Correlation L – Low Correlation

LIST OF EXPERIMENTS (AS PER SYLLABUS):


Cumulative
No. of
Exp. No. No. of
Name of the Experiment periods
periods
Cycle – I

1. Working with DDL commands 3 3


2. Working with DML and DCL commands 3 6
3. Working with Built-in functions of SQL 3 9
4. Programs using PL/SQL and Cursors 3 15
5. Working with Triggers 3 18
6. Working with Stored Procedures and Functions 3 21
Cycle – II
7. Embedded SQL 3 30
8. Database Connectivity using ADO 3 36
Database Connectivity using ODBC 3 39
9.
Database Connectivity using JDBC 3 42
10.
11. Model Exam
New Additional Experiments:

1. A hospital wants to maintain the patient details. A patient may be in patient or outpatient. Patient details patient
ID, patient name, address, and disease information are stored in database;
a. Design ER diagram for patient monitoring systems database
b. Write SQL query for the following
(i) Insert patient details
(ii) Display the patient and diseases details
(iii) Update the patient after diagnosis
(iv) Modify the patients details
(v) Delete the patient details
2. University wants to track persons associated with them. A person can be an Employee or Student. Employees are
Faculty, Technicians and Project associates. Students are Full time students, Part time students and Teaching
Assistants.

a) Design an Enhanced Entity Relationship (EER) Model for university database.


Write OQL for the following
i. Insert details in each object.
ii. Display the Employee details.
iii. Display Student Details.
iv. Modify person details.
v. Delete person details.
vi. Update the salary details

3.Consider the application for University Counseling for Engineering Colleges. The college, department and vacancy
details are maintained in 3 sites. Students are allocated colleges in these 3 sites simultaneously. Implement this application
using parallel database.
4. There are 5 processors working in a parallel environment and producing output. The output record contains college
details and students mark information. Implement parallel join and parallel sort algorithms to get the marks from different
colleges of the university and publish 10 ranks for each discipline.

Assessment Method:
S.no Assessment Split up
Regular Lab Exercises (6)
1
Internal Assessment (20 marks) Model Lab (8)
X-Component (6)
2 External Assessment (15 marks) End semester Lab (15)

INTRODUCTION

A data base management system is a collection of programs that enables users to create and
maintain a database. DBMS is a general purpose software system that facilitates the process of
defining, constructing, manipulating databases for various applications.
Functions of DBMS
• Database Definition -how data is to be stored and organized
• Database Creation -storing data in a defined database
• Data Retrieval-Querying and reporting
• Updating-changing the contents of the data base
• Programming user facilities for system development.
• Database revision and restructuring
• Database integrity control.
• Performance monitoring.
Ex: No: 1 DATA DEFINITION LANGUAGE (DDL)
AIM:
To execute the various Data Definition Language commands in RDBMS.
OBJECTIVE:
After completing the exercise the students can able to Understand how to create a table
with list of fields, Modify a row using where clause, Drop a table, Delete the unwanted rows in a
table.
DATA DEFINITION LANGUAGE
It is used to communicate with database. DDL is used Tto:

Create an object

Alter the structure of an object

To drop the object created.

ALGORITHM:
Step 1: Start the program
Step 2: Go to SQL.
Step 3: Enter the user name and password.
Step 4: Connect to the database.
Step 5: Type the commands for creating tables and perform various operations on
the tables.
Step 6: The output is displayed.
Step 7: Stop the program

DDL COMMAND:

• CREATE
• ALTER
• DROP
• TRUNCATE
• RENAME
CREATION OF TABLE
CREATE TABLE STUDENT(STUDENTREGNO integer(5), STUDENTNAME varchar(10), DEPARTMENT varchar(7), MOBILENO
integer(10));
DESC STUDENT;
CREATE TABLE STUDENT1 AS SELECT * FROM STUDENT;
DESC STUDENT1;
CREATE TABLE STUDENT2 AS SELECT STUDENTREGNO, STUDENTNAME FROM STUDENT;
DESC STUDENT2;
ALTER TABLE STUDENT MODIFY DEPARTMENT varchar(8);
DESC STUDENT;
ALTER TABLE STUDENT ADD DOB integer(10);
DESC STUDENT;
ALTER TABLE STUDENT ADD (ADDRESS varchar(10), SECTION varchar(10));
DESC STUDENT;
ALTER TABLE STUDENT DROP COLUMN SECTION;
DESC STUDENT;
OUTPUT
EVALUATION

Sl.No Module Max. Marks Marks Obtained


1 Database schema 25
2 Database query 25
3 Output 20
4 Technical Skill 20
5 Communication Skill 10
Total 100

Faculty Signature

RESULT:

Thus the SQL commands for DDL commands in RDBMS has been verified and executed
successfully.
Ex: No: 2 DATA MANIPULATION LANGUAGE (DML)
AIM:

To execute and verify the DML commands are the most frequently used SQL
commands and is used to query and manipulate the existing database objects.

DML (DATA MANIPULATION LANGUAGE)

• SELECT
• INSERT
• DELETE
• UPDATE

ALGORITHM:

STEP 1: Start the DBMS.

STEP 2: Create the table with its essential attributes.

STEP 3: Insert the record into table

STEP 4: Update the existing records into the table

STEP 5: Delete the records in to the table

STEP 6: use save point if any changes occur in any portion of the record to undo its original
state.

STEP 7: use rollback for completely undo the records

STEP 8: use commit for permanently save the records

COMMANDS:
CREATE TABLE STUDENT (STUDENTNO integer(4),SNAME VARCHAR(20),DEPARTMENT VARCHAR(10),SECTION VARCHAR(4));
INSERT INTO STUDENT VALUES(0001, 'AARTHI', 'CSE', 'G');
INSERT INTO STUDENT(STUDENTNO,SNAME,DEPARTMENT,SECTION) VALUES(0002,'JOO','ECE','F');
INSERT INTO STUDENT(STUDENTNO,SNAME,DEPARTMENT,SECTION) VALUES(0003,'LAHARI','EEE', 'H');
INSERT INTO STUDENT(STUDENTNO,SNAME,DEPARTMENT,SECTION) VALUES(0004,'MANU','IT','I');
SELECT*FROM STUDENT;
UPDATE STUDENT SET STUDENTNO=0005 WHERE STUDENTNO=0003;
SELECT*FROM STUDENT;
UPDATE STUDENT SET DEPARTMENT='CSE', SECTION='A' WHERE STUDENTNO=0002;
SELECT*FROM STUDENT;
DELETE FROM STUDENT WHERE STUDENTNO=0004;
SELECT*FROM STUDENT;
OUTPUT:

EVALUATION

Sl.No Module Max. Marks Marks Obtained


1 Database schema 25
2 Database query 25
3 Output 20
4 Technical Skill 20
5 Communication Skill 10
Total 100

Faculty Signature

RESULT:

Thus the SQL commands for DML has been verified and executed successfully
Ex: No: 3 TCL COMMANDS

AIM:
To create the SAVE POINT for the transaction and verify the various operations of TCL
commands.

OBJECTIVE:

The SAVEPOINT statement names and marks the current point in the processing of a
transaction. With the ROLLBACK TO statement, savepoints undo parts of a transaction instead of
the whole transaction.
An implicit savepoint is marked before executing an INSERT, UPDATE, or DELETE
statement. If the statement fails, a rollback to the implicit savepoint is done. Normally, just the failed
SQL statement is rolled back, not the whole transaction; if the statement raises an unhandled
exception, the host environment

ALGORITHM:

STEP 1: Start the DMBS.


STEP 2: Connect to the existing database (DB)
STEP 3: Create the table with its essential attributes.
STEP 4: Insert record values into the table or perform any kind of DML operation.
STEP 5: Create the SAVE POINTs for some set of statement on the transaction of database object.
STEP 6: Use the COMMIT command to save the effect of the previous command operation except
DDL command
STEP 7: Use the ROLLBACK TO SP_LABLE / ROLLBACK command for restore the
database status up to the save point
STEP 8: Check the status of the database.
STEP 9: Stop the DBMS.
COMMANDS
SET AUTOCOMMIT=0;
CREATE TABLE MOBILE_DETAIL(S_NO INTEGER(10),MODEL_ID NVARCHAR(50),MODEL_NAME VARCHAR(100),MOBILE_BRAND
VARCHAR(100),TOTAL_SALES INTEGER(100));
INSERT INTO MOBILE_DETAIL VALUES(1,'ONEPLUS 2','ONEPLUS_X','ONEPLUS','100');
INSERT INTO MOBILE_DETAIL VALUES(2,'VIVO1915','VIVO_PRO','VIVO','123');
SELECT*FROM MOBILE_DETAIL;
INSERT INTO MOBILE_DETAIL VALUES(3,'OPPO12','OPPO_PRO','OPPO','68');
INSERT INTO MOBILE_DETAIL VALUES(4,'MI2','XIAOMI_PRO','MI','30');
SAVEPOINT A;
INSERT INTO MOBILE_DETAIL VALUES(5,'SAMSUNG12','SAMSUNG_PRO','SAMSUNG','200');
INSERT INTO MOBILE_DETAIL VALUES(6,'NOKIA18','NOKIA_PRO_MAX','NOKIA','64');
SAVEPOINT B;
INSERT INTO MOBILE_DETAIL VALUES(7,'MOTO45','MOTO_PRO','MOTORAL','128');
INSERT INTO MOBILE_DETAIL VALUES(8,'I11','IPHONE11','APPLE','10');
SAVEPOINT C;
INSERT INTO MOBILE_DETAIL VALUES(9,'LG5','LG PRO','LG','12');
INSERT INTO MOBILE_DETAIL VALUES(10,'REDMI5','REDMI_PRO','REDMI','68');
SELECT*FROM MOBILE_DETAIL;
ROLLBACK TO B;
SELECT*FROM MOBILE_DETAIL;
ROLLBACK TO A;
SELECT*FROM MOBILE_DETAIL;
ROLLBACK;
SELECT*FROM MOBILE_DETAIL;
OUTPUT

EVALUATION

Sl.No Module Max. Marks Marks Obtained


1 Database schema 25
2 Database query 25
3 Output 20
4 Technical Skill 20
5 Communication Skill 10
Total 100
Faculty Signature

RESULT:

Thus the SQL commands for creation and various operations on transaction
(TCL COMMAND) save point has been verified and executed successfully.
Ex.NO. 4 Working with built-in function in SQL

Aim

To implement the built-in function in SQL.

ALGORITHM
Built-in functions are predefined functions that perform a specific task. Built-in functions
based on the values that they take to perform a task, can be classified into two types. They are
1. Scalar or single row function
2. Aggregate or group function
Scalar functions

Number functions

Character functions

Date functions

Conversion functions

Other functions

Number functions
• ABS(n)
• FLOOR(n)
• CEIL(n)
• EXP(n)
• LN(n)
• LOG(n)
• MOD(n)
• POWER(m,n)
• ROUND(n[,m])
• SIGN(n)
• SQRT(n)
• TRUNC(n[,m])

Character Functions
a. returning number values
• ASCII(char)
• INSTR(char1,char2[,n[,m]])
• INSTRB(char1,char2[,n[,m]])
• LENGTH(char)
• LENGTHB(char)

b. returning char value

• CHR(n)
• CONCAT(char1,char2)
• INITCAP(char)
• LPAD(char1,n[,char2])
• LTRIM(char[,set])
• REPLACE(char,search-string[,replacement-string])
• RPAD(char1,n[,char2])
• RTRIM(char[,set])
• SOUNDEX(char)
• SUBSTR(char,m[,n])
• SUBSTRB(char,m[,n])
• TRANSLATE(char,from,to)
• UPPER(char)
• LOWER(char)

Date functions
• ADD_MONTHS(d,n)
• Last_day(d)
• MONTHS_BETWEEN(d1,d2)
• NEXT_DAY(d,char)
• ROUND(d[,fmt])
• TRUNC(d[,fmt])
Date format elements
Element Meaning
YYYY 4 digit year
YY Last 2 digits of year
MM Month(01-12 ; Jan=01)
MONTH Name of month,
MON Abbreviated name of month
DDD Day of year(1-366)
DD Day of month(1-31)
D Day of week(1-7)
DAY Name of day
DY Abbreviated name of day
HH or HH12 Hour of day(1-12)
HH24 Hour of day(0-23)
MI Minute(0-59)
SS Second(0-59)

Conversion Functions
• TO_CHAR(d[,fmt])
• TO_CHAR(n[,fmt])
• TO_DATE(char[,fmt])
• TO_NUMBER(char[,fmt[,'nlsparams']])

Other functions
• greatest(expr[,expr])
• least(expr[,expr])
• Nvl(expr1,expr2)
• UID(user)
• Sysdate

Aggregate functions
• AVG()
• MAX()
• MIN()
• COUNT()
• SUM()
LIST OF EXERCISES

String Functions

1. Find the length of the column ‘Designation’

2. Display the first three characters of Department name

3. Change all ‘BlockA’ in Deplocation column as ‘BlockF’

4. Remove the ‘0’ s in the strings ‘ABC0000’, ‘000ABC’

5. Display the distinct Designations in title case

6. Display the Depname in lower case

7. Display the Deplocation in upper case

8. Translate Grade to the corresponding designation

Numeric Functions

9. Find the total number of employees.

10. Find the employee with maximum salary, minimum salary in each department in the
ascending order of depno.

11. Find the total salary paid to the employees.

12. Find the average salary paid to the employees.

13. Display the rounded value of the ‘salary’ column in ‘Employee’ table.

14. Display the salary such that it contains no decimal places.

Date Functions

15.Display the system date in the format mentioned below “27th October 1996”.

16.Display “20th September 1996” in the date format.


17.Display the date two months after the date-of-join for all the employees.

18.Display the last date of the month in the date-of-join for all the employees.

19.Display the months between the current date and the date-of-join.

20.Display the next occurrence of ‘Friday’ to the current date.

21.Display the first day of the year 2000.

COMMANDS
CREATE TABLE STUDENT(STUDENT_ID INTEGER PRIMARY KEY, STUDENT_NAME TEXT NOT NULL, DEPARTMENT TEXT NOT NULL,
CGPA FLOAT NOT NULL, NO_OF_ARREARS INTEGER NOT NULL, NATIVE_STATE TEXT NOT NULL, DOJ DATE NOT NULL);
INSERT INTO STUDENT VALUES('1001','JOO','CSE','8.89','1','AP','2020-09-01');
INSERT INTO STUDENT VALUES('1002','TULASI','ECE','8.69','2','TN','2020-09-02');
INSERT INTO STUDENT VALUES('1003','AARTHI','CSE','8.96','0','AP','2020-09-01');
INSERT INTO STUDENT VALUES('1004','HARSHI','ECE','8.12','3','KA','2020-10-05');
INSERT INTO STUDENT VALUES('1005','LAHARI','IT','8.10','1','TS','2020-09-04');
INSERT INTO STUDENT VALUES('1006','MANU','EEE','8.56','3','AP','2020-10-02');
INSERT INTO STUDENT VALUES('1007','LALLY','CSE','8.23','4','TS','2020-09-15');
INSERT INTO STUDENT VALUES('1008','LIKKI','ECE','8.79','2','KA','2020-10-11');
INSERT INTO STUDENT VALUES('1009','KAVYA','EEE','8.88','4','TN','2020-09-12');
INSERT INTO STUDENT VALUES('1010','SHAMA','IT','8.83','5','TS','2020-10-10');
SELECT*FROM STUDENT;
SELECT LENGTH(DEPARTMENT)
FROM STUDENT;
SELECT SUBSTRING(STUDENT_NAME, 1, 5)
FROM STUDENT;
UPDATE STUDENT
SET NATIVE_STATE = 'AP'
WHERE STUDENT_ID = 1002;
SELECT DISTINCT DEPARTMENT
FROM STUDENT;
SELECT LOWER(STUDENT_NAME)
FROM STUDENT;
SELECT UPPER(DEPARTMENT)
FROM STUDENT;
SELECT COUNT(STUDENT_NAME)
FROM STUDENT;
SELECT SUM(NO_OF_ARREARS)
FROM STUDENT;
SELECT MAX(CGPA), MIN(CGPA), AVG(CGPA)
FROM STUDENT;
SELECT ROUND(CGPA)
FROM STUDENT;
SELECT*FROM STUDENT
OUTPUT

EVALUATION

Sl.No Module Max. Marks Marks Obtained


1 Database schema 25
2 Database query 25
3 Output 20
4 Technical Skill 20
5 Communication Skill 10
Total 100

Faculty Signature

RESULT:

Thus the SQL commands for built in function has been verified and executed successfully
Ex: No: 04 SIMPLE PL/SQL PROGRAM

AIM:

To write a PL/SQL block using different control (if, if else, for loop, while loop,…)
statements.

OBJECTIVE:

PL/SQL Control Structure provides conditional tests, loops, flow control and
branches that let to produce well-structured programs

PL/SQL

PL/SQL is Oracle’s procedural language extension to SQL. PL/SQL allows you to mix

SQL statements with procedural statements like IF statement, Looping

structures etc. It is extension of SQL the following or advantages of

PL/SQL.

1. We can use programming features like if statement loops etc.

2. PL/SQL helps in reducing network traffic.

3. We can have user defined error massages by using concept of exception handling.

4. We can perform related actions by using concept of Triggers.

5. We can save the source code permanently for repeated execution.

PL/SQL Block:

DECLARE

Declaration of variable

Declaration of cursor----------
(OPTIONAL) Declaration of exception
BEGIN

Executable commands--------- (MANDATORY)

EXCEPTION

Exception handlers---------- (OPTIONAL)

END;
/ To execute the program / command

Declare:

This section is used to declare local variables, cursors, Exceptions and etc. This section is
optional.

Executable Section:

This section contains lines of code which is used to complete table. It is mandatory.

Exception Section:

This section contains lines of code which will be executed only when exception is
raised. This section is optional.
Simplest PL/SQL Block:

Begin

--------

END;

SERVEROUTPUT

This will be used to display the output of the PL/SQL programs. By default this will be off.

Syntax:

Set serveroutput on | off

Ex:

SQL>set serveroutput on

PL/SQL CONTROL STRUCTURES

PL/SQL has a variety of control structures that allow you to control the behaviour of
the block as it runs. These structures include conditional statements and loops.

If-then else Case
Location is NEW YORK

Case with no else

▪ Labeled case

Searched

case Simple loop

While loop


For loop


Goto and Labels

IF-THEN-ELSE
Syntax:

If <condition1> then

Sequence of statements; Elseif <condition1> then

Sequence of statements;

……

Else

Sequence of statements;

End if;

CASE

Syntax:

Case test-variable

When value1 then sequence of statements;

When value2 then sequence of statements;

When valuen then sequence of statements;

Else sequence of statements;


End case;
Location is NEW YORK
CASE WITHOUT ELSE

Syntax:

Case test-variable

When value-1 then sequence of statements;

When value-2 then sequence of statements;

……

When value-n then sequence of statements;

End case;

LABELED CASE

Syntax:

<<label>>

Case test-variable

When value1 then sequence of

statements; When value2 then

sequence of statements;

……

When value then sequence of

statements; End case;

SEARCHED

CASE Syntax:

Case

When <condition-1> then sequence of statements;

When <condition-2> then sequence of statements;


……
Location is NEW YORK
When <condition-n> then sequence of statements;

End case;
SIMPLE LOOP

Syntax:

Loop

Sequence of statements;

Exit when

<condition>; End loop;

WHILE LOOP SYNTAX

While <condition> loop

Sequence of statements;

End loop;

FOR LOOP SYNTAX

For <loop_counter_variable> in low_bound..high_bound loop

Sequence of statements;

End loop;

GOTO AND LABELS Syntax:

Goto label;

Where label is a label defined in the PL/SQL block. Labels are enclosed in double angle

brackets. When a goto statement is evaluated, control immediately passes to the statement

identified by the label.

Location is NEW YORK


PL/SQL PROGRAMS

1: Write PL/SQL block which will calculate some of two numbers and display the output?

DECLARE
A
number(2);
B
number(2);
C
number(3);
BEGIN
A := 03;
B := 09;
C := A + B;
DBMS_OUTPUT.PUT_LINE(C);
DBMS_OUTPUT.PUT_LINE( 'sum of two numbers' || C);
END;

/
Output:

2: Write a PL/SQL block which accepts employee number and increment is salary by

1000?
DECLARE
A number(4);
A := &Empno;
Location is NEW YORK
Update emp set sal = sal + 1000 where Empno = A;

END;
/

3: Write a PL/SQL block which empno and delete that row from the emp

table? DECLARE

A number(4);

BEGIN

A := &Empno;

Delete from emp where Empno = A;

END;

/
COMMANDS:
DECLARE

Anumber;

BEGIN

A:=3;

DeletefromempwhereEmp_num=A;

END;

select * from emp;


Output:

Q4: PL/SQL for reversing the given string

Algorithm:

1. Get the input string.

2. Find the length of the string.

3. Extract the characters one by one from the end of the string.

4. Concatenate the extracted characters.

5. Display the concatenated reversed string.

6. Stop the program.

Location is NEW YORK


Program:

declare

b varchar2(10) := '&b';

c varchar2(10);

l number(2);

i number(2); g number(2);

dvarchar2(10);

begin

l:=length(b);

g:=l;

for i in 1..l loop

g,1);

g := g - 1;

d := d ||

c; end loop;

dbms_output.put_line('revised string is'); dbms_output.put_line(d);

End;

c
:
=
s
u
b
s
t
r
(
b
,
Location is NEW YORK
OUTPUT:

DECLARE

strVARCHAR(20):='b.Niteeshsatyasai';

lenNUMBER;

str1VARCHAR(20);

BEGIN

len:=Length(str);

FORiINREVERSE1..lenLOOp

str1:=str1||Substr(str,i,1);

ENDLOOP;

dbms_output.Put_line('Reverseofstringis'||str1);

END;

Output:

Statementprocessed.

Reverse of string is iasaytashseetiN.b

Output:
5: PL/SQL for Fibonacci Series.

Algorithm:

1. Get the no.of terms N, in the fibonacci series to be generated.

2. If N is less than 2, then raise an exception and display the message.

3. Otherwise initialize the value of A as 0 and B as 1 and display them.

4. Repeat the steps 5&6 in N-3 times.

5. C:=A+B & Display C.

6. A:=B&B:=A

7. Stop the program.

Program:

declare

a number(3);b number(3);c number(3);n number(3):=&n; negative


exception; begin

if n < 2 then raise negative

end if;

a := 0;b := 1; dbms_output.put_line('fibonacci series is');


dbms_output.put_line(a); dbms_output.put_line(b);

for i in 3 ..n loop

c := a + b; dbms_output.put_line(c); a := b;

b :=

c; end loop;

exception

when negative then

dbms_output.put_line('n should be greater than 1');


end
;

SQL>
/

Enter value for n:5

old 5: n number(3):=&n; new 5:n number(3):=5; Fibonacci

1
2
3
5
8

PL/SQL procedure successfully completed


PROGRAM:
declare

a number:=0;

b number:=1;

c number;

i number;

procedure fib(n in number) is

begin

for i in 2 .. n

loop

c:= a + b;

dbms_output.put_line(c);

a:=b;

b:=c;

end loop;

end;

begin

dbms_output.put_line(a||' '||b);

fib(10);
end;

Output:

6: Program to check whether given number is Armstrong or not.

Algorithm:

Step 1: Declare the variable N, S, D and DUP. Step 2: Store the value in var. N and var. DUP..
Step 3: check for the value of N, which is not equal
to 0.
Step 4: divide value stored in N by 10 and store it var. D. (D=n%10). Step 5: the reminder will be
multiply 3 times and store it in Var. S.
Step 6: The coefficient will be calculated using FLOOR function. And store it in var. N. Step 7:
repeat the Steps 3, 4, 5, and 6 till loop will be terminated.
Step 8: Check whether the stored value and calculated values are same
Step 9: if both the values are same, then display “The given number is Armstrong” Step 10:
Otherwise display “it is not Armstrong” and terminate the loop.

Declare

N number; S number; D number; Begin

N:=&n; S:=0;
While(n!=0) Loop
D=n%10; S:=s+(D*D*D); N:=floor(n/10);
End loop;

If (DUP=S) then

DBMS_output.put_line(‘number is armstrong’);

Else
DBMS_output.put_line(‘number is not armstrong’);

End if; End;

Test Valid Data Set:

Enter value
of n 153
Output:

number is Armstrong
Declare
Nnumber:=153;
Snumber;
znumber:=N;
Dnumber;
Begin
S:=0;
While(n>0)Loop
D:=mod(n,10);
S:=s+(D*D*D);
N:=floor(n/10);
Endloop;
DBMS_output.put_line(s);
If(z=S)then
DBMS_output.put_line('numberisarmstrong');
Else
DBMS_output.put_line('numberisnotarmstrong');
Endif;
End;
/
Output:

Q7: Write a program to generate all prime numbers below 100.

AIM: to generate all prime numbers below 100. Declare


I number;

J number; C number;

Begin

While(i<=100) Loop

C:=0; J:=1;
While(j<=i) Loop
If(floor(i%j)=0) then

C:= C+1

J=j+1

End if;

End
loop;

If(c=2) then
Dbms_output.put_line(i);

End if;
Endloop
; End;

Valid Test Data

OUTPUT:

2
3

11
PROGRAM:
declare

n number;

i number;

j number;

function prime(n in number) return number is z number;

begin

z:=0;

for j in 2 .. n

loop

if (n != j ) then

if (mod(n,j) = 0) then

z:=z+1;

end if;

end if;

end loop;

return z;

end;

begin

n:=100;
for i in 3 .. n

loop

n:=prime(i);

if (n = 0) then

dbms_output.put_line(i||' is prime');

end if;

end loop;

end;

Output:
EVALUATION

Sl.No Module Max. Marks Marks Obtained


1 Database schema 25
2 Database query 25
3 Output 20
4 Technical Skill 20
5 Communication Skill 10
Total 100

Faculty Signature

RESULT:
Thus the PL/SQL program has been verified and executed successfully
Ex.No.5 PL/ SQL PROGRAM USING CURSORS

AIM

To write the PL/SQL program using cursor.

CURSOR

A cursor is a temporary work area created in the system memory when a SQL statement is
executed. A cursor contains information on a select statement and the rows of data accessed by it. This
temporary work area is used to store the data retrieved from the database, and manipulate this data.
A cursor can hold more than one row, but can process only one row at a time. The set of rows the
cursor holds is called the active set.

There are two types of cursors in PL/SQL:

Implicit Cursors:

When you execute DML statements like DELETE, INSERT, UPDATE and SELECT statements, implicit
statements are created to process these statements. Oracle provides few attributes called as implicit
cursor attributes to check the status of DML operations. The cursor attributes available are %FOUND,
%NOTFOUND, %ROWCOUNT, and %ISOPEN.

For example, When you execute INSERT, UPDATE, or DELETE statements the cursor attributes tell
us whether any rows are affected and how many have been affected. When a SELECT... INTO
statement is executed in a PL/SQL Block, implicit cursor attributes can be used to find out whether
any row has been returned by the SELECT statement. PL/SQL returns an error when no data is
selected. The status of the cursor for each of these attributes are defined in the below table.

Attributes Return Value Example

The return value is TRUE, if the DML statements


like INSERT, DELETE and UPDATE affect at
least one row and if SELECT ….INTO statement
return at least one row.

The return value is FALSE, if DML statements


like INSERT, DELETE and UPDATE do not affect
row and if SELECT….INTO statement do not
SQL%FOUND
return a row.
%FOUND
The return value is FALSE, if DML statements
like INSERT, DELETE and UPDATE at least one

%NOTFOUND
row and if SELECT

….INTO statement return at least one row.

The return value is TRUE, if a DML statement


like INSERT, DELETE and UPDATE do not
SQL%NOTFOUND
affect even one row and if SELECT ….INTO
statement does not return a row.

Return the number of rows affected by the DML


operations INSERT, DELETE,UPDATE,
%ROWCOUNT SELECT SQL%ROWCOUNT

Explicit Cursors

An explicit cursor is defined in the declaration section of the PL/SQL Block. It is created on a SELECT
Statement which returns more than one row. We can provide a suitable name for the cursor.

The General Syntax for creating a cursor is as given below:

CURSOR cursor_name IS select_statement;

cursor_name – A suitable name for the cursor.

select_statement – A select query which returns multiple rows.

How to use Explicit Cursor?

There are four steps in using an Explicit Cursor.

DECLARE the cursor in the declaration section.

OPEN the cursor in the Execution Section.

FETCH the data from cursor into PL/SQL variables or records in the Execution Section.

CLOSE the cursor in the Execution Section before you end the PL/SQL Block.
1) Declaring a Cursor in the Declaration Section:

DECLARE

CURSOR emp_cur IS SELECT * FROM emp_tbl WHERE salary > 5000;

In the above example we are creating a cursor ‘emp_cur’ on a query which returns the records of
all the employees with salary greater than 5000. Here ‘emp_tbl’ in the table which contains records of
all the employees.

2) Accessing the records in the cursor:

Once the cursor is created in the declaration section we can access the cursor in the execution
section of the PL/SQL program.

How to access an Explicit Cursor?

These are the three steps in accessing the cursor.

1) Open the cursor.

2) Fetch the records in the cursor one at a time.

3) Close the cursor.

General Syntax to open a cursor is:

OPEN cursor_name;

General Syntax to fetch records from a cursor is:

FETCH cursor_name INTO record_name;

OR

FETCH cursor_name INTO variable_list;

General Syntax to close a cursor is:


CLOSE cursor_name;

When a cursor is opened, the first row becomes the current row. When the data is fetched it is copied
to the record or variables and the logical pointer moves to the next row and it becomes the current
row. On every fetch statement, the pointer moves to the next row. If you want to fetch after the last
row, the program will throw an error. When there is more than one row in a cursor we can use loops
along with explicit cursor attributes to fetch all the records.

General Form of using an explicit cursor is:

DECLARE variables; records;

create a cursor;

BEGIN

OPEN cursor; FETCH cursor;

process the records; CLOSE cursor;

END;

These are the attributes available to check the status of an explicit cursor.

Attributes Return values Example

%FOUND TRUE, if fetch statement Cursor_name%FOUND

returns at least one row.

FALSE, if fetch statement

doesn’t return a row.

1
137
Cursor_name%NOTFOUN
%NOTFOUND TRUE, , if fetch statement D

doesn’t return a row.

FALSE, if fetch statement

returns at least one row.

Cursor_name%ROWCOUN
%ROWCOUNT The number of rows fetched by T

the fetch statement

If no row is returned, the

PL/SQL statement returns an

error.

%ISOPEN TRUE, if the cursor is already Cursor_name%ISNAME

open in the program

FALSE, if the cursor is not

opened in the program.

PL/SLQL PROGRM USING CURSORS


1. To write a Cursor to display List of Employees from Emp Table in PL/SQL block
DECLARE
cursor c is select empno, ename, deptno, sal from emp ;
i emp.empno%type;
j emp.ename%type;
k emp.deptno%type;
l emp.sal%type;
BEGIN
open c;
dbms_RESULT.put_line('Empno, name, deptno, salary of employees are:=
'); loop
fetch c into i, j, k, l; exit
when c%notfound;
dbms_RESULT.put_line(i||' '||j||' '||k||'
'||l); end loop;
close c;

END;

RESULT:
SQL> @EMP
Empno,name,deptno,salary of employees are:=
7369 SMITH 20 800
7499 ALLEN 30 1600
7521 WARD 30 1250
7566 JONES 20 2975
7654 MARTIN 30 1250
7698 BLAKE 30 2850
7782 CLARK 10 2450
7788 SCOTT 20 3000
7839 KING 10 5000
7844 TURNER 30 1500
7876 ADAMS 20 1100
7900 JAMES 30 950
7902 FORD 20 3000
7934 MILLER 10 1300

PL/SQL procedure successfully completed.


COMMANDS:
declare

c_id employee.id%type;

c_name employee.name%type;

c_addr emp.address%type;

cursor c_emp is select id,name,address from employee;

begin

open c_emp;

loop

fetch c_emp into c_id,c_name,c_addr;

exit when c_emp%notfound;

dbms_output.put_line(c_id||' '||c_name||' '||c_addr);

end loop;

close c_emp;

end;

Output:
2. DISPLAYING EMPLOYEE DETAILS USING CURSORS.

Aim: To write a pl/sql program to displaying employee details using cursors.

Source code:

declare

no emp.eno%type;

name emp.ename%type;

cursor emp_cur is select eno,ename from emp;

begin

open emp_cur;

loop

fetch emp_cur into no,name;

exit when emp_cur%notfound;

DBMS_output.put_line('Employee No:'||no||'Employee Name:'||name);

end loop;

close emp_cur;

end;

Execution:

SQL> @e:\plsql\c1r.sql;

Employee No:101 Employee Name:kalam

Employee No:100 Employee Name:john

Employee No:102 Employee Name:priya


Employee No:103 Employee Name:raja

Employee No:104 Employee Name:giri

Employee No:105 Employee Name:kohili

Employee No:106 Employee Name:latha

Employee No:107 Employee Name:hari


PL/SQL procedure successfully completed.

COMMANDS:
declare

emp_num emp.emp_num%type;

name emp.name%type;

dept_no emp.dept_no%type;

cursor emp_cur is select emp_num,name ,dept_no from emp;

begin

open emp_cur;

loop

fetch emp_cur into emp_num,name,dept_no;

exit when emp_cur%notfound;

DBMS_output.put_line('Employee No:'||emp_num||' Employee Name:'||name||' Employee

depatment:'||dept_no);

end loop;

close emp_cur;

end;

Out put:
3.TOP 10 EMPLOYEES

Aim: To Write a pl/sql program to to displaying top 10 employee details based on salary using
cursors

Source code:

declare

i number(2);

E emp%rowtype;

cursor ec is select * from emp order by salary desc;

begin

Dbms_output.put_line('Eno Ename Job Salary');

Dbms_output.put_line('----------------------');

i:=1;

open ec;

loop

fetch ec into E;

i:=i+1;
Dbms_output.put_line(E.eno||' '||rpad(E.ename,8,' ')||' '|| rpad(E.job,5,' ')||' '||E.salary);
exit when i>10 or ec%notfound;
end loop;

close ec;

end;

Execution:

SQL> @e:\plsql\c2.sql;

Eno Ename Job Salary

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

104 giri gm 14000

106 latha sales 12800

111 kiran agm 12800

112 swathi clerk 12600

113 wasim agm 12400

107 hari sales 6000

105 kohili clerk 6000

108 lakshmi clerk 5600

100 john sales 4880

101 kalam clerk 4800

PL/SQL procedure successfully completed.

COMMANDS:
declare

i number(2);

E emp%rowtype;

cursor ec is select * from emp order by salary desc;


begin

i:=1;

open ec;

loop

fetch ec into E;
i:=i+1;

Dbms_output.put_line(E.emp_num||' '||rpad(E.name,8,' ')||' '|| rpad(E.dept_no,5,' ')||'

'||E.salary);

exit when i>10 or ec%notfound;

end loop;

close ec;

end;

Output:

4. STUDENT MARK LIST

Aim: To Write a pl/sql program to print mark list using cursors.

Procedure:

Creating table:
SQL>create table Student(
sno number(4),

sname varchar(10),

m1 numbar(3),

m2 numbar(3),

m3 numbar(3));

table created.

SQL>insert into student values

(500,’wasim’,70,75,89); 1 row inserted.

SQL>insert into student values (500,’siva’,75,69,88);

1 row inserted.

SQL>insert into student values (500,’vani’,84,75,75);

1 row inserted.

SQL>insert into student values

(500,’naga’,67,50,33); 1 row inserted.

Source code:

declare

stu student%rowtype;

total number(4);

result varchar(4);

cursor c is select * From student;

begin

for stu in c

loop

Dbms_output.put_line('STUDENT MARKLIST');

Dbms_output.put_line('----------------------------');

1 Dbms_output.put_line('sno:'||stu.sno||' sname:'||stu.sname);
total:=stu.m1+stu.m2+stu.m3;

if stu.M1>35 and stu.M2>35 and stu.M3>35

then

result:='pass';

else

result:='fail';

end if;

Dbms_output.put_line('m1:'||stu.M1||' m2:'||stu.M2||' m3:'||stu.M3);

Dbms_output.put_line('total:'||total||' result:'||result);

end loop;

end;

Execution:

SQL> @e:\plsql\c3.sql

STUDENT MARKLIST

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

sno:500 sname:wasim

m1:70 m2:75 m3:89

total:234 result:pass

STUDENT MARKLIST

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

sno:501 sname:siva

1 m1:75 m2:69 m3:88


total:232 result:pass

STUDENT MARKLIST

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

sno:502 sname:vani

m1:84 m2:75 m3:75

total:234 result:pass

STUDENT MARKLIST

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

sno:504 sname:naga

m1:67 m2:50 m3:33

total:150 result:fail

PL/SQL procedure successfully completed.

COMMANDS:
declare

stu student%rowtype;

total number(4);

result varchar(4);

cursor c is select * From student;

begin

for stu in c

loop

Dbms_output.put_line('STUDENT MARKLIST');

Dbms_output.put_line('----------------------------');

Dbms_output.put_line('sno:'||stu.stu_no||' sname:'||stu.stu_name);

total:=stu.m1+stu.m2+stu.m3;

if stu.M1>35 and stu.M2>35 and stu.M3>35

then

result:='pass';

else

result:='fail';
end if;

Dbms_output.put_line('m1:'||stu.M1||' m2:'||stu.M2||' m3:'||stu.M3);

Dbms_output.put_line('total:'||total||' result:'||result);

end loop;

end;

/
Output:

5. PARAMETERIZED CURSOR

Aim: To Write a pl/sql program to display employees using parameterized cursor.

Source code:

declare

n number;

er emp%rowtype;

cursor c(d number) is

select * from emp where emp.eno=d;


begin

n:=&n;

1 open c(n);
if c%isopen then

loop

fetch c into er;

exit when c%notfound;

Dbms_output.put_line('Employee No:'||er.eno

||'Employee Name:'||er.ename);

end loop;

else

DBMS_OUTPUT.PUT_LINE('not found');

end if;

close c;

end;

Execution:

SQL> @e:\plsql\c4.sql

Enter value for n: 100

old 7: n:=&n;

new 7: n:=100;

Employee No:100 Employee Name:Mahesh

PL/SQL procedure successfully completed.

COMMANDS:
declare

n number;

er emp%rowtype;

cursor c(d number) is

select * from emp where emp.emp_num=d;

begin

n:=4;

open c(n);
if c%isopen then

loop
fetch c into er;

exit when c%notfound;

Dbms_output.put_line('Employee No:'||er.emp_num

||'Employee Name:'||er.name);

end loop;

else

DBMS_OUTPUT.PUT_LINE('not found');

end if;

close c;

end;

Output:

6. INCREMENTING SALARY OF EMPLOYEES.

Aim: To Write a pl/sql program to update the commission values for all employees with salary
less than 2000 by adding Rs.1000 to existing employees.
Source code:
declare

cursor c is select *From emp for update;

emp_rec emp%rowtype;

begin

for emp_rec in c

loop

if emp_rec.salary<2000 then

update emp set comm=comm+1000

where current of c;

end if;

end loop;

end;

Displaying rows before execution:

SQL>Select *From employee;

Eno Ename Job Salary comm

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

106 latha sales 12800 5000

111 kiran agm 12800 6000

100 john sales 1880 500

101 kalam clerk 1800 600

105 kohili clerk 1000 200

Execution:

SQL>@E:\plsql\incr.sql ;
PL/SQL procedure successfully completed.
Displaying rows after execution:

SQL>Select *From employee;

Eno Ename Job Salary comm

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

106 latha sales 12800 5000

111 kiran agm 12800 6000

100 john sales 1880 1500

101 kalam clerk 1800 1600

105 kohili clerk 1000 1200

7.DELETING EMPLOYEE

Aim: To Write a pl/sql program to delete employees whose experience is less then 2 years.

Procedure:

Employee table:

Emp(eno,ename,salary,experience)

Source code:

declare

cursor c is select *From emp for update;

emp_rec emp%rowtype;

begin

for emp_rec in c

loop

if emp_rec.experience<2 then

delete emp

where current of c;

end if;
end loop;

end;

Execution:

SQL>@del.sql
PL/SQL procedure successfully completed.

COMMANDS:
declare

cursor c is select *From emp for update;

emp_rec emp%rowtype;

begin

for emp_rec in c

loop

if emp_rec.salary<2000 then

update emp set comm=comm+1000

where current of c;

end if;

end loop;

end;

Output:
EVALUATION

Sl.No Module Max. Marks Marks Obtained


1 Database schema 25
2 Database query 25
3 Output 20
4 Technical Skill 20
5 Communication Skill 10
Total 100

Faculty Signature

Result:
Thus the cursor program was implemented and verified
Ex: No: 6 PL/ SQL programs using Function

AIM:

To write the PL/SQL block for the implementation of functions

ALGORITHM:

STEP 1: Start the program.

STEP 2: Create the table with its essential attributes.

STEP 3: Insert attribute values into the table.

STEP 4: Create the function with necessary arguments and return data types.

STEP 5: create the PL/SQL block to call / use the function.

STEP 6: Execute the PL/SQL program.

STEP 7: Give the input values

STEP 8: Extract/process the information from the function.

STEP 9: Stop the program.

STORED FUNCTION

A function is similar to procedure, except that it returns a


value. The calling program should use the value returned by the
function.

CREATE FUNCTION

The create function command is used to create a stored function.

SYNTAX:

CREATE [OR REPLACE] FUNCTION name

[(parameter[,parameter, ...])]

RETURN datatype

{IS | AS}

[local declarations] BEGIN


executable statements RETURN value;
[EXCEPTION exception handlers]

END [name];

Note:
OR REPLACE is used to create a function even though a function with the
same name already exists

RETURN datatype specifies the type of data to be returned by the function.

RETURN statement in the executable part returns the value. The value
must be of the same type as the return type specified using RETURN
option in the header.

User-defined PL/SQL functions can be used in SQL in the same manner as the
standard functions such as ROUND and SUBSTR

Q 1: To write a PL/SQL block to implementation of factorial using function

I) PROGRAM:

SQL>create
function fnfact(n
number) return
number is
bn

g
i

b:=1;

for i in 1..n loop

b:=b*i;

end loop;

return b;

end;

SQL>Declare

nn
umber:=&
n; begin
end;
y number;
/

dbms_output.put_line(y);
Output:

Function created.
Enter value for n:
5 old 2: n
number:=&n; new 2:

n number:=5; 120

PL/SQL procedure successfully completed.

COMMANDS:
declare
num number;

factorial number;

function fact(x number) return number is f number;

begin

if x =0 then

f:= 1;

else

f:= x*fact(x-1);

end if;

return f;

end;

begin

num:=4;

factorial:=fact(num);

dbms_output.put_line('THE factorial of 4 is '||factorial);

end;

output:
Q2:create a function which count total no.of employees having salary less than 6000.

/*function body*/

Create or replace function count_emp(esal number)return number as

Cursor vin_cur as Select empno,sal from


emp;
Xno emp.empno%type;
Xsal emp.sal%type;

C number;

Begin

Open
vin_cur;
C:=0;
loop

fetch vin_cur into xno,xsal;

if(xsal<esal) then

c:=c+1;

end if;

exit when
vin_cur%notfound; end
loop;
close vin_cur;

return c;

end;

Function created.

/*function specification*/
Declare
Ne number;
Xsal number;
Begin

Ne:=count_emp(xsal); Dbms_output.put_line(xsal);
Dbms_output.put_line(‘there are ‘||ne||;employees’);
End;
OUTPUT

There are 8 employees.

COMMANDS:
Declare

Ne number;

Xno emp.emp_num%type;

Xsal emp.salary%type;

C number;

Cursor vin_cur is Select emp_num,salary from emp;

function count_emp(xsal in number,xno in number) return number is z number;

begin

if(xsal < 8000) then

z := xno;

else

z := 0;

end if;

return z;

end;

Begin

open vin_cur;

loop

fetch vin_cur into xno,xsal;

exit when vin_cur%notfound;

c := count_emp(xsal,xno);

if(c > 0) then


Dbms_output.put_line('the employee with emp_num ' ||c||' has salary '||xsal);

end if;

end loop;

close vin_cur;

End;

output:

EVALUATION

Sl.No Module Max. Marks Marks Obtained


1 Database schema 25
2 Database query 25
3 Output 20
4 Technical Skill 20
5 Communication Skill 10
Total 100

Faculty Signature

Result:

Thus the implementation of functions and its applications has been


executed successfully.
Ex.No. 7 PL/SQL PROGRAM USING PROCEDURES

AIM
To write a PL/SQL program using procedures..

SYNTAX

CREATE [OR REPLACE] PROCEDURE name [(parameter[,parameter, ...])]

{IS|AS}

[local declarations] BEGIN

executable statements

[EXCEPTION

exce

ption

handlers]

END

[name];

EXECUTION:

SQL> SET SERVEROUTPUT ON

1.SUM OF TWO NUMBERS USING PROCEDURES

Aim:

To Write a pl/sql program for creating a procedure for calculating sum of two
numbers.
Source code:

create or replace procedure "SUM"(n1 IN NUMBER,n2 IN NUMBER) is

total number(6);

begin

total:=n1+n2;

dbms_output.put_line('the sum

is:'||total); end;

Execution:

Method1:

SQL> exec sum(10,20);

the sum is:30

PL/SQL procedure successfully completed.

Method 2:

SQL> begin

2 sum(12,13);

3 end;

4 /

the sum is:25

PL/SQL procedure successfully completed.

2. To write a PL/SQL block to display the student name, marks whose average mark
is above 60%.
ALGORITHM

STEP1:Start

STEP2:Create a table with table name stud_exam

STEP3:Insert the values into the table and Calculate total and average of each student

STEP4: Execute the procedure function the student who get above 60%.

STEP5: Display the total and average of student STEP6: End

EXECUTION

SETTING SERVEROUTPUT ON:

SQL> SET SERVEROUTPUT ON

I) PROGRAM:

1. PROCEDURE USING POSITIONAL PARAMETERS:

SQL> SET SERVEROUTPUT ON

SQL> CREATE OR REPLACE PROCEDURE PROC1 AS BEGIN

DBMS_OUTPUT.PUT_LINE('Hello from procedure...');

END;

Output:

Procedure created.

SQL> EXECUTE PROC1

Hello from procedure...

COMMANDS:

Declare

tot number;

stu_no Student.stu_no%type;

stu_name Student.stu_name%type;
m1 Student.m1%type;

m2 Student.m2%type;

m3 Student.m3%type;

C number;

Cursor vin_cur is Select stu_no,stu_name,m1,m2,m3 from Student;

procedure avg_stu(m1 in number,m2 in number,m3 in number,ave out number) is

begin

ave := (m1 + m2 + m3)/3;

end;

Begin

open vin_cur;

loop

fetch vin_cur into stu_no,stu_name,m1,m2,m3 ;


exit when vin_cur%notfound;

avg_stu(m1,m2,m3,tot);

if(tot > 80) then

Dbms_output.put_line(stu_name||' has the average of ' ||tot||' and his reg.no is '||stu_no);

end if;

end loop;

close vin_cur;

End;

Output:
2. PROCEDURE USING NOTATIONAL PARAMETERS:

SQL> CREATE OR REPLACE PROCEDURE PROC2

(N1 IN NUMBER,N2 IN NUMBER,TOT OUT NUMBER) IS


BEGIN

TOT := N1 + N2;

END;

Output:

Procedure created.

SQL> VARIABLE T NUMBER

SQL> EXEC PROC2(33,66,:T)

PL/SQL procedure successfully completed.

SQL> PRINT T

----------

99

3. PROCEDURE FOR GCD NUMBERS

SQL> create or replace procedure pro is

a number(3); b number(3); c number(3); d


number(3); begin a:=&a; b:=&b; if(a>b)
then c:=mod(a,b); if(c=0) then

dbms_output.put_line('GCD is'); dbms_output.put_line(b);

else dbms_output.put_line('GCD is');


dbms_output.put_line(c);

end if; else

d:=mod(b,a); if(d=0) then

dbms_output.put_line('GCD is'); dbms_output.put_line(a);

else dbms_output.put_line('GCD is');


dbms_output.put_line(d);

end if; end if; end;

Enter value for a: 8 old 8: a:=&a; new 8: a:=8;

Enter value for b: 16 old 9: b:=&b;

new 9: b:=16; Procedure created.

SQL> set serveroutput on;

SQL> execute pro;

GCD is

PL/SQL procedure successfully completed.

COMMANDS:

Declare

a number;

b number;

C number;

d number;

e number;

procedure gcd(a in number,b in number) is

begin

if (b !=0) then

gcd(b,mod(a,b));

else

Dbms_output.put_line('The GCD of '|| c ||' and '|| d || ' is ' || a);


end if;

end;

Begin

a := 8;

b := 4;

c := a;

d := b ;

gcd(a,b);

End;

Statement processed.

The GCD of 8 and 4 is 4

OUTPUT:
EVALUATION

Sl.No Module Max. Marks Marks Obtained


1 Database schema 25
2 Database query 25
3 Output 20
4 Technical Skill 20
5 Communication Skill 10
Total 100

Faculty Signature

RESULT:

Thus the implementation of PL/SQL procedure has been verified and


executed successfully.
EX.NO.8 PL/SL PROGRAM USINGTRIGGERS

Aim

To write a PL/SQL program using triggers

TRIGGER

A trigger is a pl/sql block structure which is fired when a DML statements like
Insert, Delete, Update is executed on a database table. A trigger is triggered
automatically when an associated DML statement is executed.
A Trigger is a stored procedure that defines an action that the database
automatically takes when some database-related event such as Insert, Update or Delete
occur.

TRIGGER VS. PROCEDURE VS CURSOR

TRIGGER PROCEDURES CURSORS

These are named


These are named These are named PL/SQL
PL/SQL blocks. PL/SQL blocks. blocks.
User as per need These can be created
These are invoked invokes both
automatically. these. explicitly and implicitly.
These can take
These can‟t take These can take parameters.

parameters. parameters.

These are stored in These are stored in These are not stored in
database. database. database.

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)

BEGIN

--- sql

statements

END;

CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a


trigger with the given name or overwrites an existing trigger with the
same name.
{BEFORE | AFTER | INSTEAD OF } - This clause indicates at what time should
the trigger get fired. i.e for example: before or after updating a table. INSTEAD
OF is used to create a trigger on a view. before and after cannot be used to
create a trigger on a view.

{INSERT [OR] | UPDATE [OR] | DELETE} - This clause determines the


triggering event. More than one triggering events can be used together
separated by OR keyword. The trigger gets fired at all the specified
triggering event.
[OF col_name] - This clause is used with update triggers. This clause is
used when you want to trigger an event only when a specific column is
updated.
CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a
trigger with the given name or overwrites an existing trigger with the
same name.
[ON table_name] - This clause identifies the name of the table or view to
which the trigger is associated.
[REFERENCING OLD AS o NEW AS n] - This clause is used to reference the
old and new values of the data being changed. By default, you reference the
values as :old.column_name or :new.column_name. The reference names can
also be changed from old (or new) to any other user-defined name. You cannot
reference old values when inserting a record, or new values when deleting a
record, because they do not exist.
[FOR EACH ROW] - This clause is used to determine whether a trigger must
fire when each row gets affected ( i.e. a Row Level Trigger) or just once when
the entire sql statement is executed(i.e.statement level Trigger).
WHEN (condition) - This clause is valid only for row level triggers. The
trigger is fired only for rows that satisfy the condition specified.
Types of PL/SQL Triggers

There are two types of triggers based on the level it is triggered.

1) Row level trigger - An event is triggered for each row upated, inserted or deleted.

2) Statement level trigger - An event is triggered for each sql statement executed.

Row Level Trigger vs. Statement Level Trigger:

Row Level Trigger Statement Level Trigger


These are fired for each row affected
by These are fired once for the statement
instead of the no of rows modified by
the DML statement. it.

These are used for


generating/checking These are used for generated the
the values begin inserted or updated. summary information.

Before trigger vs. after trigger

Before
Triggers After Triggers

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

executio
n.

VARIABLES USED IN TRIGGERS

:new
:old

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

The following hierarchy is followed when a trigger is fired.

1) BEFORE statement trigger fires first.

2) Next BEFORE row level trigger fires, once for each row affected.

3) Then AFTER row level trigger fires once for each affected row. This events will
alternates between BEFORE and AFTER row level triggers.
4) Finally the AFTER statement level trigger fires.

RAISE_APPLICATION_ERROR ( )

RAISE_APPLICATION_ERROR is a built-in procedure in oracle which is used to display


the user-defined error messages along with the error number whose range is in between
-20000 and -20999.

Whenever a message is displayed using RAISE_APPLICATION_ERROR, all previous


transactions which are not committed within the PL/SQL Block are rolled back
automatically (i.e. change due to INSERT, UPDATE, or DELETE statements).

RAISE_APPLICATION_ERROR raises an exception but does not handle it.

RAISE_APPLICATION_ERROR is used for the following reasons,

a) to create a unique id for an user-defined exception.

b) to make the user-defined exception look like an Oracle error.

The General Syntax to use this procedure is:

RAISE_APPLICATION_ERROR (error_number, error_message);

• The Error number must be between -20000 and -20999

• The Error_message is the message you want to display when the error occurs.

Steps to be folowed to use RAISE_APPLICATION_ERROR procedure:

1. Declare a user-defined exception in the declaration section.

2. Raise the user-defined exception based on a specific business rule in the


execution section.
3. Finally, catch the exception and link the exception to a user-defined error
number in RAISE_APPLICATION_ERROR.

Using the above example we can display a error message using


RAISE_APPLICATION_ERROR.
COMMANDS:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'ABCD', 22, 'Hyderabad', 50000.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (2, 'EFGH', 25, 'Chennai', 35000.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (3, 'IJKL', 23, 'Kukatapally', 20000.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (4, 'MNOP', 25, 'Kavali', 25000.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (5, 'QRST', 27, 'Bhopal', 45000.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (6, 'UVWX', 22, 'Tirupati', 40000.00 );
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;
/
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 5000;
IF sql%notfound THEN
dbms_output.put_line('no customers updated');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers updated ');
END IF;
END;
/
OUTPUT:
EVALUATION

Sl.No Module Max. Marks Marks Obtained


1 Database schema 25
2 Database query 25
3 Output 20
4 Technical Skill 20
5 Communication Skill 10
Total 100

Faculty Signature

RESULT: Thus the Trigger procedure has been executed successfully for both before
and after sequence.
Ex.No. 9 Embedded SQL

AIM

To study about the Embedded SQL.

THEORY

• Embedded SQL statements are processed by a special SQL precompiler. All


SQL statements begin with an introducer and end with a terminator, both of
which flag the SQL statement for the precompiler. The introducer and
terminator vary with the host language. For example, the introducer is "EXEC
SQL" in C and "&SQL(" in MUMPS, and the terminator is a semicolon (;) in C
and a right parenthesis in MUMPS.
• Variables from the application program, called host variables, can be used in
embedded SQL statements wherever constants are allowed. These can be used
on input to tailor an SQL statement to a particular situation and on output to
receive the results of a query.
• Queries that return a single row of data are handled with a singleton
SELECT statement; this statement specifies both the query and the host
variables in which to return data.
• Queries that return multiple rows of data are handled with cursors. A cursor
keeps track of the current row within a result set. The DECLARE CURSOR
statement defines the query, the OPEN statement begins the query processing,
the FETCH statement retrieves successive rows of data, and the CLOSE
statement ends query processing.
• While a cursor is open, positioned update and positioned delete statements
can be used to update or delete the row currently selected by the cursor.

The following code is a simple embedded SQL program, written in C. The program
illustrates many, but not all, of the embedded SQL techniques. The program prompts
the user for an order number, retrieves the customer number, salesperson, and status
of the order, and displays the retrieved information on the screen.

int main() {

EXEC SQL INCLUDE SQLCA;

EXEC SQL BEGIN DECLARE SECTION;

int OrderID; /* Employee ID (from user) */

int CustID; /* Retrieved customer ID */

char SalesPerson[10] /* Retrieved salesperson name */


char Status[6] /* Retrieved order status */

EXEC SQL END DECLARE SECTION;

/* Set up error processing */

EXEC SQL WHENEVER SQLERROR GOTO query_error;

EXEC SQL WHENEVER NOT FOUND GOTO bad_number;

/* Prompt the user for order number */

printf ("Enter order number: ");

scanf_s("%d", &OrderID);

/* Execute the SQL query */

EXEC SQL SELECT CustID, SalesPerson, Status

FROM Orders

WHERE OrderID = :OrderID

INTO :CustID, :SalesPerson, :Status;

/* Display the results */

printf ("Customer number: %d\n", CustID);

printf ("Salesperson: %s\n", SalesPerson);

printf ("Status: %s\n", Status);

exit();

query_error:

printf ("SQL error: %ld\n", sqlca-

>sqlcode); exit();
bad_number:

printf ("Invalid order number.\n");

exit();

• Host Variables The host variables are declared in a section enclosed by the BEGIN
DECLARE SECTION and END DECLARE SECTION keywords. Each host
variable name is prefixed by a colon (:) when it appears in an embedded SQL
statement. The colon allows the precompiler to distinguish between host variables
and database objects, such as tables and columns, that have the same name.
• Data Types The data types supported by a DBMS and a host language can be quite
different. This affects host variables because they play a dual role. On one hand,
host variables are program variables, declared and manipulated by host language
statements. On the other hand, they are used in embedded SQL statements to
retrieve database data. If there is no host language type that corresponds to a DBMS
data type, the DBMS automatically converts the data.
• Error Handling The DBMS reports run-time errors to the applications program
through an SQL Communications Area, or SQLCA. In the preceding code example,
the first embedded SQL statement is INCLUDE SQLCA. This tells the precompiler to
include the SQLCA structure in the program. This is required whenever the program
will process errors returned by the DBMS. The WHENEVER...GOTO statement tells
the precompiler to generate error-handling code that branches to a specific label
when an error occurs.
• Singleton SELECT The statement used to return the data is a singleton SELECT
statement; that is, it returns only a single row of data. Therefore, the code example
does not declare or use cursors.
COMMANDS:
import java.sql.*;

import java.util.*;

public class App

public static void main(String[] args)

try

{
Scanner sc= new Scanner(System.in);

System.out.print("Enter the student reg.no - ");

int a = sc.nextInt();

Class.forName("com.mysql.cj.jdbc.Driver");

Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","root");

Statement stmt=con.createStatement();

ResultSet rs=stmt.executeQuery("select * from stu ");

while(rs.next())

if(rs.getInt(1) == a){

System.out.println("The reg no "+rs.getInt(1)+" his/her name "+rs.getString(2)+" has scored "+rs.getInt(3)+"%


and the student has "+rs.getString(4)+"ed");

con.close();

catch(Exception e)

System.out.println(e);

output:
ODBC:

Select * from stu where marks > 35;


EVALUATION

Sl.No Module Max. Marks Marks Obtained


1 Database schema 25
2 Database query 25
3 Output 20
4 Technical Skill 20
5 Communication Skill 10
Total 100

Faculty Signature

RESULT: Thus the procedure for Embedded SQL has been executed successfully and

verified.

You might also like