Dbms Lab Manual
Dbms Lab Manual
LAB MANUAL
BONAFIDE CERTIFICATE
________________________________
REGISTER NUMBER
Name: Reg No :
Marks Faculty
S.No Date Experiment
(100) Signature
9 Embedded SQL
9. Embedded SQL
PRE-REQUISITE:
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:
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.
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.
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)
Mapping of the Program’s Student Outcomes (PSOs) with the ABET Student Outcomes
(ESOs)
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
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.
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
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.
• SELECT
• INSERT
• DELETE
• UPDATE
ALGORITHM:
STEP 6: use save point if any changes occur in any portion of the record to undo its original
state.
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
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:
EVALUATION
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
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)
• 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
Numeric Functions
10. Find the employee with maximum salary, minimum salary in each department in the
ascending order of depno.
13. Display the rounded value of the ‘salary’ column in ‘Employee’ table.
Date Functions
15.Display the system date in the format mentioned below “27th October 1996”.
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.
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
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
PL/SQL.
3. We can have user defined error massages by using concept of exception handling.
PL/SQL Block:
DECLARE
Declaration of variable
Declaration of cursor----------
(OPTIONAL) Declaration of exception
BEGIN
EXCEPTION
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:
Ex:
SQL>set serveroutput on
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;
……
Else
Sequence of statements;
End if;
CASE
Syntax:
Case test-variable
Syntax:
Case test-variable
……
End case;
LABELED CASE
Syntax:
<<label>>
Case test-variable
sequence of statements;
……
SEARCHED
CASE Syntax:
Case
End case;
SIMPLE LOOP
Syntax:
Loop
Sequence of statements;
Exit when
Sequence of statements;
End loop;
Sequence of statements;
End loop;
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
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;
END;
/
COMMANDS:
DECLARE
Anumber;
BEGIN
A:=3;
DeletefromempwhereEmp_num=A;
END;
Algorithm:
3. Extract the characters one by one from the end of the string.
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;
g,1);
g := g - 1;
d := d ||
c; end loop;
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.
Output:
5: PL/SQL for Fibonacci Series.
Algorithm:
6. A:=B&B:=A
Program:
declare
end if;
c := a + b; dbms_output.put_line(c); a := b;
b :=
c; end loop;
exception
SQL>
/
1
2
3
5
8
a number:=0;
b number:=1;
c number;
i number;
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:
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:=&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’);
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:
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;
OUTPUT:
2
3
11
PROGRAM:
declare
n number;
i number;
j 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
Faculty Signature
RESULT:
Thus the PL/SQL program has been verified and executed successfully
Ex.No.5 PL/ SQL PROGRAM USING CURSORS
AIM
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.
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.
%NOTFOUND
row and if SELECT
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.
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
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.
Once the cursor is created in the declaration section we can access the cursor in the execution
section of the PL/SQL program.
OPEN cursor_name;
OR
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.
create a cursor;
BEGIN
END;
These are the attributes available to check the status of an explicit cursor.
1
137
Cursor_name%NOTFOUN
%NOTFOUND TRUE, , if fetch statement D
Cursor_name%ROWCOUN
%ROWCOUNT The number of rows fetched by T
error.
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
c_id employee.id%type;
c_name employee.name%type;
c_addr emp.address%type;
begin
open c_emp;
loop
end loop;
close c_emp;
end;
Output:
2. DISPLAYING EMPLOYEE DETAILS USING CURSORS.
Source code:
declare
no emp.eno%type;
name emp.ename%type;
begin
open emp_cur;
loop
end loop;
close emp_cur;
end;
Execution:
SQL> @e:\plsql\c1r.sql;
COMMANDS:
declare
emp_num emp.emp_num%type;
name emp.name%type;
dept_no emp.dept_no%type;
begin
open emp_cur;
loop
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;
begin
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;
------------------------------------
COMMANDS:
declare
i number(2);
E emp%rowtype;
i:=1;
open ec;
loop
fetch ec into E;
i:=i+1;
'||E.salary);
end loop;
close ec;
end;
Output:
Procedure:
Creating table:
SQL>create table Student(
sno number(4),
sname varchar(10),
m1 numbar(3),
m2 numbar(3),
m3 numbar(3));
table created.
1 row inserted.
1 row inserted.
Source code:
declare
stu student%rowtype;
total number(4);
result varchar(4);
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;
then
result:='pass';
else
result:='fail';
end if;
Dbms_output.put_line('total:'||total||' result:'||result);
end loop;
end;
Execution:
SQL> @e:\plsql\c3.sql
STUDENT MARKLIST
---------------------------
sno:500 sname:wasim
total:234 result:pass
STUDENT MARKLIST
--------------------------
sno:501 sname:siva
STUDENT MARKLIST
--------------------------
sno:502 sname:vani
total:234 result:pass
STUDENT MARKLIST
---------------------------
sno:504 sname:naga
total:150 result:fail
COMMANDS:
declare
stu student%rowtype;
total number(4);
result varchar(4);
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;
then
result:='pass';
else
result:='fail';
end if;
Dbms_output.put_line('total:'||total||' result:'||result);
end loop;
end;
/
Output:
5. PARAMETERIZED CURSOR
Source code:
declare
n number;
er emp%rowtype;
n:=&n;
1 open c(n);
if c%isopen then
loop
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
old 7: n:=&n;
new 7: n:=100;
COMMANDS:
declare
n number;
er emp%rowtype;
begin
n:=4;
open c(n);
if c%isopen then
loop
fetch c into er;
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:
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
emp_rec emp%rowtype;
begin
for emp_rec in c
loop
if emp_rec.salary<2000 then
where current of c;
end if;
end loop;
end;
----------------------------------------------------
Execution:
SQL>@E:\plsql\incr.sql ;
PL/SQL procedure successfully completed.
Displaying rows after execution:
----------------------------------------------------
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
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
emp_rec emp%rowtype;
begin
for emp_rec in c
loop
if emp_rec.salary<2000 then
where current of c;
end if;
end loop;
end;
Output:
EVALUATION
Faculty Signature
Result:
Thus the cursor program was implemented and verified
Ex: No: 6 PL/ SQL programs using Function
AIM:
ALGORITHM:
STEP 4: Create the function with necessary arguments and return data types.
STORED FUNCTION
CREATE FUNCTION
SYNTAX:
[(parameter[,parameter, ...])]
RETURN datatype
{IS | AS}
END [name];
Note:
OR REPLACE is used to create a function even though a function with the
same name already exists
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
I) PROGRAM:
SQL>create
function fnfact(n
number) return
number is
bn
g
i
b:=1;
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
COMMANDS:
declare
num number;
factorial 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);
end;
output:
Q2:create a function which count total no.of employees having salary less than 6000.
/*function body*/
C number;
Begin
Open
vin_cur;
C:=0;
loop
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
COMMANDS:
Declare
Ne number;
Xno emp.emp_num%type;
Xsal emp.salary%type;
C number;
begin
z := xno;
else
z := 0;
end if;
return z;
end;
Begin
open vin_cur;
loop
c := count_emp(xsal,xno);
end if;
end loop;
close vin_cur;
End;
output:
EVALUATION
Faculty Signature
Result:
AIM
To write a PL/SQL program using procedures..
SYNTAX
{IS|AS}
executable statements
[EXCEPTION
exce
ption
handlers]
END
[name];
EXECUTION:
Aim:
To Write a pl/sql program for creating a procedure for calculating sum of two
numbers.
Source code:
total number(6);
begin
total:=n1+n2;
dbms_output.put_line('the sum
is:'||total); end;
Execution:
Method1:
Method 2:
SQL> begin
2 sum(12,13);
3 end;
4 /
2. To write a PL/SQL block to display the student name, marks whose average mark
is above 60%.
ALGORITHM
STEP1:Start
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%.
EXECUTION
I) PROGRAM:
END;
Output:
Procedure created.
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;
begin
end;
Begin
open vin_cur;
loop
avg_stu(m1,m2,m3,tot);
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:
TOT := N1 + N2;
END;
Output:
Procedure created.
SQL> PRINT T
----------
99
GCD is
COMMANDS:
Declare
a number;
b number;
C number;
d number;
e number;
begin
if (b !=0) then
gcd(b,mod(a,b));
else
end;
Begin
a := 8;
b := 4;
c := a;
d := b ;
gcd(a,b);
End;
Statement processed.
OUTPUT:
EVALUATION
Faculty Signature
RESULT:
Aim
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.
parameters. parameters.
These are stored in These are stored in These are not stored in
database. database. database.
INSTEAD OF }
BEGIN
--- sql
statements
END;
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.
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.
: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
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 ( )
• The Error_message is the message you want to display when the error occurs.
Faculty Signature
RESULT: Thus the Trigger procedure has been executed successfully for both before
and after sequence.
Ex.No. 9 Embedded SQL
AIM
THEORY
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() {
scanf_s("%d", &OrderID);
FROM Orders
exit();
query_error:
>sqlcode); exit();
bad_number:
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.*;
try
{
Scanner sc= new Scanner(System.in);
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();
while(rs.next())
if(rs.getInt(1) == a){
con.close();
catch(Exception e)
System.out.println(e);
output:
ODBC:
Faculty Signature
RESULT: Thus the procedure for Embedded SQL has been executed successfully and
verified.