DBMS Lab Manual
DBMS Lab Manual
DBMS Lab Manual
P IT
Coimbatore-641048
LAB MANUAL
Prepared by Approved by
Mr.A.Dinesh Kumar,AP/CSE HoD/CSE
Department of Computer Science and Engineering /Dr.N.G.P IT
Department of Computer Science and Engineering /Dr.N.G.P IT
OBJECTIVE:
Learn to create and use a database
Be familiarized with a query language
Have hands on experience on DDL Commands
Have a good understanding of DML Commands and DCL commands
Familiarize advanced SQL queries.
Be Exposed to different applications
LIST OF EXPERIMENTS
1. Creation of a database and writing SQL queries to retrieve information from the
database.
2. Performing Insertion, Deletion, Modifying, Altering, Updating and Viewing records
based on conditions.
3. Creation of Views, Synonyms, Sequence, Indexes, Save point.
4. Creating an Employee database to set various constraints.
5. Creating relationship between the databases.
6. Study of PL/SQL block.
7. Write a PL/SQL block to satisfy some conditions by accepting input from the user.
8. Write a PL/SQL block that handles all types of exceptions.
9. Creation of Procedures.
10. Creation of database triggers and functions.
11. Mini project (Application Development using Oracle/ Mysql )
LAB EQUIPMENTS
Hardware and Software required for a batch of 20 students:
Hardware:
20 Personal Computers
Software:
Front end : VB/VC ++/JAVA
Back end: Oracle 11g, my SQL, DB2
Platform: Windows 2000 Professional/XP
Oracle server could be loaded and can be connected from individual PCs.
Department of Computer Science and Engineering /Dr.N.G.P IT
Department of Computer Science and Engineering /Dr.N.G.P IT
EXNO 1 &2
CS6312 Database Management Systems lab
DDL, DML, DCL AND TCL COMMANDS OF SQL
AIM :
To execute the SQL queries for Data Definition Language (DDL),Data
Manipulation Language (DML) ,Data control Language(DCL) and Transaction Control
languages(TCL) using oracle.
CREATE:
Description : To create a object in the database.
VIEW:
Description : To view the description of table.
Output :
ROLLNO NUMBER(5)
DEPT VARCHAR2(7)
COLLEGE VARCHAR2(10)
ALTER:
Description : This command is used to add,modify column in a table.
Syntax : alter table <table_name> add(columnname1 datatype,
columnname datatype, columnname3 datatype, ....);
TRUNCATE:
Description : Truncate command is used to delete all the rows from the table and
free the space containing the table.
Syntax : truncate table <table_name>;
Example : SQL> truncate table ss11;
Output : Table truncated.
DROP:
Description : The SQL DROP command is used to remove an object from the
database. If you drop a table, all the rows in the table is deleted and the table
structure is removed from the database.
Department of Computer Science and Engineering /Dr.N.G.P IT
Department of Computer Science and Engineering /Dr.N.G.P IT
DML statements deals with querying, updating, deleting and inseting records in
tables, views or schema.
DML commands are
Insert
Update
Select
Where clause
Delete
Department of Computer Science and Engineering /Dr.N.G.P IT
Department of Computer Science and Engineering /Dr.N.G.P IT
INSERT:
Description : This statement used to insert a row of data into table.
Output :
Enter value for rollno: 08
Enter value for name: bharathi
Enter value for mark1: 89
Enter value for mark2: 92
old 1: insert into ss17 values(&rollno,'&name',&mark1,&mark2)
new 1: insert into ss17 values(08,'bharathi',89,92)
1 row created.
SQL> /
Enter value for rollno: 01
Enter value for name: abi
Enter value for mark1: 66
Enter value for mark2: 45
old 1: insert into ss17 values(&rollno,'&name',&mark1,&mark2)
new 1: insert into ss17 values(01,'abi',66,45)
1 row created.
OR
Description : The second form specifies both the column names and the values
to be inserted.
SELECT:
Description : This command is used to select rows from a table.
Output :
ROLLNO NAME MARK1 MARK2
8 bharathi 89 92
1 abi 66 45
11 kiruthika 95 98
SCREEN SHOT
Department of Computer Science and Engineering /Dr.N.G.P IT
Department of Computer Science and Engineering /Dr.N.G.P IT
WHERE CLAUSE:
Description : The WHERE Clause is used to retrieve specific information from
a table excluding other irrelevant data.
The condition you provide in the WHERE clause filters the rows retrieved from
the table and gives you only those rows which you expected to see.
WHERE clause can be used along with SELECT, DELETE, UPDATE
statements.
Output :
NAME MARK1
----------- ----------
naveena 88
SCREEN SHOT
Department of Computer Science and Engineering /Dr.N.G.P IT
Department of Computer Science and Engineering /Dr.N.G.P IT
UPDATE:
Description : Updates existing data within a table.
8 bharathi 89 92 181
1 abi 66 45 111
11 kiruthika 95 98 193
17 naveena 88 74 162
3 teena 23 36 59
DELETE:
Description : This command is used to delete the row from database.
1 abi 66 45 111
11 kiruthika 95 98 193
Department of Computer Science and Engineering /Dr.N.G.P IT
Department of Computer Science and Engineering /Dr.N.G.P IT
17 naveena 88 74 162
3 teena 23 36 59
COMMIT:
Description : Used to save data that made by developer.
Syntax : commit;
Department of Computer Science and Engineering /Dr.N.G.P IT
Department of Computer Science and Engineering /Dr.N.G.P IT
ROLLBACK:
Description : Used to save data that made by developer.
Syntax : commit;
Single row or Scalar functions return a value for every row that is
processed in a query.
Group Functions:
Group functions are built-in SQL functions that operate on groups of rows
and return one value for the entire group.
AGGREGATE FUNCTION
1. AVG:
Description : The AVG() function returns the average value of a numeric
column.
Syntax : SELECT AVG(column_name) FROM <table_name>;
OUTPUT :
AVG(MARK1)
------------------
68
2. SUM :
Description : The SUM() function returns the total sum of a numeric column.
Syntax : SELECT SUM(column_name) FROM <table_name>;
Example : SQL> select sum(mark1) from ss17;
OUTPUT :
SUM(MARK1)
--------------------
272
3. MAX :
Description : The MAX() function returns the largest value of the selected
column.
OUTPUT :
MAX(MARK1)
--------------------
95
4. MIN :
Description : The MIN() function returns the smallest value of the selected
column.
OUTPUT :
MIN(MARK1)
--------------------
23
5. COUNT :
Description : The COUNT() function returns the numbers of rows .
Syntax : SELECT COUNT(column_name) FROM <table_name>;
Example : SQL> select count(name) from ss17;
OUTPUT :
COUNT(NAME)
----------------------
4
6. STDDEV :
Description : The STDDEV() function returns standard deviation of X .
OUTPUT :
STDDEV(MARK1)
-------------------------
32.444825
CS6312 Database Management Systems lab
7. VARIANCE :
Description : The VARIANCE() function returns variance of X.
OUTPUT :
VARIANCE(MARK1)
------------------------------
1052.66667
GRANT:
Description : This command is used for gives access privileges to users for
database.
REVOKE:
Description : This command is used for withdraw access privileges to users for
database.
Viva-Voce:
1. What is SQL?
2. What is database?
3. What is DBMS?
4. What is a Database system?
5. Advantages of DBMS?
6. Disadvantage in File Processing System?
7. What are the categories of SQL command?
8. What is DML?
9. What are DML command?
10. Give the general form of SQL Queries?
11. Define tuple variable?
12.Write the syntax to retrieve specific columns from a table:
13. Define DCL?
14. List the DCL commands used in data bases
15. What type of privileges can be granted?
16. Write the syntax for grant command
17. What are TCL commands?
RESULT:
Thus the DDL,DML, TCL,DCL commands of sql was executed
successfully and output is verified.
EXNO 3 CS6312 Database Management Systems lab
DATABASE OBJECTS
AIM :
To create a database objects and perform synonyms, sequence, views ,index and
save point objects.
SYNONYMS
A synonym is an alias or alternate name for a table, view, sequence or schema
objects.
The object can be of these types: table, view, sequence, stored procedure,
function, or package, and synonym.
5 raksha ooty b
8 dinu erode o
11 raji cbe d
CREATE A SYNONYM:
Description : Used to save data that made by developer.
5 raksha ooty b
8 dinu erode o
11 raji cbe d
grade='c';
1 row updated.
5 raksha ooty b
8 dinu erode o
11 raji cbe d
CS6312 Database Management Systems
lab
SEQUENCE
START WITH : defines the first number of the sequence. Default is one.
INCREMENT : define how many to add to get the nextvalues. Default is one.
MINVALUE : defines the lowest value of the sequence when the sequence
is created to count down (increment by a minus number).
NEXTVAL:
Description : Insert one row into table Nextval stands for nextvalue.
Output : NEXTVAL
-------------
1
2
3
4
5
6
6 rows selected.
CURRVAL:
Output : CURRVAL
--------------
6
6
6
6
6
6
6 rows selected.
ALTER:
AFTER ALTERING:
Sequence altered.
NEXTVAL
---------------
67
CS6312 Database Management Systems lab
68
69
70
71
72
6 rows selected.
Drop Sequence:
Description : Used to save data that made by developer.
VIEWS
CREATE A VIEW :
Description : A view is, in essence, a virtual table. It does not physically exist.
Rather, it is created by a query joining one or more tables.
Syntax : create view <view_name>as select col1,col2,... from <basetable>;
Create a virtual table based on the result set of the select statement.
Now query the view as follws:
UPDATING A VIEW :
Description : Update command for view is same as for tables.
After update
SQL> select * from myview;
EMPNO ENAME
---------- ----------
111 swathi
CS6312 Database Management Systems lab
44 uma
88 veena
14 kiruthi
DELETE A VIEW :
Description : Delete the row from database.
After delete
SQL> select * from myview;
EMPNO ENAME
---------- ----------
44 uma
88 veena
14 kiruthi
DROPPING A VIEW :
Description : Drop command for destroy the table from database.
INDEX
Creating a Indexes
Description : Drop command for destroy the table from database.
SAVEPOINT
Description : command is used to undo the Records in a particular transaction.
RESULT:
Thus the database objects (synonyms, sequences, views, index objects )
and (savepoint) tcl commands was executed successfully and output is verified.
EX NO 4 EMPLOYEE DATABASECS6312
USING Database Management Systems lab
CONSTRAINTS
AIM :
INTEGRITY CONSTRAINT
a) Domain Integrity
Verify wheather the data entered is n proper form and also they set a range for the
input data.
Not null
Check
Description :
While creating tables, by default the rows can have null value .
The enforcement of not null constraint in a table ensure that the table contains
values.
SYNTAX
Create table<table_name>(col1 data type CONSTRAINT<constraint name>
constraint def,col2 datatype);
Example : create table empn(eid number not null,ename varchar2(12) not null,dept
char(5),city varchar2(25));
CITY VARCHAR2(25)
Check Constraint:
Example : Create table empin(eid number not null,ename varchar2(12) not null,dept
char(5),gender varchar(2) check(gender in(‘M’,’F’)));
2)NOT IN :
SYNTAX : Check (col name NOT IN (set of values not permitted));
Example : Create table empino(eid number not null,ename varchar2(12) not null,dept
char(5),gender varchar(2) check(gender not in(‘M’,’F’)));
3)BETWEEN :
SYNTAX : Check (col name BETWEEN value1 AND value2);
CS6312 Database Management Systems lab
4)LIKE :
ENTITY INTEGRITY
REFERENCED KEY
Description : It is a unique or primary key upon which is defined on a column
belonging to the parent table.
Example : select distinct name from empss where 33<=(select eregno from
where name=’c’);
OUTPUT :
NAME
---------
Charu
Dharan
sharan
VIVA QUESTIONS
1. What is integrity constraint?
2. List the types of constraint.
3. Primary Key Constraint
4. Referential Integrity
RESULT :
Thus the various set of constraints are executed successfully and output is
verified.
EX No 5 CS6312
CREATING RELATIONSHIP Database Management
BETWEEN Systems lab
THE DATABASE
AIM :
To create a database and perform joins.
1. Simple Join
a) Equi-join:
Description :
o A join, which is based on equalities, is called equi-join.
o It combines rows that have the same values for the specified columns.
Output :
EMPNO ENAME JOB DEPTNO SAL DEPTNO DNAME CLGNAME
----------- ------------- -------- ------------- ------ -------------- ------------ ---------------
5 raja asp 1 20000 1 CSE ksr
8 ganga asp 2 17000 2 ece kite
30 veena ap 3 15000 3 IT KITE
12 kiruthika ap 3 15000 3 IT KITE
CS6312 Database Management Systems lab
b) Non Equi-join:
Description :
A join which is based on the relational operations other than = is called a
non equi-join.
Output :
EMPNO ENAME JOB DEPTNO SAL DEPTNO DNAME CLGNAME
---------- ------------ --------- -------------- ---------- ----------- --------------- ---------------
12 kiruthika ap 3 15000 1 CSE ksr
SCREEN SHORTS:
CS6312 Database Management Systems lab
2. Self join:
Description :
o Joining of a table to itself is known as self-join.
o It joins one row in a table to another.
o It can compare each row of the table to itself and also with other
rows of the same table.
Output :
ENAME JOB DNAME
------------- ----------- -------------
raja asp CSE
veena ap IT
kiruthika ap IT
3.Outer Join:
Description :
o It extends the result of a simple join.
o An outer join returns all the rows returned by simple join as well as
those rows from one table that do not match any row from the table.
o The symbol (+) represents outer join.
Output :
ENAME DEPTNO
---------- ----------
raja 1
ganga 2
veena 3
kiruthika 3
CS6312 Database Management Systems lab
VIVA QUESTIONS:
3. What is outer join? Explain Left outer join, Right outer join and Full outer join.
RESULT:
Thus the joins are executed successfully and output is verified.
EX No 6 CS6312
STUDY OF PL/SQL Database Management Systems lab
BLOCK
INTRODUCTION
The PL/SQL programming language was developed by Oracle Corporation in the
late 1980s as procedural extension language for SQL and the Oracle relational database.
Following are notable facts about PL/SQL:
PL/SQL can also directly be called from the command-line SQL*Plus interface.
Direct call can also be made from external programming language calls to
database.
PL/SQL ARCHITECTURE
These two environments are independent. PL/SQL is bundled with the Oracle server
but might be unavailable in some tools. In either environment, the PL/SQL engine
accepts as input any valid PL/SQL block or subprogram.
In Oracle Tools
Furthermore, if the block contains no SQL statements, the engine executes the
entire block at the application site. This is useful if your application can benefit from
conditional and iterative control.
Frequently, Oracle Forms applications use SQL statements merely to test the
value of field entries or to do simple computations. By using PL/SQL instead, you can
avoid calls to the Oracle server. Moreover, you can use PL/SQL functions to manipulate
field entries.
Advantages of PL/SQL
Full portability
Tight integration with Oracle
Tight security
Declarations
This section starts with the keyword DECLARE. It is an optional section and
defines all variables, cursors, subprograms, and other elements to be used in the
program.
Executable Commands
This section is enclosed between the keywords BEGIN and END and it is a
mandatory section. It consists of the executable PL/SQL statements of the program.
Exception Handling
This section starts with the keyword EXCEPTION. This section is again
optional and contains exception(s) that handle errors in the program.
Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested
within other PL/SQL blocks using BEGIN and END.
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;
CS6312 Database Management Systems lab
Hello World
For example:
text1
--text2 varchar4(12)
DATE
this section := 'Hello
:= SYSDATE;
is mandatory, mustworld';
-- current
contain dateone
at least andexecutable
time statement
BEGIN
SELECTThe street_number
symbol := functions as an assignment operator to store a value in a variable.
INTO number1
FROMBlocks
address can be nested: Because a block is an executable statement, it can appear
inWHERE
another block
name wherever an executable statement is allowed. A block to an interactive
= 'INU';
EXCEPTION
tool (such as SQL*Plus) or embed it in an Oracle Precompiler or OCI program. The
-- this section is optional
interactive tool or program runs the block one time. The block is not stored in the
WHEN OTHERS THEN
database, and for that reason, it is called an anonymous block (even if it has a label).
DBMS_OUTPUT.PUT_LINE('Error Code is ' || TO_CHAR(SQLCODE ) );
PL/SQL - PROCEDURES Message is ' || SQLERRM );
DBMS_OUTPUT.PUT_LINE('Error
END; A subprogram is a program unit/module that performs a particular task. These
subprograms are combined to form larger programs. This is basically called the
'Modular design'. A subprogram can be invoked by another subprogram or program
which is called the calling program.
A subprogram can be created:
At schema level
Inside a package
PL/SQL subprograms are named PL/SQL blocks that can be invoked with a set of
parameters. PL/SQL provides two kinds of subprograms:
Functions: these subprograms return a single value, mainly used to compute and
return a value.
Procedures: these subprograms do not return a value directly, mainly used to
perform an action.
Parts of a PL/SQL Subprogram
Each PL/SQL subprogram has a name, and may have a parameter list. Like
anonymous PL/SQL blocks and, the named blocks a subprograms will also have
following three parts:
Declarative Part
It is an optional part. However, the declarative part for a subprogram does
not start with the DECLARE keyword. It contains declarations of types, cursors,
constants, variables, exceptions, and nested subprograms. These items are local to
the subprogram and cease to exist when the subprogram completes execution.
Executable Part
This is a mandatory part and contains statements that perform the
designated action.
Exception-handling
This is again an optional part. It contains the code that handles run-time
errors.
Creating a Procedure
A procedure is created with the CREATE OR REPLACE PROCEDURE
statement.
Where,
procedure-name specifies the name of the procedure.
CS6312 Database Management Systems lab
The optional parameter list contains name, mode and types of the parameters. IN
represents that value will be passed from outside and OUT represents that this
parameter will be used to return a value outside of the procedure.
procedure-body contains the executable part.
PL/SQL - Functions
A PL/SQL function is same as a procedure except that it returns a value.
Creating a Function
A standalone function is created using the CREATE FUNCTION statement. The
simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as
follows:
Where,
The optional parameter list contains name, mode and types of the parameters. IN
represents that value will be passed from outside and OUT represents that this
parameter will be used to return a value outside of the procedure.
RETURN clause specifies that data type you are going to return from the
function.
o function-body contains the executable part.
o function-body must contain a RETURN statement.
CS6312 Database Management Systems lab
PL/SQL - Cursors
Oracle creates a memory area, known as context area, for processing an SQL
statement, which contains all information needed for processing the statement, for
example, number of rows processed, etc.
A cursor is a pointer to this context area. PL/SQL controls the context area
through a cursor. A cursor holds the rows (one or more) returned by a SQL statement.
The set of rows the cursor holds is referred to as the active set.
There are two types of cursors:
Implicit cursors
Explicit cursors
Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement
is executed, when there is no explicit cursor for the statement. Programmers cannot
control the implicit cursors and the information in it.
In PL/SQL, the most recent implicit cursor as the SQL cursor, which always has
the attributes like %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. The
SQL cursor has additional attributes, %BULK_ROWCOUNT and
%BULK_EXCEPTIONS, designed for use with the FORALL statement.
Explicit Cursors
Explicit cursors are programmer defined cursors for gaining more control over
the context area. An explicit cursor should be defined in the declaration section of the
PL/SQL Block. It is created on a SELECT Statement which returns more than one row.
The syntax for creating an explicit cursor is :
For example:
OPEN c_customers;
Fetching the Cursor
Fetching the cursor involves accessing one row at a time.
CLOSE c_customers;
Example:
Following is a complete example to illustrate the concepts of explicit cursors:
DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CS6312 Database Management Systems lab
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
EXIT WHEN c_customers%notfound;
END LOOP;
CLOSE c_customers;
END;
/
When the above code is executed at SQL prompt, it produces the following result:
1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP
PL/SQL - Triggers
Triggers are stored programs, which are automatically executed or fired when
some events occur. Triggers are, in fact, written to be executed in response to any of the
following events:
Creating Triggers
The syntax for creating a trigger is:
Where,
{BEFORE | AFTER | INSTEAD OF}: This specifies when the trigger would be
executed. The INSTEAD OF clause is used for creating trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.
[OF col_name]: This specifies the column name that would be updated.
[ON table_name]: This specifies the name of the table associated with the trigger.
[REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old
values for various DML statements, like INSERT, UPDATE, and DELETE.
[FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger would be
executed for each row being affected. Otherwise the trigger will execute just once
when the SQL statement is executed, which is called a table level trigger.
WHEN (condition): This provides a condition for rows for which the trigger
would fire. This clause is valid only for row level triggers.
CS6312 Database Management Systems lab
Example:
To start with, we will be using the CUSTOMERS table:
S
e
l
e
c
t
|2
*0||
0|
31f0|
2r.2
|
|o05
|0
m
+
|R
The following program creates a row level trigger for the customers table that -ac| |
-A
would fire for INSERT or UPDATE or DELETE operations performed on the m u-h1
CUSTOMERS table. This trigger will display the salary difference between the old es-m 5D
st0e
values and new values: +
ehl
o-d0
CREATE OR REPLACE TRIGGER display_salary_changes |m h
BEFORE DELETE OR INSERT OR UPDATE ON customers -a.
e-b0i
FOR EACH ROW r-a0|
WHEN (NEW.ID > 0) s-d2
DECLARE ;-
sal_diff number; -||2
BEGIN -+ 23
sal_diff := :NEW.salary - :OLD.salary; --0
K
--0
dbms_output.put_line('Old salary: ' || :OLD.salary); h+
dbms_output.put_line('New salary: ' || :NEW.salary); -i-0|
dbms_output.put_line('Salary difference: ' || sal_diff); + .
-l0
END; -aK
/ -n0o
-|t
When the above code is executed at SQL prompt, it produces the following result: -|a
+
--6
Trigger created. -5|
-3-
--0
-|02
-.5
-k-0
-+ 0
a-
-u|
-
--h8M
-i5u
-k0m
-+ 0
|-.b
-a
+
--0i
--40|
-
-||2
-47
--5
C
--0
h-0|
-a-
--i.B
-t0h
0
-ao
-lp
--|a
i-
-|l
-
|--
+
+
-5
2-
2-|
-
|-H
-a
M
-r
P
-d
-i
-k
-|
-
-
-6
-
-|
+
|
K
o
I
m
aD
l
|
N
A
M
E
|
A
CS6312 Database Management Systems lab G
E
Here following two points are important and should be noted carefully: |
OLD and NEW references are not available for table level triggers, rather you A
can use them for record level triggers. D
D
If you want to query the table in the same trigger, then you should use the
R
AFTER keyword, because triggers can query the table or change it again only E
after the initial changes are applied and the table is back in a consistent state. S
Above trigger has been written in such a way that it will fire before any DELETE S
or INSERT or UPDATE operation on the table, but you can write your trigger on
a single or multiple operations, for example BEFORE DELETE, which will fire |
whenever a record will be deleted using DELETE operation on the table.
S
PL/SQL - Packages A
L
PL/SQL packages are schema objects that groups logically related PL/SQL types, A
variables and subprograms. R
Y
A package will have two mandatory parts:
Package specification |
+
Package body or definition -
-
Package Specification -
+
The specification is the interface to the package. It just DECLARES the types, -
variables, constants, exceptions, cursors, and subprograms that can be referenced from -
outside the package. In other words, it contains all information about the content of the -
package, but excludes the code for the subprograms. -
-
All objects placed in the specification are called public objects. Any subprogram
-
not in the package specification but coded in the package body is called
-
a private object.
-
The following code snippet shows a package specification having a single -
procedure. You can have many global variables defined and multiple procedures or -
functions inside a package. +
-
CREATE PACKAGE cust_sal AS -
PROCEDURE find_sal(c_id customers.id%type); -
END cust_sal; -
/ -
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
CS6312 Database Management Systems lab
When the above code is executed at SQL prompt, it produces the following result:
Package created.
Package Body
The package body has the codes for various methods declared in the package
specification and other private declarations, which are hidden from code outside the
package.
The CREATE PACKAGE BODY Statement is used for creating the package body. The
following code snippet shows the package body declaration for the cust_sal package
created above.
When the above code is executed at SQL prompt, it produces the following result:
Package body created.
Using the Package Elements
The package elements (variables, procedures or functions) are accessed with the
following syntax:
package_name.element_name;
Consider, we already have created above package in our database schema, the following
program uses the find_sal method of the cust_sal package:
DECLARE
code customers.id%type := &cc_id;
BEGIN
cust_sal.find_sal(code);
END;
/
CS6312 Database Management Systems lab
When the above code is executed at SQL prompt, it prompt to enter customer ID, and
when you enter an ID, it displays the corresponding salary as follows:
VIVA QUESTIONS
1. What is PL/SQL?
2. What is the basic structure of PL/SQL?
3. What are the components of a PL/SQL Block?
4. What are the datatypes a available in PL/SQL?
5. What is the difference between a procedure and a function?
6. Describe the use of %ROWTYPE and %TYPE in PL/SQL?
RESULT:
Thus the case study is studied.
EX NO 7 PL/SQLCS6312
BLOCK Database Management Systems lab
Q. Write a PL/SQL block to satisfy some conditions by accepting input from the user.
AIM:
To write a PL/SQL to implement the given program.
1. SIMPLE IF:
Syntax:
IF condition THEN
statement1;
statement2;
END IF;
Example:
SQL> set serveroutput on;
SQL> DECLARE
2 a number(2) := 10;
3 BEGIN
4 a:= 10;
9 END IF;
CS6312 Database Management Systems lab
10 dbms_output.put_line('value of a is : ' ||
a); 11 END;
12 /
OUTPUT:
a is less than 20
value of a is : 10
Syntax
IF condition THEN
statement1;
ELSE
statement2;
CS6312 Database Management Systems lab
END IF;
Example:
SQL> set serveroutput on;
SQL> DECLARE
2 a number(3) := 100;
3 BEGIN
8 ELSE
10 END IF;
11 dbms_output.put_line('value of a is : ' ||
a); 12 END;
13 /
OUTPUT:
IF-THEN-ELSIF Statement
Syntax:
IF condition1 THEN
statement1;
ELSIF condition2 THEN
statement2;
ELSIF condition3 THEN
statement3;
ELSE
statement;
END IF;
Example :
SQL> set serveroutput on;
SQL> DECLARE
2 a number(3) := 100;
3 BEGIN
CS6312 Database Management Systems lab
4 IF ( a = 10 ) THEN
5 dbms_output.put_line('Value of a is 10' );
6 ELSIF ( a = 20 ) THEN
7 dbms_output.put_line('Value of a is 20' );
8 ELSIF ( a = 30 ) THEN
9 dbms_output.put_line('Value of a is 30' );
10 ELSE
12 END IF;
14 END;
15 /
OUTPUT:
None of the values is matching
Exact value of a is: 100
NESTED IF:
Syntax :
IF condition THEN
statement1;
ELSE IF condition THEN
statement2;
ELSE
statement3;
END IF;
END IF;
ELSE
statement3;
END IF;
Example :
SQL> DECLARE
2 a number(3) := 100;
CS6312 Database Management Systems lab
3 b number(3) := 200;
4 BEGIN
11 END IF;
12 END IF;
16 /
OUTPUT:
Value of a is 100 and b is 200
Step 5: If the condition is false check b is greater than c then ‘b’ is greater.
Step 7: PL/SQL procedure is completed and display greatest number among the
three number.
PROGRAM:
SQL> set serveroutput on;
SQL> declare
2 a number;
3 b number;
4 c number;
5 begin
6 a:=&a;
7 b:=&b;
8 c:=&c;
14 dbms_output.put_line('********************************');
16 dbms_output.put_line(a|| 'is
greater'); 17 else if b >c then
21 end if;
22 end if;
23 end;
24 /
OUTPUT:
Enter value for a: 23
old 6: a:=&a;
7: b:=&b;
new 7: b:=45;
Enter value for c: 12
old 8: c:=&c;
new 8: c:=12;
********************************
********************************
45 is greater
VIVA QUESTIONS:
1. Define block.
2. What are the two types of sub programs in PL/SQL?
3. List the Advantages of Sub programs.
4. What is Procedure?
5. Explain about REPLACE and AUTHID.
6. Define Function.
7. Give the syntax for Function.
8. What are the Parameters in Procedure?
9. Discuss abput control structures.
RESULT:
Thus, the PL/SQL programs have been executed successfully.
EXNO 8 CS6312 Database
EXCEPTION HANDLING Management Systems lab
IN PL/SQL
AIM :
To write a PL/SQL block to raise and handle different types of exceptions.
1. Checking whether any of the item with its unit is less than the pre-order level
using Pre-Defined Exception:
ALGORITHM :
Step 1 : Check in the item table whether any of the item’s unit is lesser than its
pre-order level.
Step 2 : If no data is found, then the NO_DATA_FOUND exception is raised
automatically.
Step 3 : Else if multiple rows are returned, then TOO_MANY_ROWS exception
is raised.
Step 4 : Else the name of the item is displayed.
Step 5 : End the PL/SQL block.
PROGRAM :
SQL>set serveroutput on;
SQL>declare
2 name varchar2(10);
3 begin
4 select iname into name from item where unit<pol;
5 dbms_output.put_line(‘the name of the item is ’|| name);
6 exception
7 when NO_DATA_FOUND then
8 dbms_output.put_line('None of the row matches the given condition');
9 when TOO_MANY_ROWS then
10 dbms_output.put_line(‘multiple rows matches the given condition');
11 end;
12 /
OUTPUT :
None of the row matches the given condition
2. Checking whether the item with its unit is less than the pre-order level using
User-Defined Exception:
ALGORITHM :
Step 1 : Declare the user-defined exception.
Step 2 : Read the id of the item.
Step 3 : Scan the item table for the matching id.
Step 4 : If found, then check whether it’s unit s less than the pre-order level.
Step 5 : If yes, then raise the exception by using the statement RAISE
EXCEPTION_NAME.
Step 6 : Else display the item name.
Step 7 : End the PL/SQL block.
PROGRAM :
SQL> set serverout on;
SQL> declare
2 iunit number;
3 ipol number;
4 DATA_NOT_AVAILABLE exception;
5 begin
6 select unit,pol into iunit,ipol from item where
id=1; 7 if ipol<iunit then
8 raise DATA_NOT_AVAILABLE;
9 end if;
10 exception
11 when DATA_NOT_AVAILABLE then
12 dbms_output.put_line('No records were retreived');
13 end;
14 /
OUTPUT :
No records were retrieved
ALGORITHM :
Step 1 : Declare an user-defined exception called SUCCESS_INSERT.
Step 2 : Write an SQL insert statement to insert the amount into the feespaid
table.
Step 3 : Check whether any of the row was updated.
Step 4 : If found, the raise the exception SUCCESS_INSERT.
Step 5 : Else the insertion error occurs.
Step 6 :End the PL/SQL block.
PROGRAM :
SQL>set serveroutput on;
SQL> declare
2 amount number(5);
3 sid number(5);
4 SUCCESS_INSERT exception;
5 begin
6 insert into feespaid
values(&id,&amt); 7 if SQL%FOUND
then
8 raise SUCCESS_INSERT;
CS6312 Database Management Systems lab
9 end if;
10 exception
11 when SUCCESS_INSERT then
12 dbms_output.put_line('Insertion done...');
13 end;
14 /
OUTPUT:
SQL> /
VIVA QUESTIONS:
1. What is an Exception? What are types of Exception?
2. What is Raise_application_error?
RESULT:
Thus, the exception handling in PL/SQL blocks have been executed successfully.
CS6312 Database Management Systems lab
ADDITIONAL PROGRAMS
a) THE FIBONACCI SERIES GENERATION
AIM
To write a PL/SQL program to generate Fibonacci series for ‘n’ numbers.
ALGORITHM:
Step 2: Declare all the variables assign the values for the some of the variables
Step 3: Add the two variables (a, b) and values are stored in the temporary
variables(c).
Step 4: Display the temporary variables(c) and swap the ‘a’ and ‘b’ values and
increment i value
PROGRAM:
SQL> declare
2 a number:=-1;
3 b number:=1;
4 c number;
5 i number:=1;
6 begin
7 dbms_output.put_line('The Fibonacci series is:');
8 for i in 1..5
9 loop
10 c:=a+b;
11 a:=b;
12 b:=c;
13 dbms_output.put_line(c);
14 end loop;
15 end;
16 /
OUTPUT:
The Fibonacci series is:
0
1
1
2
3
PL/SQL procedure successfully completed.
RESULT:
Thus the PL/SQL commands for generating Fibonacci series up to ‘n’ number was
executed and verified successfully.
CS6312 Database Management Systems lab
Step 2: Declare all the variables assign the values for s as 0(zero).
Step 4: check n is greater than 0, if it is calculate mod n and assign to the n2.
Step 5: Add n2 value with s and truncate floating value when n is divided into 10
Step 7: PL/SQL procedure is completed and display sum of digits of given number.
CS6312 Database Management Systems lab
PROGRAM:
SQL> declare
2 n number;
3 n1 number;
4 s number:=0;
5 n2 number;
6 begin
7 n:=&n;
8 n1:=n;
9 while n>0
10 loop
11 n2:=mod(n,10);
12 s:=s+n2;
13 n:=trunc(n/10);
14 end loop;
15 dbms_output.put_line('The sum of the given number is:'||s);
16 end;
17 /
OUTPUT:
Enter value for n: 23
old 7: n:=&n;
new 7: n:=23;
The sum of the given number is:5
RESULT:
Thus the PL/SQL commands for sum of digits of a given number was executed and verified
successfully.
CS6312 Database Management Systems lab
c) PALINDROME
AIM
To write a PL/SQL program to check whether a given string is palindrome or not.
ALGORITHM:
Step 4: Check L is greater than 0, if it is cut one character from last and store in the
string name2.
Step 5: Decrement L value by 1 and repeat step 4 to 5 until L equal to or less than
zero.
Step 6: Check name1 is equal to name2 if it is then print the given string is
PROGRAM
SQL> declare
2 name1 varchar(20);
3 name2 varchar(20);
4 l number;
5 begin
6 name1:='&name1';
7 l:=length(name1);
8 while l>0
9 loop
10 name2:=name2||substr(name1,l,1);
11 dbms_output.put_line(name2);
12 l:=l-1;
13 end loop;
14 dbms_output.put_line('Reverse of string');
15 dbms_output.put_line('******************************************');
16 if name1=name2
17 then
18 dbms_output.put_line(name1||' is palindrome');
19 else
20 dbms_output.put_line(name1||' is not palindrome');
21 end if;
22 end;
23 /
CS6312 Database Management Systems lab
OUTPUT:
SQL> /
Enter value for name1: hah
old 6: name1:='&name1';
new 6: name1:='hah';
h
ha
hah
Reverse of string
******************************************
hah is palindrome
RESULT:
Thus the PL/SQL commands to check a given string is palindrome or not was executed
and verified successfully.
CS6312 Database Management Systems lab
ALGORITHM:
a=a+b
b=a-b
a=a–b
Step 5: PL/SQL procedure is completed and display a and b value after swapping
CS6312 Database Management Systems lab
PROGRAM:
SQL> declare
2 a number;
3 b number;
4 begin
5 a:=&a;
6 b:=&b;
7 dbms_output.put_line('Swap the two values without using Third variables');
8 dbms_output.put_line('*************************************************');
9 dbms_output.put_line('The value of a:'||a);
10 dbms_output.put_line('The value of b:'||b);
11 a:=a+b;
12 b:=a-b;
13 a:=a-b;
14 dbms_output.put_line('The value of a after swapping: '||a);
15 dbms_output.put_line('The value of b after swapping: '||b);
16 end;
17 /
CS6312 Database Management Systems lab
OUTPUT:
Enter value for a: 9
old 5: a:=&a;
new 5: a:=9;
Enter value for b: 2
old 6: b:=&b;
new 6: b:=2;
Swap the two values without using Third variables
**************************************************************
The value of a:9
The value of b:2
The value of a after swapping: 2
The value of b after swapping: 9
RESULT:
Thus the PL/SQL commands to swap the two numbers without using third variables was
executed and verified successfully.
CS6312 Database Management Systems lab
ALGORITHM:
Step 4: swap the two numbers with a help of temporary variable ‘c’
c=a
a=b
b=c
Step 5: PL.SQL procedure is completed and display a and b value after swapping
CS6312 Database Management Systems lab
PROGRAM:
SQL> declare
2 a number;
3 b number;
4 c number;
5 begin
6 a:=&a;
7 b:=&b;
8 dbms_output.put_line('Swap the two values using third variables');
9 dbms_output.put_line('***********************************************');
10 dbms_output.put_line('The value of a:'||a);
11 dbms_output.put_line('The value of b:'||
b); 12 c:=a;
13 a:=b;
14 b:=c;
15 dbms_output.put_line('The value of a after swapping: '||a);
16 dbms_output.put_line('The value of b after swapping: '||b);
17 end;
18 /
CS6312 Database Management Systems lab
OUTPUT:
Enter value for a: 3
old 6: a:=&a;
new 6: a:=3;
Enter value for b: 6
old 7: b:=&b;
new 7: b:=6;
Swap the two values using third variables
**************************************************************
The value of a:3
The value of b:6
The value of a after swapping: 6
The value of b after swapping: 3
RESULT:
Thus the PL/SQL commands to swap the two numbers using third variables was executed
and verified successfully.
CS6312 Database Management Systems lab
f) FACTORIAL
AIM
To write a PL/SQL program to find a factorial value for a given number.
ALGORITHM:
Step 2: Declare all the variables assign the values for i and fact as 1.
Step 6: PL/SQL procedure is completed and display factorial value for a given number.
CS6312 Database Management Systems lab
PROGRAM:
SQL> declare
2 fact number:=1;
3 n number;
4 i number:=1;
5 r number;
6 begin
7 dbms_output.put_line('This is the Factorial program:');
8 r:=&n;
9 while i<=r
10 loop
11 fact:=fact *
i; 12 i:=i+1;
13 end loop;
14 dbms_output.put_line('The factorial value is:');
15 dbms_output.put_line(fact);
16 end;
17 /
OUTPUT:
Enter value for n: 5
old 8: r:=&n;
new 8: r:=5;
This is the Factorial program:
The factorial value is:
120
RESULT:
Thus the PL/SQL commands to find the factorial value for a given number was executed
and verified successfully.
CS6312 Database Management Systems lab
ALGORITHM:
Step 1: Set the server output on.
Step 6: PL/SQL procedure is completed and display greatest number among the
two number.
CS6312 Database Management Systems lab
PROGRAM:
SQL> declare
2 a number;
3 b number;
4 begin
5 a:=&a;
6 b:=&b;
7 dbms_output.put_line('Greatest Among Two numbers:');
8 dbms_output.put_line('**************************************');
9 dbms_output.put_line('the given number a: '||a);
10 dbms_output.put_line('the given number b: '||b);
11 if a > b
12 then
13 dbms_output.put_line(a|| ' is greater');
14 else
15 dbms_output.put_line(b|| ' is greater');
16 end if;
17 end;
18 /
CS6312 Database Management Systems lab
OUTPUT:
Enter value for a: 34
old 5: a:=&a;
new 5: a:=34;
Enter value for b: 23
old 6: b:=&b;
new 6: b:=23;
Greatest Among Two numbers:
**************************************
the given number a: 34
the given number b: 23
34 is greater
RESULT:
Thus the PL/SQL commands to display greatest number among the two numbers was
executed and verified successfully.
CS6312 Database Management Systems lab
Step 5: If the condition is false check b is greater than c then ‘b’ is greater.
Step 7: PL/SQL procedure is completed and display greatest number among the
three number
CS6312 Database Management Systems lab
PROGRAM:
SQL> declare
2 a number;
3 b number;
4 c number;
5 begin
6 a:=&a;
7 b:=&b;
8 c:=&c;
9 dbms_output.put_line('The Greatest number among the Three number is:');
10 dbms_output.put_line('********************************');
11 dbms_output.put_line('the given number a: '||a);
12 dbms_output.put_line('the given number b: '||b);
13 dbms_output.put_line('the given number c: '||c);
14 dbms_output.put_line('********************************');
15 if a>b and a>c then
16 dbms_output.put_line(a|| 'is greater');
17 else if b >c then
18 dbms_output.put_line(b|| 'is greater');
19 else
20 dbms_output.put_line(c|| 'is greater');
21 end if;
22 end if;
23 end;
24 /
CS6312 Database Management Systems lab
OUTPUT:
RESULT:
Thus the PL/SQL commands to display greatest number among the three numbers was
executed and verified successfully.
CS6312 Database Management Systems lab
ALGORITHM:
Step 5: If remainder is equal to zero then it is an odd number otherwise it is an even number.
Step 6: PL/SQL procedure is completed and display the given number is odd or even.
CS6312 Database Management Systems lab
PROGRAM:
SQL> declare
2 a number;
3 b number;
4 begin
5 dbms_output.put_line('Find a number is ODD or
EVEN'); 6 b:=&b;
7 a:=mod(b,2);
8 if a =0 then
9 dbms_output.put_line('even number');
10 else
11 dbms_output.put_line('odd number');
12 end if;
13 end;
14 /
OUTPUT:
Enter value for c: 6
old 7: b:=&b;
new 7: b:=6;
Find a number is ODD or EVEN
even number
PL/SQL procedure successfully completed.
RESULT:
Thus the PL/SQL commands to find a given number is odd or even was executed and
verified successfully.
CS6312 Database Management Systems lab
ALGORITHM:
Step 4: Perform addition with two numbers (a,b) and store result in the variable e.
Step 5: Perform subtraction with two numbers(a,b) and store result in the variable e
Step 6: Perform multiplication with two numbers (a,b) and store result in the variable e.
Step 7: Perform division with two numbers (a,b) and store result in the variable e.
PROGRAM:
SQL> declare
2 a number;
3 b number;
4 c number;
5 d number;
6 e number;
7 begin
8 dbms_output.put_line('The Arithmetic operation:');
9 a:=&c;
10 b:=&d;
11 dbms_output.put_line('The Addition result:');
12 e:=a+b;
13 dbms_output.put_line(e);
14 dbms_output.put_line('The Subtraction result is:');
15 e:=a-b;
16 dbms_output.put_line(e);
17 dbms_output.put_line('The Multiplication result is:');
18 e:=a*b;
19 dbms_output.put_line(e);
20 dbms_output.put_line('The Division result is:');
21 e:=a/b;
22 dbms_output.put_line(e);
23 end;
24 /
CS6312 Database Management Systems lab
OUTPUT:
Enter value for c: 6
old 9: a:=&c;
new 9: a:=6;
Enter value for d: 2
old 10: b:=&d;
new 10: b:=2;
The Arithmetic operation:
The Addition result:
8
The Subtraction result is:
4
The Multiplication result is:
12
The Division result is:
3
RESULT:
Thus the PL/SQL commands to perform arithmetic operation like addition, subtraction,
multiplication and division was executed and verified successfully.
CS6312 Database Management Systems lab
ALGORITHM:
Step 4: Assign that value into n and check n is greater than 0(zero),if it is do
1. n1:=mod(n,10);
2. s:=s+power(n1,3);
3. n:=floor(n/10);
Step 5: Repeat step 4 until n becomes 0(zero) or less than 0.
Step 6: If ‘s’ is equal to ‘b’ then its an amstrong number else it is not an amstrong number.
PROGRAM:
SQL> declare
2 a number;
3 b number;
4 n number;
5 n1 number;
6 s number:=0;
7 begin
8 dbms_output.put_line('The Amstrong number program');
9 dbms_output.put_line('******************************************');
10 b:=&a;
11 n:=b;
12 while n>0
13 loop
14 n1:=mod(n,10);
15 s:=s+power(n1,3);
16 n:=floor(n/10);
17 end loop;
18 if b != s
19 then
20 dbms_output.put_line('Not Amstrong number');
21 else
22 dbms_output.put_line('Amstrong number');
23 end if;
24 end;
25 /
CS6312 Database Management Systems lab
OUTPUT:
SQL> /
Enter value for a: 153
old 10: b:=&a;
new 10: b:=153;
The Amstrong number program
************************************************************
Amstrong number
RESULT:
Thus the PL/SQL commands to check a given number is amstrong number or not was
executed and verified successfully.
CS6312 Database Management Systems lab
ALGORITHM:
Step 1: Set the server output on.
Step 5: Check all subject mark is greater than 35 if it is not the display student result as fail.
Step 6: If all marks are greater than 35 then check percentage is less than 60 then display
‘Third Grade’.
Step 7: If the percentage is greater than 60 and less than 75 then display ‘Second Grade’.
PROGRAM:
SQL> declare
2 tam number;
3 eng number;
4 maths number;
5 cs number;
6 chem number;
7 physi number;
8 tot number;
9 avge number;
10 begin
11 tam:=&tam;
12 eng:=ŋ
13 cs:=&cs;
14 maths:=&maths;
15 physi:=&physi;
16 chem:=&chem;
17 tot:=tam+eng+cs+maths+ physi +chem;
18 avge:=trunc(tot/6);
19 dbms_output.put_line('Student Result');
20 dbms_output.put_line('*********************************************');
21 dbms_output.put_line('English:'||eng);
22 dbms_output.put_line('Tamil:'||tam);
23 dbms_output.put_line('Maths:'||maths);
24 dbms_output.put_line('Computer Science'||cs);
25 dbms_output.put_line('Physics:'||physi);
26 dbms_output.put_line('Chemistry:'||chem);
27 dbms_output.put_line('*********************************************');
28 dbms_output.put_line('The Percentage:'||avge);
29 if (tam<35 or eng<35 or maths<35 or chem<35 or physi<35 or cs<35) then
30 dbms_output.put_line('Fail');
31 else if (avge<=60) then
CS6312 Database Management Systems lab
OUTPUT:
Student Result
*********************************************
English:67
Tamil:89
Maths:45
Computer Science90
Physics:67
Chemistry:89
*********************************************
The Percentage:74
Second Grade
RESULT:
Thus the PL/SQL commands to display the grade of student result was executed and
verified successfully.
CS6312 Database Management Systems lab
1. c:=mod(a,10);
2. b:=(b*10)+c;
3. a:=trunc(a/10);
Step 5: Repeat step 4 until a becomes 0(zero) or less than 0.
PROGRAM:
SQL> declare
2 a number;
3 b number:=0;
4 c number;
5 begin
6 dbms_output.put_line('Reverse of the given number');
7 dbms_output.put_line('********************************************');
8 a:=&a;
9 while a>0
10 loop
11 c:=mod(a,10);
12 b:=(b*10)+c;
13 a:=trunc(a/10);
14 end loop;
15 dbms_output.put_line('The reverse number:'||b);
16 end;
17 /
OUTPUT:
Enter value for a: 78
old 8: a:=&a;
new 8: a:=78;
Reverse of the given number
********************************************
The reverse number:87
RESULT:
Thus the PL/SQL commands to display the given number in reverse order was executed
and verified successfully.
CS6312 Database Management Systems lab
AIM
To write a PL/SQL program to reverse the given number using string function.
ALGORITHM:
Step 4: Check L is greater than 0, if it is cut one character from last and store in the string
name2.
Step 5: Decrement L value by 1 and repeat step 4 to 5 until L equal to or less than zero.
PROGRAM:
SQL> declare
2 name1 varchar(20);
3 name2 varchar(20);
4 l number;
5 begin
6 name1:='&name1';
7 l:=length(name1);
8 while l>0
9 loop
10 name2:=name2||substr(name1,l,1);
11 l:=l-1;
12 end loop;
13 dbms_output.put_line('Reverse the number using string
function'); 14 dbms_output.put_line('The given nunber is: '||name1);
15 dbms_output.put_line('The reverse of a given number is: '||name2);
16 end;
17 /
OUTPUT:
Enter value for name1: 234
old 6: name1:='&name1';
new 6: name1:='234';
Reverse the number using string function
The given nunber is: 234
The reverse of a given number is: 432
PL/SQL procedure successfully completed.
RESULT:
Thus the PL/SQL commands to display the given number in reverse order using string
function was executed and verified successfully
CS6312 Database Management Systems lab
ALGORITHM:
Step 4: Inside the for loop calculate mod(a,i) and check the result is equal to
0(zero) then increment count value c by 1(e).this will continue until I is equal to a.
Step 5: If c is equal to 2 then the given number is prime number otherwise the
Step 6: PL/SQL procedure is completed and display the given number is prime or not.
CS6312 Database Management Systems lab
PROGRAM:
SQL> declare
2 a number;
3 c number:=0;
4 i number;
5 begin
6 a:=&a;
7 for i in 1..a
8 loop
9 if mod(a,i)=0
then 10 c:=c+1;
11 end if;
12 end loop;
13 if c=2 then
14 dbms_output.put_line(a||' is prime number');
15 else
16 dbms_output.put_line(a||' is not prime number');
17 end if;
18 end;
19 /
OUTPUT:
Enter value for a: 23
old 6: a:=&a;
new 6: a:=23;
23 is prime number
RESULT:
Thus the PL/SQL commands to find a given number is prime or not was executed and verified
successfully.
EX No 9 CREATIONS OF CS6312 Database Management Systems lab
PROCEDURE
AIM:
To implement a procedure program.
ALGORITHM:
Step 1: Create a table ticket with fields ticket_number, starting place, destination
place, and ticket_fare.
Step 3 : If the ticket-fare of ticket-number placed is greater than 100, then the total-
fare is multiplied by 1-2 and returned else if is multiplied by 1-6 and is returned.
SYNTAX :
CREATE [ORREPLACE] PROCEDURE PROCEDURENAME
[PARAMETER[IN/OUT/IN/IN OUT] DATATYPE
[:=/DEFAULT EXPRESSION]
[(PARAMETER)]
IS/AS
DECLARATION
BEGIN
PL/SQL CODES
[EXCEPTION]
END
CS6312 Database Management Systems lab
PROCEDURES
SQL> create table ticket (ticket_number number, starting_place varchar2(20),
destination_place varchar2(22),total_fare number);
Table created.
SQL> insert into ticket values(&ticket_number, '&starting_place', '&destination_place',
&total_fare);
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SQL> select * from ticket;
TICKET_NUMBER STARTING_PLACE DESTINATION_PLACE TOTAL_FARE
-------------------------- -------------------------- ------------------------------ -------------------
2 begin
4 if tfare>=100 then
8 where ticket_number=tno;
9 end if;
10 dbms_output.put_line('table updated');
11 end;
CS6312 Database Management Systems lab
12 /
Procedure created.
SQL> exec change(1);
VIVA QUESTIONS:
1. Define block.
2. What are the two types of sub programs in PL/SQL?
3. List the Advantages of Sub programs.
4. What is Procedure?
5. Explain about REPLACE and AUTHID.
6. Define Function.
7. Give the syntax for Function.
8. What are the Parameters in Procedure?
9. Discuss abput control structures.
RESULT:
Thus the procedure was executed successfully.
EX NO 10 a FUNCTIONS CS6312 Database Management Systems lab
IN PL/SQL
AIM:
To write PL/SQL(Functions)and to understand stored procedures in SQL.
FUNCTION:
A function is a subprogram that computes a value. The syntax for creating a
function is given Below
SYNTAX :
Create or replace function<function_name>[argument]
Return datatype is
(local declaration)
begin
(executable statements)
[Exception]
(exception handlers)
end
ALGORITHM :
Step 1: Create a table ticket with fields ticket_number, starting place, destination
place, and ticket_fare.
Step 2: create a function fun() which returns the tickets-fare of the ticket number
being passed.
PROGRAM :
SQL> create function trainfn (trainnumber number) return number is trainfunction
ittrain.tfare % type;
2 begin
4 return(trainfunction);
5 end;
6 /
Function created.
SQL> set serveroutput on;
SQL> Declare
2 total number;
3 begin
4 total:=trainfn (101);
6 end;
7 /
RESULT :
Thus the PL/SQL functions have been implemented successfully.
EX NO 10 CS6312
TRIGGERS IN Database Management Systems lab
PL/SQL
b
AIM :
To write a PL/SQL program to initiate Triggers under various conditions.
1. Create a trigger to insert a record into a table after each row is updated.
ALGORITHM :
Step 1 : Create two tables cust and order_new with attributes cid and cname.
Step 2 : Create a trigger named after _update_insert.
Step 3 : Update the cust table.
Step 4 : After each row is updated , a record must be inserted into the order_new
table.
Step 5 : End the trigger.
PROGRAM :
SQL> create or replace trigger after_update_insert
2 after
3 update
4 of cname
5 on cust
6 referencing old as o new as n
7 for each row
8 begin
9 insert into order_new values(:o.cid,:n.cname);
10 end;
11 /
OUTPUT :
Trigger created.
11
2.Create a trigger to delete a record from the table before SQL update statement is
executed.
ALGORITHM :
Step 1 : Create two tables cust and order_id.
Step 2 : Create a trigger named before_update_delete.
Step 3 : Delete a record from order_id table.
Step 4 : Update the cust table for the given condition.
Step 5 : End the trigger.
PROGRAM :
1 create or replace trigger before_update_delete
2 before
3 update on cust
4 begin
5 delete from order_new where cid=3;
CS6312 Database Management Systems lab
6 end;
OUTPUT :
Trigger created.
1 row updated.
CID CNAME
1 veena
3 siva
3. Create a trigger to delete a record from the table after a SQL update statement
is executed.
ALGORITHM:
Step 1 : Create two tables named cust and order_new.
Step 2 : Create a trigger named after_update_delete.
Step 3 : update the table cust under given condition.
Step 4 : Delete the record from the table order_new.
Step 5 : End the trigger.
PROGRAM :
1 create or replace trigger after_update_delete
2 after
3 update on cust
4 begin
5 delete from order_new where cid=3;
6 end;
OUTPUT :
Trigger created.
CS6312 Database Management Systems lab
CID CNAME
1 sita
3 mani
CID CNAME
1 sita
4. Create a trigger to delete the record from the table after each row is
updated.
ALGORITHM :
Step 1 : Create two tables cust and order_new.
Step 2 : Create a trigger named after_update_delete.
Step 3 : Update the table for the given condition.
Step 4 : After each row of updation, delete a row from the table order_new.
Step 5 : End the trigger.
PROGRAM :
1 create or replace trigger afterupdatedeleterows
2 after
3 update on cust
4 for each row
5 begin
6 delete from order_new where cname='sound';
7 dbms_output.put_line('1 row deleted');
8 end;
9 /
OUTPUT :
Trigger created.
2 rows updated.
SQL> select * from order_new;
CID CNAME
1 sita
VIVA QUESTION
1. What is the need for triggers? Or List the requirements needed to design a trigger.
2. What is trigger?
RESULT :
Thus, the triggers using PL/SQL have been successfully executed.
EX NO 11 CS6312
MINI PROJECT - MENU Database Management Systems lab
DESIGN
AIM
To design a Note Pad Application menu using Visual Basic.
PROCEDURE
STEP 1: Start
STEP 2: Create the form with essential controls and insert the menu using menu editor.
STEP 3: Write the code for doing the appropriate functions.
STEP 4: Save the forms and project.
STEP 5: Execute the form.
STEP 6: Stop
EXECUTION
Coding:
Private Sub ab_Click()
RichTextBox1.SelFontName = "Arial Black"
End Sub
End Sub
End Sub
End Sub
Output:
File Menu:
Edit Menu
Format Menu:
VIVA QUESTIONS:
1. Explain about visual basic?
2. What is the size of .NET object?
3. What is the difference between DataTable and DataSet?
4. What are the namespace available in .net?
5. What are the two main parts of the .NET Framework?
6. What is serialization in .NET?
7. What are the advantages of VB.NET?
RESULT:
Thus the program has been loaded and executed successfully.
EX NO 11.1 CS6312 Database Management Systems lab
REPORT DESIGN
AIM
To design a report design using Visual Basic.
PROCEDURE
STEP 1: Start
STEP 2: Create the form with essential controls and insert the menu using menu editor.
STEP 3: Write the code for doing the appropriate functions.
STEP 4: Save the forms and project.
STEP 5: Execute the form and generate report
STEP 6: Stop
EXECUTION
Code for progress bar:
Private Sub Form_KeyPress(KeyAscii As Integer)
Unload Me
End Sub
Private Sub Frame1_Click()
Unload Me
frmLogin.Show
End Sub
Private Sub Timer1_Timer()
On Error Resume Next
ProgressBar1.Value = ProgressBar1.Value + 1
If ProgressBar1.Value = 100 Then
login.Show
Unload Me
End If
End Sub
'MsgBox ("UPDATED")
End Sub
MsgBox ("deleted")
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
Text5.Text = ""
Text6.Text = ""
Text7.Text = ""
Text8.Text = ""
Text9.Text = ""
End Sub
End Sub
Adodc1.Recordset.MoveNext
MsgBox ("THISIS YOUR FIRST RECORD")
End If
End Sub
Dim a As String
a = InputBox("Enter Item Code")
s = "Item_code = '" + a + "'"
Adodc1.Recordset.MoveFirst
Adodc1.Recordset.Find s
If Adodc1.Recordset.EOF Then
MsgBox ("INVALID RECORD")
End If
End Sub
Private Sub cmdupadte_Click(Index As Integer)
Adodc1.Recordset.Update
MsgBox ("UPDATED")
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
Text5.Text = ""
Text6.Text = ""
Text7.Text = ""
Text8.Text = ""
Text9.Text = ""
End Sub
Private Sub commov_Click(Index As Integer)
Adodc1.Recordset.MoveFirst
End Sub
Private Sub Command1_Click()
Dim a As String
a = InputBox("Enter Item Code")
s = "Item_code = '" + a + "'"
Adodc1.Recordset.MoveFirst
Adodc1.Recordset.Find s
'Adodc1.Recordset ("select * from t1 where [ITEM_CODE] = " & Text1.Text(0) & "")
DataReport1.Show
If Adodc1.Recordset.EOF Then
MsgBox ("INVALID RECORD")
CS6312 Database Management Systems lab
End If
End Sub
Private Sub Command2_Click()
Adodc1.Recordset.Update
MsgBox ("UPDATED SUCCESSFULY")
End Sub
Private Sub Command3_Click()
Dim s As String
a = InputBox("Enter The student name")
a = Trim(a)
s = "STUDENTNAME='" & a '" "
Adodc1.Recordset.Delete
MsgBox ("deleted")
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
Text5.Text = ""
Text6.Text = ""
Text7.Text = ""
Text8.Text = ""
Text9.Text = ""
End Sub
Private Sub Command5_Click()
DataReport1.Show
End Sub
Private Sub EXIT_Click()
End
End Sub
Private Sub Image2_Click()
'Adodc1.Recordset (" * from t1 where [ITEM_CODE] = " & Text1.Text(0) & "")
DataReport1.Show
End Sub
Private Sub MSHFlexGrid1_Click()
'Adodc2.Refresh
End Sub
Private Sub VIEW_Click()
DataReport1.Show
End Sub
CS6312 Database Management Systems lab
Output:
Progress Bar
Login
CS6312 Database Management Systems lab
Stock Form:
Report Design:
RESULT:
Thus the program has been loaded and executed successfully.
CS6312 Database Management Systems lab
VIVA QUESTIONS:
1. How many .NET languages can a single .NET DLL contain?
2. What are the different types of applications supported in .NET (or) .NET Framework?
3. What is meant by .NET framework?
4. How many .NET languages can a single .NET DLL contain?
5. Which is the root namespace for fundamental types in .NET Framework?
6. Which method do you use to enforce garbage collection in .NET?
7. What are the namespace available in .net?
8. What are the two main parts of the .NET Framework?
9. What are the benefits of.NET Framework?
10. What are the advantages of VB.NET?
APPLICATIONS:
Airlines and railways: Airlines and railways use online databases for reservation, and for
displaying the schedule information.
Banking: Banks use databases for customer inquiry, accounts, loans, and other transactions.
Education: Schools and colleges use databases for course registration, result, and other
information.
Telecommunications: Telecommunication departments use databases to store information
about the communication network, telephone numbers, record of calls, for generating monthly
bills, etc.
Credit card transactions: Databases are used for keeping track of purchases on credit cards in
order to generate monthly statements.
E-commerce: Integration of heterogeneous information sources (for example, catalogs) for
business activity such as online shopping, booking of holiday package, consulting a doctor, etc.
Health care information systems and electronic patient record: Databases are used for
maintaining the patient health care details.
Digital libraries and digital publishing: Databases are used for management and delivery of
large bodies of textual and multimedia data.
Finance: Databases are used for storing information such as sales, purchases of stocks and
bonds or data useful for online trading.
Sales: Databases are used to store product, customer and transaction details.
Human resources: Organizations use databases for storing information about their employees,
salaries, benefits, taxes, and for generating salary checks.