DBMS - Lab Manual
DBMS - Lab Manual
DBMS - Lab Manual
LAB MANUAL
Prepared By
Dr.R.Kanniga Devi
Mrs.R.Sumathi
SCHOOL OF COMPUTING
BONAFIDE CERTIFICATE
________________________________
REGISTER NUMBER
Name: Reg No :
Class : Faculty :
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.
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.
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
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:
VIVA VOCE
Database
S.No Experiments
schema
Query Output
Technica Communic
l ation
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
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
Command:
Table created.
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
REFERENCES table
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:
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.
Command:
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.
Command:
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.
To modify structure of an already existing table to add one more columns and
also modify the existing columns.
QUERY: 06
Q6: Write a Query to Alter the column EMPNO NUMBER (4) TO EMPNO NUMBER (6).
QUERY: 07
Q7. Write a Query to Alter the table employee with multiple columns (EMPNO,ENAME.)
Command:
SQL>ALTER TABLE EMP MODIFY (EMPNO NUMBER (7), ENAMEVARCHAR2(12)); Table
altered.
Command:
QUERY: 08
Q8. Write a query to add a new column in to employee
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:
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
Command:
SQL> ALTER TABLE EMP DROP COLUMN
DOJ; Table altered.
QUERY: 11
Q11. Write a query to drop multiple columns from employee
Command:
SQL> ALTER TABLE EMP DROP (DOB,
QUALIFICATION); Table altered.
RENAME
QUERY: 12
Command:
------------------- --------------------------
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:
Example:
DROP
Command:
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.
INSERT
The SQL INSERT INTO Statement is used to add new rows of data to a table in the database.
Command:
SQL>INSERT INTO EMP VALUES (101,'NAGARAJAN','LECTURER',15000);
1 row created.
SQL :> INSERT INTO <TABLE NAME> VALUES< ‘&column name’, ‘&column name 2’, …..);
Command:
SQL> /
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.
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
Update Multiple
Columns: QUERY: 05
Q5. Write a query to update multiple records from employee.
Command:
1 row updated.
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
Command:
1 row deleted.
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:
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.
1 row created.
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
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
SQL> SAVEPOINT C;
Savepoint created.
Rollback complete.
Rollback complete.
Rollback complete.
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.
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
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
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
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
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;
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 := g - 1;
d := d ||
c; end loop;
End;
c
:
=
s
u
b
s
t
r
(
b
,
Location is NEW YORK
OUTPUT:
Algorithm:
6. A:=B&B:=A
Program:
declare
end if;
c; end loop;
exception
end
;
SQL>
/
1
2
3
5
8
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’);
number is Armstrong
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
7
11
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.
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
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.
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.
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
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;
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;
close ec;
end;
Execution:
SQL> @e:\plsql\c2.sql;
------------------------------------
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;
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
5. PARAMETERIZED CURSOR
Source code:
declare
n number;
er emp%rowtype;
begin
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;
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.
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
:
----------------------------------------------------
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
Result:
Thus the cursor program was implemented and verified
AIM:
ALGORITHM:
STEP 4: Create the function with necessary arguments and return data types.
STORED 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:
begin
b:=1;
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
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
Faculty Signature
Result:
AIM
To write a PL/SQL program using procedures..
SYNTAX
{IS|AS}
executable statements
[EXCEPTION
exce
ption
handlers]
END
[name];
EXECUTION:
PROCEDURES 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;
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.
TOT := N1 + N2;
END;
Output:
Procedure created.
SQL> PRINT T
----------
99
GCD is
RESULT:
Aim
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.
BEGIN
- sql
statements
END;
trigger is fired only for rows that satisfy the condition specified.
Types of PL/SQL Triggers
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.
Program:
SQL> create or replace trigger itstudent4 before insert on itstudent4 for each row
2 declare
3 name varchar2(20);
4 begin
6 :new.username:=name;
7 end;
8 /
Trigger
created.
e)Output:
1 row created.
NAME USERNAME
--------------- ---------------
akbar SCOTT
suji SCOTT
2. Create a Simple Trigger that does not allow Insert, Update and Delete
Operations on the Table
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:
ERROR at line 1:
ERROR at line 1:
ERROR at line 1:
3. Create a Trigger that raises an User Defined Error Message and does not allow
updating and Insertion
Program: Table
used:
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;
8 end if;
9 end;
10 /
Trigger created.
Output:
ERROR at line 1:
ERROR at line 1:
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
else
select count(*) into a from dept where deptno=:new.deptno;
if(a=1) then
end if;
end if;
END;
RESULT:
SQL> @trigger
Trigger created.
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
ERROR at line 1:
SQL> /
ERROR at line 1:
SQL> /
1 row created.
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:
EMPLOYEE_NAM
EMP_NO E STREET CITY
---------- -------------------- -------------------- ------------------
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.
rajesh
1 row updated.
EMPLOYEE_NAM
EMP_NO E STREET CITY
5. Create a Trigger to check the age valid and Raise appropriate error code and error
message.
Table created.
NAME CHAR(10)
AGE NUMBER(3)
BEGIN IF(:NEW.AGE<0)
THEN
END;
Trigger created.
ERROR at line 1:
NAME AGE
---------- ----------
abc 10
6. Create a Trigger for EMP table it will update another table SALARY while
inserting values.
NUMBER(10));
Table created.
TOTALSAL NUMBER(10));
Table created.
DECLARE
A VARCHAR2(10);
BEGIN
A:=:NEW.INAME;
TOTALSAL=TOTALSAL+:NEW.SALARY,TOTALEMP=TOTALEMP+1
WHERE INAME=A;
END;
/
Trigger created.
1 row created.
1 row created.
VEC 1 1000
SRM 0 0
VEC 1 1000
SRM 1 3000
VEC 2 6000
SRM 1 3000
1 row created.
VEC 3 8000
SRM 1 3000
1 row created.
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
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.
RESULT: Thus the procedure for Embedded SQL has been executed successfully and
verified..