You are on page 1of 105

SCHOOL OF COMPUTING

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LAB MANUAL

INT18R371 – DATABASE MANAGEMENT SYSTEM LAB

Prepared By

Dr.R.Kanniga Devi
Mrs.R.Sumathi
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 :

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 ADO

11 Database Connectivity using ODBC

12 Database Connectivity using JDBC


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 ADO

11. Database Connectivity using ODBC

12. Database Connectivity using JDBC


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 V
Course Credit 2
Course Coordinator Mrs.R.Sumathi
Module Coordinator Dr. K.Kartheeban
Programme Coordinator Dr.K.Kartheeban

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
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 PO6PO7 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
9. Database Connectivity using ODBC 3 39
10. Database Connectivity using JDBC 3 42
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 (20)
1
Internal Assessment (50 marks) Model Lab (20)
Record (10)
2 External Assessment (50 marks) End semester Lab (50)

Rubrics for Assessment – Regular Lab Experiments

Component Rubrics for assessment Marks (100)


Database schema  Efficiency of writing Database schema 25
Excellent( 25-20) Good( 20-15) Average(15-10)
Poor(10-0)
 Efficiency of Writing query
Query Excellent( 25-20) Good( 20-15) Average(15-10) 15
Poor(10-0)
 Efficiency of Back end Connection
Database Connectivity Excellent( 25-20) Good( 20-15) Average(15-10) 15
Poor(10-0)
 Output
Output Excellent( 20-15) Good( 15-10) Average(10-5) 15
Poor(5-0)
 Answering the technical questions in viva voce
Technical Skill Excellent( 20-15) Good( 15-10) Average(10-5) 20
Poor(5-0)
1. Communicating the answers in viva voce
Communication Skill Excellent( 10-8) Good( 8-6) Average(6-4) 10
Poor(4-0)

Mapping the Experiments:

VIVA VOCE
Database
S.No Experiments
schema
Query Output
Technica Communic
l ation

1 Working with DDL commands 25 25 20 20 10


Working with DML and DCL
2 25 25 20 20 10
commands
Working with Built-in functions of
3 25 25 20 20 10
SQL
Programs using PL/SQL and
4 25 25 20 20 10
Cursors
5 Working with Triggers 25 25 20 20 10
Working with Stored Procedures and
6 25 25 20 20 10
Functions
7 Embedded SQL 25 25 20 20 10
8 Database Connectivity using ADO 25 25 20 20 10
9 Database Connectivity using ODBC 25 25 20 20 10
10 Database Connectivity using JDBC 25 25 20 20 10

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
QUERY: 01
Q1: Write a query to create a table employee with empno, ename, designation, and salary.
Syntax: It is used to create a table

SQL: CREATE <OBJ.TYPE><OBJ.NAME> (COLUMN NAME.1 <DATATYPE> (SIZE),

COLUMN NAME.2 <DATATYPE> (SIZE) ………);

Command:

SQL>CREATE TABLE EMP (EMPNO NUMBER (4),ENAME VARCHAR2 (10),


DESIGNATIN VARCHAR2 (10),SALARY NUMBER (8, 2));

Table created.

Constraints with Table Creation:

Constraints are condition for the data item to be stored into a database.
There are two types of Constraints viz., Column Constraints and Table Constraints.

Syntax

[CONSTRAINT constraint name]

{[NOT] NULL / UNIQUE / PRIMARY

KEY}(Column[,column]..) FOREIGN KEY (column [, colum]…)

REFERENCES table

[ON DELETE CASCADE] [CHECK (condition)]

TABLE DESCRIPTION

It is used to view the table structure to confirm whether the table was created
correctly.

QUERY: 02

Q2: Write a query to display the column name and data type of the table employee.

Syntax: This is used to view the structure of the table. SQL: DESC <TABLE
NAME>; Command:

SQL> DESC EMP;

Name Type

--------------- ----------------
EMPNO NUMBER(4)
ENAME VARCHAR2(1
DESIGNATI VARCHAR2(1
SALARY NUMBER(8,2)

QUERY: 03

Q3: Write a query for create a from an existing table with all the fields

Syntax: syntax for create a table from an existing table with all fields.

SQL> CREATE TABLE <TRAGET TABLE NAME> SELECT * FROM<SOURCE TABLE


NAME>;

Command:

SQL> CREATE TABLE EMP1 AS SELECT * FROM


EMP; Table created.
Command:

SQL> DESC EMP1

Name Null? Type


---------------- --------------------------
EMPNO NUMBER(4)
ENAME VARCHAR2(10)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)

QUERY: 04

Q4: Write a query for create a from an existing table with selected fields

Syntax: Syntax for create a from an existing table with selected fields.

SQL> CREATE TABLE <TRAGET TABLE NAME> AS SELECT EMPNO, ENAMEFROM


<SOURCE TABLE NAME>;

Command:

SQL> CREATE TABLE EMP2 AS SELECT EMPNO, ENAME FROM


EMP; Table created.
Command:

SQL> DESC EMP2

Name Null? Type


----------------- --------------------- ---
EMPNO NUMBER (4)
ENAME VARCHAR2 (10)

QUERY: 05

Q5: Write a query for create a new table from an existing table without any record:

Syntax: The syntax for create a new table from an existing table without any record.

SQL> CREATE TABLE <TRAGET TABLE NAME> AS SELECT * FROM<SOURCE TABLE


NAME> WHERE <FALSE CONDITION>;
Command:

SQL> CREATE TABLE EMP3 AS SELECT * FROM EMP


WHERE1>2; Table created.
Command:

SQL> DESC EMP3;


Name Null? Type
------------------ -----------------------
EMPNO NUMBER(4)
ENAME VARCHAR2(10)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2);

ALTER & MODIFICATION ON TABLE

To modify structure of an already existing table to add one more columns and
also modify the existing columns.

Alter command is used to:

2. Add a new column.


3. Modify the existing column definition.
4. To include or drop integrity constraint.

QUERY: 06

Q6: Write a Query to Alter the column EMPNO NUMBER (4) TO EMPNO NUMBER (6).

Syntax: The syntax for alter & modify on a single column.

SQL > ALTER <TABLE NAME> MODIFY <COLUMN NAME><DATATYPE>(SIZE);


Command:
SQL>ALTER TABLE EMP MODIFY EMPNO NUMBER
(6); Table altered.
Command:

SQL> DESC EMP;


Name Null? Type
----------------- ----------------------------------
EMPNO NUMBER(6)
ENAME VARCHAR2(10)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)

QUERY: 07

Q7. Write a Query to Alter the table employee with multiple columns (EMPNO,ENAME.)

Syntax: To alter table with multiple column.

SQL > ALTER <TABLE NAME> MODIFY <COLUMN NAME1><DATATYPE>(SIZE),

MODIFY <COLUMN NAME2><DATATYPE>(SIZE)………….;

Command:
SQL>ALTER TABLE EMP MODIFY (EMPNO NUMBER (7), ENAMEVARCHAR2(12)); Table
altered.

Command:

SQL> DESC EMP;


Name Null? Type
----------------- ---------------------------
EMPNO NUMBER(7)
ENAME VARCHAR2(12)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2);

QUERY: 08
Q8. Write a query to add a new column in to employee

Syntax: To add a new column.


SQL> ALTER TABLE <TABLE NAME> ADD (<COLUMN NAME><DATATYPE><SIZE>);

Command:
SQL> ALTER TABLE EMP ADD QUALIFICATION
VARCHAR2(6); Table altered.
SQL> DESC EMP;
Name Null? Type
---------------- --------------------
---- EMPNO
NUMBER(7) ENAME
VARCHAR2(12) DESIGNATIN
VARCHAR2(10)
SALARY
NUMBER(8,2) QUALIFICATION
VARCHAR2(6)

QUERY: 09
Q9: Write a query to add multiple columns in to employee Syntax: Syntax for add a new
column.
SQL> ALTER TABLE <TABLE NAME> ADD (<COLUMN NAME1><DATATYPE><SIZE>,
(<COLUMN NAME2><DATA TYPE><SIZE>…);
Command:

SQL>ALTER TABLE EMP ADD (DOB DATE, DOJ


DATE); Table altered.

SQL> DESC EMP;


Name Null? Type
----------------- ---------------------------
EMPNO NUMBER(7)
ENAME VARCHAR2(12)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)
QUALIFICATION VARCHAR2(6)
DOB DATE
DOJ DATE

REMOVE / DROP

It will delete the table structure provided the table should be empty.
QUERY: 10
Q10. Write a query to drop a column from an existing table employee

Syntax: syntax for add a new column.


SQL> ALTER TABLE <TABLE NAME> DROP COLUMN <COLUMN NAME>;

Command:
SQL> ALTER TABLE EMP DROP COLUMN
DOJ; Table altered.

SQL> DESC EMP;


Name Type
----------------- ---------------------------
EMPNO NUMBER(7)
ENAME VARCHAR2(12)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)
QUALIFICATION VARCHAR2(6)
DOB DATE

QUERY: 11
Q11. Write a query to drop multiple columns from employee

Syntax:The Syntax for add a new column.


SQL> ALTER TABLE <TABLE NAME> DROP <COLUMNNAME1>,<COLUMN NAME2>,
……….. ;

Command:
SQL> ALTER TABLE EMP DROP (DOB,
QUALIFICATION); Table altered.

SQL> DESC EMP;


Name Null? Type
------------------ -----------------------
EMPNO NUMBER(7)
ENAME VARCHAR2(12)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)

RENAME

QUERY: 12

Q12. Write a query to rename table emp to employee

Syntax:The Syntax for add a new column.

SQL> ALTER TABLE RENAME <OLD NAME> TO <NEW NAME>

Command:

SQL> ALTER TABLE RENAME EMP TO


EMPLOYEE; SQL> DESC EMPLOYEE;
Name Null? Type

------------------- --------------------------
EMPNO NUMBER(7)
ENAME VARCHAR2(12)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)

TRUNCATE TABLE

If there is no further use of records stored in a table and the structure has to be retained then the
records alone can be deleted.
Syntax:

TRUNCATE TABLE <TABLE N


AME>;

Example:

Truncate table EMP;

DROP

To remove a table along with its structure and data.

Syntax:The Syntax for add a new column.

SQL> Drop table<table name>;

Command:

SQL> drop table employee;


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

INSERT

The SQL INSERT INTO Statement is used to add new rows of data to a table in the database.

Insert a record from an existing table: QUERY: 01


Q1. Write a query to insert the records in to employee.

Syntax: syntax for insert records in to a table

SQL :> INSERT INTO <TABLE NAME> VALUES< VAL1, ‘VAL2’,…..);

Command:
SQL>INSERT INTO EMP VALUES (101,'NAGARAJAN','LECTURER',15000);

1 row created.

Insert A Record Using Substitution Method:


QUERY: 02
Q2. Write a query to insert the records in to employee using substitution method.

Syntax: syntax for insert records into the table.

SQL :> INSERT INTO <TABLE NAME> VALUES< ‘&column name’, ‘&column name 2’, …..);

Command:

SQL> INSERT INTO EMP


VALUES(&EMPNO,'&ENAME','&DESIGNATIN','&SALARY'); Enter value for empno: 102
Enter value for ename:
SARAVANAN
Enter value for designatin:
LECTURER
Enter value for salary: 15000
1 row created.

old 1: INSERT INTO EMP VALUES(&EMPNO,'&ENAME','&DESIGNATIN','&SALARY')


new 1: INSERT INTO EMP
VALUES(102,'SARAVANAN','LECTURER','15000') SQL> /

Enter value for empno: 103

Enter value for ename:


PANNERSELVAM
Enter value for designatin: ASST. PROF
Enter value for salary: 20000
1 row created.

old 1: INSERT INTO EMP VALUES(&EMPNO,'&ENAME','&DESIGNATIN','&SALARY')

new 1: INSERT INTO EMP VALUES(103,'PANNERSELVAM','ASST.PROF','20000')

SQL> /

Enter value for empno: 104


Enter value for ename: CHINNI
Enter value for designatin:
HOD, PROF
Enter value for salary: 45000
222
222
1 row created.

old 1: INSERT INTO EMP VALUES(&EMPNO,'&ENAME','&DESIGNATIN','&SALARY')

new 1: INSERT INTO EMP VALUES(104,'CHINNI','HOD, PROF','45000')

SQL> SELECT * FROM EMP;


EMPNO ENAME DESIGNATIN SALARY

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


101 NAGARAJAN LECTURER 15000
102 SARAVANAN LECTURER 15000
103 PANNERSELVAM ASST. PROF 20000
104 CHINNI HOD, PROF 45000

SELECT

SELECT Statement is used to fetch the data from a database table which returns data in
the form of result table. These result tables are called result-sets.

Display the EMP table:


QUERY: 03
Q3. Write a query to display the records from employee.

Syntax: Syntax for select Records from the


table. SQL> SELECT * FROM <TABLE
NAME>; Command:
SQL> SELECT * FROM EMP;

EMPNO ENAME DESIGNATIN SALARY

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

101 NAGARAJAN LECTURER 15000

UPDATE
The SQL UPDATE Query is used to modify the existing records in a table. You can use WHERE
clause with UPDATE query to update selected rows, otherwise all the rows would be affected.

QUERY: 04

Q4. Write a query to update the records from employee.

Syntax: syntax for update records from the table.


SQL> UPDATE <<TABLE NAME> SET <COLUMNANE>=<VALUE> WHERE
<COLUMN NAME=<VALUE>;
Command:
SQL> UPDATE EMP SET SALARY=16000 WHERE
EMPNO=101; 1 row updated.
SQL> SELECT * FROM EMP;

EMPNO ENAME DESIGNATIN SALARY


---------- ------------ ------------------- ---------------
101 NAGARAJAN LECTURER 16000
102 SARAVANAN LECTURER 15000
103 PANNERSELVAM ASST. PROF 20000
104 CHINNI HOD,PROF 45000

Update Multiple
Columns: QUERY: 05
Q5. Write a query to update multiple records from employee.

Syntax: syntax for update multiple records from the table.

SQL> UPDATE <<TABLE NAME> SET <COLUMNANE>=<VALUE> WHERE


<COLUMN NAME=<VALUE>;

Command:

SQL>UPDATE EMP SET SALARY = 16000, DESIGNATIN='ASST. PROF' WHERE EMPNO=102;

1 row updated.

SQL> SELECT * FROM EMP;

EMPNO ENAME DESIGNATIN SALARY


---------- ------------ -------------------- --------------
101 NAGARAJAN LECTURER 16000
102 SARAVANAN ASST. PROF 16000
103 PANNERSELVAM ASST. PROF 20000
104 CHINNI HOD, PROF 45000

DELETE

The SQL DELETE Query is used to delete the existing records from a table. You can use
WHERE clause with DELETE query to delete selected rows, otherwise all the records would be
deleted.
QUERY: 06

Q6. Write a query to delete records from employee.

Syntax: Syntax for delete Records from the table:

SQL> DELETE <TABLE NAME> WHERE <COLUMN NAME>=<VALUE>;

Command:

SQL> DELETE EMP WHERE EMPNO=103;

1 row deleted.

SQL> SELECT * FROM EMP;

EMPNO ENAME DESIGNATIN SALARY

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

101 NAGARAJAN LECTURER 16000

102 SARAVANAN ASST. PROF 16000

104 CHINNI HOD, PROF 45000


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.

Syntax:
SAVEPOINT<SAVEPOINT_NAME
>; Ex:
SQL> create table ORDER_PROCESSING(
Order_ID number(3), Product_ID varchar2(10), Quantity number(3,2), Price number(4,2));

Table created.

SQL> insert into ORDER_PROCESSING values(101,'RICE-22','6.5','30.50');

1 row created.

SQL> insert into ORDER_PROCESSING values(102,'OIL','2.0','90.50');

1 row created.
SQL> SELECT * FROM ORDER_PROCESSING;
ORDER_IDPRODUCT_ID QUANTITY PRICE
-------------- ---------------- -------------- ----------
101 RICE-22 6.5 30.5
102 OIL 2 90.5

SQL> COMMIT; Commit complete.

SQL> insert into ORDER_PROCESSING values(103,'BAGS','2','95');

1 row created.

SQL> insert into ORDER_PROCESSING values(104,'WATER BOTS','2','20');

1 row created.

SQL> SAVEPOINT A; Savepoint created.

SQL> insert into ORDER_PROCESSING values(105,'EGG','8','40.50');

1 row created.

SQL> insert into ORDER_PROCESSING values(106,'SHAMPOO','1','75.50');

1 row created.

SQL> SAVEPOINT B; Savepoint created.

SQL> insert into ORDER_PROCESSING values(107,'BAR SOAP','1','45.50');

1 row created.

SQL> insert into ORDER_PROCESSING values(108,'TONER','1','75.50');

1 row created.

SQL> SAVEPOINT C;
Savepoint created.

SQL> insert into ORDER_PROCESSING values(109,'SUGAR','2.0','60.50');


1 row created.
SQL> SELECT * FROM ORDER_PROCESSING;

ORDER_ID PRODUCT_ID QUANTITY PRICE


-------------- ---------------- --------------- ----------
101 RICE-22 6.5 30.5
102 OIL 2 90.5
103 BAGS 2 95

104 WATER BOTS2 20


105 EGG 8 40.5
106 SHAMPOO 1 75.5
107 BAR SOAP 1 45.5
108 TONER 1 75.5
109 SUGAR 2 60.5
9 rows selected.
SQL> ROLLBACK TO B;

Rollback complete.

SQL> SELECT * FROM ORDER_PROCESSING;

ORDER_ID PRODUCT_ID QUANTIT PRICE


---------------- ------------------- -------------- ------------
101 RICE-22 6.5 30.5
102 OIL 2 90.5
103 BAGS 2 95
104 WATER BOTS 2 20
105 EGG 8 40.5
106 SHAMPOO 1 75.5
6 rows
SQL> ROLLBACK TO A;

Rollback complete.

SQL> SELECT * FROM ORDER_PROCESSING;

ORDER_ID PRODUCT_ID QUANTITY PRICE


---------------- -------------------- ---------------- -----------
101 RICE-22 6.5 30.5
102 OIL 2 90.5
103 BAGS 2 95
104 WATER BOTS 2 20
SQL> ROLLBACK;
Rollback complete.

SQL> SELECT * FROM ORDER_PROCESSING;

ORDER_ID PRODUCT_ID QUANTITY PRIC


E
--------------- -------------------- ---------------- -------------
101 RICE-22 6.5 30.5
102 OIL 2 90.5
SQL> ROLLBACK;

Rollback complete.

SQL> SELECT * FROM ORDER_PROCESSING;


ORDER_ID PRODUCT_ID QUANTITY PRICE
---------------- ------------------- ---------------- -----------

101 RICE-22 6.5 30.5

102 OIL 2 90.5


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.


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 := 10;
B := 20;

C := A + B; DBMS_OUTPUT.PUT_LINE(C);
DBMS_OUTPUT.PUT_LINE( ‘sum of two numbers’ || C);
END;

Output:

30

sum of two numbers 30

PL/SQL procedure successfully completed.

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;

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:

Enter value for b: ramu

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


new 2: b varchar2(10) :=
'ramu'; revised string isumar

PL/SQL procedure successfully completed.

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

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

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

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


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.

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.

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.

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.

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.
D
i
s
p
l
a
y
i
n
g

r
o
w
s

a
f
t
e
r

e
x
e
c
u
t
i
o
n
:

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.

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
b number;

begin

b:=1;

for i in 1..n loop

b:=b*i;
end loop;

return b;

end;

SQL>Declare

n number:=&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.

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.


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

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.

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.

1. Create a trigger that insert current user into a username column of an


existing table

Program:

SQL> create table itstudent4(name


varchar2(15),username varchar2(15)); Table created.

SQL> create or replace trigger itstudent4 before insert on itstudent4 for each row

2 declare

3 name varchar2(20);

4 begin

5 select user into name from dual;

6 :new.username:=name;

7 end;

8 /

Trigger
created.
e)Output:

SQL> insert into itstudent4


values('&name','&username'); Enter value for
name: akbar

Enter value for username: ranjani

old 1: insert into itstudent4 values('&name','&username')

new 1: insert into itstudent4 values('akbar','ranjani')


1 row
created.
SQL> /

Enter value for name: suji


Enter value for username:
priya
old 1: insert into itstudent4 values('&name','&username')

new 1: insert into itstudent4 values('suji','priya')

1 row created.

SQL> select * from itstudent4;

NAME USERNAME

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

akbar SCOTT

suji SCOTT

2. Create a Simple Trigger that does not allow Insert, Update and Delete
Operations on the Table

Program: Table used:

SQL> select * from itempls;


ENAME EID SALARY
---------- --------- ---------

xxx 11 10000
yyy 12 10500

zzz 13 15500

Trigger:

SQL> create trigger ittrigg before insert or update or delete on itempls for
each row 2 begin
3 raise_application_error(-20010,'You cannot do
manipulation'); 4 end;

6/

Trigger created.

Output:

SQL> insert into itempls


values('aaa',14,34000); insert into itempls
values('aaa',14,34000)

ERROR at line 1:

ORA-20010: You cannot do manipulation


ORA-06512: at "STUDENT.ITTRIGG", line
2
ORA-04088: error during execution of trigger 'STUDENT.ITTRIGG'

SQL> delete from itempls where


ename='xxx'; delete from itempls where
ename='xxx'
*

ERROR at line 1:

ORA-20010: You cannot do manipulation


ORA-06512: at "STUDENT.ITTRIGG", line
2
ORA-04088: error during execution of trigger 'STUDENT.ITTRIGG'

SQL> update itempls set eid=15 where


ename='yyy'; update itempls set eid=15
where ename='yyy'
*

ERROR at line 1:

ORA-20010: You cannot do manipulation


ORA-06512: at "STUDENT.ITTRIGG", line
2
ORA-04088: error during execution of trigger 'STUDENT.ITTRIGG'

3. Create a Trigger that raises an User Defined Error Message and does not allow
updating and Insertion

Program: Table
used:

SQL> select * from itempls;


ENAME EID SALARY

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

xxx 11 10000

yyy 12 10500
zzz 13 15500

Trigger:

SQL> create trigger ittriggs before insert or update of salary on itempls for each
row

2 declare
3 triggsal itempls.salary%type;

4 begin
5 select salary into triggsal from itempls where eid=12;

6 if(:new.salary>triggsal or :new.salary<triggsal) then


7 raise_application_error(-20100,'Salary has not been changed');

8 end if;
9 end;

10 /

Trigger created.
Output:

SQL> insert into itempls values


('bbb',16,45000); insert into itempls values
('bbb',16,45000)

ERROR at line 1:

ORA-04098: trigger 'STUDENT.ITTRIGGS' is invalid and failed re-


validation SQL> update itempls set eid=18 where ename='zzz';

update itempls set eid=18 where ename='zzz'

ERROR at line 1:

ORA-04298: trigger 'STUDENT.ITTRIGGS' is invalid and failed re-validation

4. To write a TRIGGER to ensure that DEPT TABLE does not contain duplicate of
null values in DEPTNO column.

INPUT

CREATE OR RELPLACE TRIGGER trig1 before insert on dept for each row

DECLARE

a number;

BEGIN

if(:new.deptno is Null) then

raise_application_error(-20001,'error::deptno cannot be null');

else
select count(*) into a from dept where deptno=:new.deptno;

if(a=1) then

raise_application_error(-20002,'error:: cannot have duplicate deptno');

end if;

end if;

END;

RESULT:

SQL> @trigger

Trigger created.

SQL> select * from dept;

DEPTNO DNAME LOC

--------- -------------- 10 ACCOUNTING NEW YORK


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

20 RESEARCH DALLAS

30 SALES CHICAGO

40 OPERATIONS BOSTON

SQL> insert into dept values(&deptnp,'&dname','&loc');

Enter value for deptnp: null

Enter value for dname: marketing

Enter value for loc: hyd

old 1: insert into dept values(&deptnp,'&dname','&loc')

new 1: insert into dept values(null,'marketing','hyd')

insert into dept values(null,'marketing','hyd')

ERROR at line 1:

ORA-20001: error::deptno cannot be null


35

ORA-06512: at "SCOTT.TRIG1", line 5

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

SQL> /

Enter value for deptnp: 10

Enter value for dname: manager

Enter value for loc: hyd

old 1: insert into dept values(&deptnp,'&dname','&loc')

new 1: insert into dept values(10,'manager','hyd')

insert into dept values(10,'manager','hyd')

ERROR at line 1:

ORA-20002: error:: cannot have duplicate deptno

ORA-06512: at "SCOTT.TRIG1", line 9

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

SQL> /

Enter value for deptnp: 50

Enter value for dname: MARKETING

Enter value for loc: HYDERABAD

old 1: insert into dept values(&deptnp,'&dname','&loc')

new 1: insert into dept values(50,'MARKETING','HYDERABAD')

1 row created.

SQL> select * from dept;

DEPTNO DNAME LOC

--------- -------------- 10 ACCOUNTING NEW YORK


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

20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

50 MARKETING HYDE

5. Write a trigger on the employee table which shows the old values and new
values of Ename after any updations on ename on Employee table.

SOLUTION:

SQL> select * from employee;

EMPLOYEE_NAM
EMP_NO E STREET CITY
---------- -------------------- -------------------- ------------------

1 rajesh first cross gulbarga

2 paramesh second cross bidar


3 pushpa ghandhi road banglore

4 vijaya shivaji nagar manglore


5 keerthi anand sagar street bijapur

SQL> get e:/plsql/l12.sql;

1 create or replace trigger show

2 before update on employee


3 for each row

4 begin
5 dbms_output.put_line('the old name was :');

6 dbms_output.put_line(:old.employee_name);
7 dbms_output.put_line('the updated new name is :');

8 dbms_output.put_line(:new.employee_name);
9* end;
SQL> /
Trigger created.

SQL> update employee set employee_name='kiran' where emp_no=1; the


old name was :

rajesh

the updated new name is :


kiran

1 row updated.

SQL> select * from employee;

EMPLOYEE_NAM
EMP_NO E STREET CITY

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

1 kiran first cross gulbarga

2 paramesh second cross bidar


3 pushpa ghandhi road banglore

4 vijaya shivaji nagar manglore


5 keerthi anand sagar street bijapur

5. Create a Trigger to check the age valid and Raise appropriate error code and error
message.

SQL> create table data(name char(10),age number(3));

Table created.

SQL> desc data;


Name Null? Type

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

NAME CHAR(10)

AGE NUMBER(3)

SQL> CREATE TRIGGER DATACHECK AFTER INSERT OR UPDATE OF AGE ON


DATA

FOR EACH ROW

BEGIN IF(:NEW.AGE<0)
THEN

RAISE_APPLICATION_ERROR(-20000,'NO NEGATIVE AGE


ALLOWED'); END IF;

END;

Trigger created.

SQL> INSERT INTO DATA


VALUES('ABC',10); 1 ROW CREATED.

SQL> INSERT INTO DATA VALUES ('DEF',-15)

ERROR at line 1:

ORA-20000: No negative age allowed


ORA-06512: at "4039.DATACHECK", line
3

ORA-04088: error during execution of trigger '4039.DATACHECK'

NAME AGE
---------- ----------

abc 10

6. Create a Trigger for EMP table it will update another table SALARY while
inserting values.

SQL> CREATE TABLE SRM_EMP2(INAME VARCHAR2(10), IID NUMBER(5),


SALARY

NUMBER(10));

Table created.

SQL> CREATE TABLE SRM_SAL2(INAME VARCHAR2(10), TOTALEMP


NUMBER(5),

TOTALSAL NUMBER(10));

Table created.

SQL> CREATE OR REPLACE TRIGGER EMPTRIGR22 AFTER INSERT ON


SRM_EMP2

FOR EACH ROW

DECLARE

A VARCHAR2(10);

BEGIN

A:=:NEW.INAME;

UPDATE SRM_SAL2 SET

TOTALSAL=TOTALSAL+:NEW.SALARY,TOTALEMP=TOTALEMP+1
WHERE INAME=A;

END;

/
Trigger created.

SQL> INSERT INTO SRM_SAL2 VALUES('VEC',0,0);

1 row created.

SQL> INSERT INTO SRM_SAL2 VALUES('SRM',0,0);

1 row created.

SQL> INSERT INTO SRM_EMP2

VALUES('VEC',100,1000); 1 row created.

SQL> SELECT * FROM SRM_SAL2;

INAME TOTALEMP TOTALSAL

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

VEC 1 1000

SRM 0 0

SQL> INSERT INTO SRM_EMP2 VALUES('SRM',200,3000);


1 row created.

SQL> SELECT * FROM SRM_SAL2;

INAME TOTALEMP TOTALSAL

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

VEC 1 1000

SRM 1 3000

SQL> INSERT INTO SRM_EMP2

VALUES('VEC',100,5000); 1 row created.

SQL> SELECT * FROM SRM_SAL2;


INAME TOTALEMP TOTALSAL

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

VEC 2 6000

SRM 1 3000

SQL> INSERT INTO SRM_EMP2 VALUES('VEC',100,2000);

1 row created.

SQL> SELECT * FROM SRM_SAL2;

INAME TOTALEMP TOTALSAL

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

VEC 3 8000

SRM 1 3000

SQL> INSERT INTO SRM_EMP2 VALUES('SRM',200,8000);

1 row created.

SQL> SELECT * FROM SRM_SAL2;

INAME TOTALEMP TOTALSAL

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

VEC 3 8000

SRM 2 11000

RESULT: Thus the Trigger procedure has been executed successfully for both before
and after sequences.
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.

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

verified..

You might also like