0% found this document useful (0 votes)
18 views35 pages

23itc04 DBMS Laboratory

DBMS Laboratory
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views35 pages

23itc04 DBMS Laboratory

DBMS Laboratory
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

1

Institution Vision & Mission


Institution Vision
 To be a Centre of Excellence in Engineering, Technology and Management on par with
International Standards.
Institution Mission
 To prepare the students with high professional skills and ethical values.
 To impart knowledge through best practices.
 To instill a spirit of innovation through Training, Research and Development.
 To undertake continuous assessment and remedial measures.
 To achieve academic excellence through intellectual, emotional and social stimulation.

Department Vision & Mission


Department Vision
 To produce competent Information Technology professionals capable of delivering
innovative solutions to challenges in IT domain
Department Mission
 To impart knowledge in the state of art technologies in Information Technology
 To inculcate the analytical and logical skills in the field of Information Technology

 To prepare the graduates with ethical and moral values

Program Educational Objectives


PEO1 : Graduates will be able to practice as Information Technology professionals in
Multinational companies
PEO2 : Graduates will be able to adapt to the changes in the emerging technologies
PEO3 : Graduates will be able to excel as socially committed engineers

Program Specific Outcomes


PSO1 : Graduates will be able to practice as Information Technology professionals in
Multinational companies
PSO2 : Graduates will be able to adapt to the changes in the emerging technologies
PSO3 : Graduates will be able to excel as socially committed engineers

23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM


2

Program Outcomes
PO1 : Engineering Knowledge: Apply knowledge of mathematics, natural science,
computing, engineering fundamentals and an engineering specialization as specified
in WK1 to WK4 respectively to develop to the solution of complex engineering
problems.
PO2 : Problem Analysis: Identify, formulate, review research literature and analyse
complex engineering problems reaching substantiated conclusions with
consideration for sustainable development. (WK1 to WK4).
PO3 : Design/Development of solutions: Design creative solutions for complex
engineering problems and design/develop systems/components/processes to meet
identified needs with consideration for the public health and safety, whole-life cost,
net zero carbon, culture, society and environment as required. (WK5).
PO4 : Conduct investigations of complex problems: Conduct investigations of complex
engineering problems using research-based knowledge including design of
experiments, modelling, analysis & interpretation of data to provide valid
conclusions. (WK8).
PO5 : Engineering Tool Usage: Create, select and apply appropriate techniques, resources
and modern engineering & IT tools, including prediction and modelling recognizing
their limitations to solve complex engineering problems. (WK2 and WK6).
PO6 : The Engineer and The World: Analyze and evaluate societal and environmental
aspects while solving complex engineering problems for its impact on sustainability
with reference to economy, health, safety, legal framework, culture and environment.
(WK1, WK5, and WK7).
PO7 : Ethics: Apply ethical principles and commit to professional ethics, human values,
diversity and inclusion; adhere to national & international laws. (WK9).
PO8 : Individual and Collaborative Team Work: Function effectively as an individual,
and as a member or leader in diverse/multi-disciplinary teams.
PO9 : Communication: Communicate effectively and inclusively within the engineering
community and society at large, such as being able to comprehend and write
effective reports and design documentation, make effective presentations
considering cultural, language, and learning differences.
PO10 : Project Management and Finance: Apply knowledge and understanding of
engineering management principles and economic decision-making and apply these
to one’s own work, as a member and leader in a team, and to manage projects and in
multidisciplinary environments.
PO11 : Life-long Learning: Recognize the need for, and have the preparation and ability for i)

23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM


3

independent and life-long learning ii) adaptability to new and emerging technologies and iii)
critical thinking in the broadest context of technological change. (WK8).

23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM


4

LIST OF EXPERIMENTS

1 Data Definition Language commands in RDBMS

Data manipulation Language and Data control Language commands in


2 RDBMS

3 Apply Integrity constraints and Domain constraints for a Database

4 Creation of views, Nested Queries and Join Queries

5 Study of PL/SQL blocks

6 High level programming language extensions(Control structuresand


Procedures)

7 Implementation of Functions

8 Implementation of Triggers

10 Design and Implementation of Banking System

11 Design and Implementation of payroll Processing System

23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM


5

INDEX

Page
[Link] Date Name of the Experiments Marks Signature
No
1 Implementation of Data Definition Language
commands in RDBMS
Implementation of Data manipulation Language
2 and Data control Language commands in
RDBMS
3 Apply Integrity constraints and Domain
constraints for a Database
4 Creation of views, Nested Queries and Join
Queries
5 Study of PL/SQL blocks
6 High level programming language
extensions(Control structures and Procedures)
7 Implementation of Functions
8 Implementation of Triggers
9

10 Design and Implementation of Banking System

11 Design and Implementation of payroll


Processing System

23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM


6

23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM


7

Ex. No : 1 IMPLEMENTATION OF DATA DEFINITION LANGUAGE


Date : COMMANDS IN RDBMS

AIM:

To execute and verify the Data Definition Language commands.

OBJECTIVES

To understand DDL commands.

THEORY

The commands used are:

 CREATE - It is used to create a table.


 ALTER – The structure of a table can be modified by using the ALTER TABLE
command. This command is used to add a new column, modify the existing column
definition and to include or drop integrity constraint.
 DROP - It will delete the table structure provided the table should be empty.
 TRUNCATE - If there is no further use of records stored in a table and
the structure has to be retained, and then the records alone can be
deleted.
 DESC - This is used to view the structure of the table
.
PROCEDURE
CREATION OF TABLE:
SYNTAX:
CREATE TABLE table_name(
Column1 datatype,
Column2 datatype,
Column3 datatype,
……
);
Here,
 table_name is name of the table you want to create
 column is the name of a column in the table
 datatype is the type of data that the column can hold (e.g., integer, varchar, date)

23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM


8

-- create a table Students with different columns


CREATE TABLE Students(
id int,
name varchar(50),
address text,
grades varchar(50),
phone varchar(10)
);

Here, we created a table named Students with five columns.


The table we created will not contain any data as we have not inserted anything into the
table

Here, int, varchar(50), and text specify types of data that could be stored in the respective
columns.
CREATE TABLE IF NOT EXISTS
If we try to create a table that already exists, we get an error message ‘Error: table already
exist’.
To fix this issue, we can add the optional IF NOT EXISTS command while creating a table.
Example:

-- create a Companies table if it does not exist


CREATE TABLE IF NOT EXISTS Companies (
id int,
name varchar(50),
address text,
email varchar(50),
phone varchar(10)
);
Here, the SQL command checks if a table name Companies exists, and if not, it creates a
table with specified columns.

23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM


9

Create Table Using Another Existing Table


In SQL, we can create a new table by duplicating an existing table's structure.
Example.

-- create a backup table from the existing table Customers


CREATE TABLE CustomersBackup
AS
SELECT *
FROM Customers;

This SQL command creates the new table named CustomersBackup, duplicating the structure of the
Customers table.

SQL DROP DATABASE Statement


In SQL,DROP DATABASE is used to delete a database from our Database Management System.
Example

DROP DATABASE my_database;

Here, the SQL command will delete a database named my_database.


Also, you need admin or DROP permission to run this command.

DROP DATABASE Syntax


The syntax of the SQL DROP DATABASE statement is:

DROP DATABASE database_name;

Here,database_name is the name of the database to be removed.

Note: When we delete a database, all tables and records within a database are also deleted.

RESULT:

The DDL commands have been executed successfully


23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM
10

Ex. No : 2
IMPLEMENTATION OF DML AND DCL COMMANDS IN RDBMS
Date :

AIM:

To execute the Data Manipulation Language (DML) commands and DCL statements in RDBMS.

OBJECTIVES

To understand Data Manipulation Language (DML) commands.

THEORY

The commands used are:

 DML commands are the most frequently used SQL commands and is used to query and
manipulate the existing database objects. Some of the commands are
 INSERT
 This is used to add one or more rows to a table. The values are separated by commas and
the data types char and date are enclosed in apostrophes. The values must be entered in the
same order as theyare defined.
 SELECT
 It is used to retrieve information from the [Link] is generally referred to as querying the
table. We can either display all columns in a table or only specify column from the table.
 UPDATE
 It is used to alter the column values in a table. A single column may be updated or more
than one column could be updated.
 DELETE
 After inserting row in a table we can also delete them if required. The delete command
consists of a from clause followed by an optional where clause
.
PROCEDURE
INSERT COMMAND
(a)Inserting a single row into a table:
Syntax:
insert into <table name> values (<expression1>,<expression2>)
Example:
SQL>INSERT INTO EMPLOYEE VALUES(101,'MANU','LECTURER',15000);
23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM
11

(b)Inserting more than one record using a single insert commands:


Syntax:
insert into <table name> values (&col1, &col2, ….)
Example:
SQL> INSERT INTO EMPLOYEE
VALUES(&EMPNO,'&ENAME','&DESIGNATIN'&SALARY');
(c) Skipping the fields while inserting:
Insert into <tablename>(<column name1>,<column name3>)>values
(<expression1>,<expression3>);
Other way is to give null while passing the values
Example :
INSERT INTO EMPLOYEE VALUES(101,'MANU','LECTURER',150); INSERT INTO
EMPLOYEE VALUES(102,'RAMU','STAFF',100); INSERT INTO EMPLOYEE
VALUES(103,'SENU','AP',200);
INSERT INTO EMPLOYEE VALUES(102,'ANNU','PROF',500);

SELECT COMMAND
(a).View all rows and all columns
Syntax:
Select * from tablename;
Example:
Select * from Employee;
(a)Selected Columns And All Rows Syntax: Select<column1>,<column2>from tablename;
(b)Selected Columns And selected Rows
Syntax:
SELECT<column1>, <column2> FROM <tablename> WHERE <condition> ;
Example:
Select empno, ename from Employee where job=’LECTURER’;

23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM


12

(c) Eliminating duplicate rows


Syntax:
SELECT DISTINCT <column1>, <column2> FROM <tablename>
Example:
Select distinct empno from Employee;
UPDATE COMMAND
(a) updating all rows
Syntax:
update tablename set columnname1>=<exprssion1>,<columnname2>=<exprssion2>;
Example:
Update Employee set job = ‘PROF’;
(b) updating records conditionally
Syntax:
update tablename set field=values where condition;
Example:
Update Employee set salary= 800 where empno=103;

DELETE COMMAND
(a) removal of specific rows
Syntax:
Delete from <table name> where <condition>;
Example:
delete from Employee where empno=101;
(b) Removal of all rows
Syntax:
Delete from <table name>;
Example:

23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM


13

Delete from Employee;

OBJECTIVES
To understand DCL commands
THEORY:
Data Control Language (DCL) consists of various commands which are related to data sharing
and security of data in database.
They are GRANT REVOKE
Granting Privileges:
Objects that are created by a user are owned and controlled by that user. If user wishes to access
any of the objects belonging to another user, the owner of the object will have to give permissions
for such access. This is called Granting of Privileges.
Granting privileges using the GRANT statements:
The GRANT statements provide various types of access to database objects such as tables, views.
Syntax:
GRANT {object privileges} ON object name

TO username; Object Privileges: each object privilege that is granted authorizes the grantee to
perform some operation on the object. The user can grant all the privileges or grant only
specific object privileges. The list of object privileges is as follows:

• ALTER: allows the grantee to change the table definitions with the ALTER table command.

• DELETE: allows the grantee to remove the records from the table with the DELETE
command.

• INDEX: allows the grantee to create an index on the table with the CREATE INDEX
command.

23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM


14

• INSERT: allows the grantee to add records to the table with the INSERT command.

• SELECT: allows the grantee to query the table with SELECT command.

• UPDATE: allows the grantee to modify the records in the table with the UPDATE
command.

Revoking privileges given:

Privileges once given can be denied to a user using the REVOKE command. The object
owner can revoke privileges granted to another user. A user of an object who is not owner,
but has been granted the GRANT privilege, has the power to REVOKE the privileges from
the grantee.

Revoking permission using the REVOKE statement:

The REVOKE statement is used to deny the grant given on an object.

Syntax:

REVOKE {object privileges} ON object name

FROM username;

The REVOKE command is used to revoke object privileges that the user previously granted
to the Revoke.

The REVOKE command cannot be used to revoke the privileges granted through operating
system.

23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM


15

RESULT:
The DML commands are executed successfully and Familiarized DCL statements.

Ex. No : 3 APPLY INTEGRITY CONSTRAINTS AND DOMAIN CONSTRAINTS


Date : FOR A DATABASE

AIM:
To implement Domain Constraints and Integrity Constraints .

THEORY:
Constraints are the Rules which are enforced on the data being stored in a table Types of Data
Constraints

1. Integrity Constraint
Integrity Constraints are the protocols that a table's data columns must follow. It is divided into two
different types
 The Primary Key Constraint
 The Foreign Key Constraint

2. Domain rule Constraint


This type of constraint is applied to data prior the data being inserted into table [Link] are
 CHECK Constraint
 UNIQUE Constraint
 NOT NULL constraint
 DEFAULT Constraint

Oracle allows programmer to define constraints at


 Column level
 Table level

PROCEDURES

Creation of the PRIMARY KEY defined at column level

Syntax:
CREATE TABLE tablename
(Columnname1 DATATYPE CONSTRAINT <constraintname1> PRIMARY KEY, Columnname2
DATATYPE, columnname3 DATATYPE, ..... );
Example :
CREATE TABLE Employee (
EmployeeID INT CONSTRAINT PK_sample PRIMARY KEY, FirstName VARCHAR(50),
23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM
16

LastName VARCHAR(50), BirthDate DATE, DepartmentID INT);

The PRIMARY KEY defined at table level

Syntax:
CREATE TABLE tablename
(Columnname1 DATATYPE, columnname2 DATATYPE, columnname3 DATATYPE, PRIMARY KEY
(columnname1, columnname2));
Example:
CREATE TABLE example_table ( employee_id INT, department_id INT,employee_nameVARCHAR(50),
PRIMARY KEY (employee_id, department_id)
);

The FOREIGN KEY defined at column level

Syntax:
CREATE TABLE tablename (
Columnname1 DATATYPE REFERENCES referenced_table(columnname) ON DELETE CASCADE,
columnname2 DATATYPE, columnname3 DATATYPE
);
Example :
CREATE TABLE products ( product_id INT PRIMARY KEY, product_name VARCHAR(50), price
DECIMAL(10, 2)
);
CREATE TABLE orders ( order_id INT PRIMARY KEY, product_id INT,
quantity INT, order_date DATE,
FOREIGN KEY (product_id) REFERENCES products(product_id) ON DELETE CASCADE
);

The table in which FOREIGN KEY is defined is called FOREIGN TABLE or DETAIL TABLE.
The table in which PRIMARY KEY is defined and referenced by FOREIGN KEY is called PRIMARY
TABLE or MASTER TABLE.

ON DELETE CASCADE is set then DELETE operation in master table will trigger the DELETE
operation for corresponding records in the detail table.

The FOREIGN KEY defined at table level


Syntax:
CREATE TABLE tablename ( Columnname1 DATATYPE, columnname2 DATATYPE, columnname3
DATATYPE,
PRIMARY KEY (Columnname1, columnname2),
FOREIGN KEY (columnname2) REFERENCES tablename2(columnname2)
);

A CONSTRAINT can be given User Defined Name, the syntax is: CONSTRAINT < constraint
name><constraint definition>
Example code :
CREATE TABLE tablename2 ( columnname2 INT PRIMARY KEY, data_column VARCHAR(50)
);
CREATE TABLE tablename ( Columnname1 INT, columnname2 INT, columnname3 VARCHAR(50),
23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM
17

PRIMARY KEY (Columnname1, columnname2),


FOREIGN KEY (columnname2) REFERENCES tablename2(columnname2)
);

The CHECK Constraint defined at column level


CREATE TABLE tablename ( Columnname1 DATATYPE, columnname2 DATATYPE, columnname3
DATATYPE, CHECK (Condition)
);
Example :
CREATE TABLE samtable ( id INT CHECK (id > 0), name VARCHAR(50),
dob DATE
);

The CHECK Constraint defined at table level


CREATE TABLE examtable ( Columnname1 INT, columnname2 VARCHAR(50), columnname3 DATE,
CHECK (Columnname1 > 0), CHECK (columnname2 > 0)
);

The UNIQUE Constraint defined at the column level


CREATE TABLE example_table ( Columnname1 INT UNIQUE, columnname2 VARCHAR(50)
UNIQUE, columnname3 DATE
);

The UNIQUE Constraint defined at the the table level


CREATE TABLE tablename ( Columnname1 DATATYPE, columnname2 DATATYPE, columnname3
DATATYPE, UNIQUE (Columnname1)
);
Example :
CREATE TABLE example_table ( employee_id INT, employee_name VARCHAR(50), department_id
INT,
UNIQUE (employee_id)
);

NOT NULL constraint


CREATE TABLE tablename ( Columnname1 DATATYPE NOT NULL, columnname2 DATATYPE
NOT NULL, columnname3 DATATYPE
);
Example :
CREATE TABLE employees ( employee_id INT NOT NULL,
employee_name VARCHAR(50) NOT NULL, hire_date DATE);

Note: The NOT NULL constraint can only be applied at column level.
DEFAULT Constraint
CREATE TABLE tablename (
Columnname1 DATATYPE DEFAULT (logical expression), columnname2 DATATYPE,
columnname3 DATATYPE,
);

23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM


18

Example :
CREATE TABLE estable ( id INT DEFAULT 1,
name VARCHAR(50) DEFAULT 'John Doe',
salary DECIMAL(10, 2)
);

RESULT:
Thus, Domain Constraints and Integrity Constraints were executed successfully.

Ex. No : 4
VIEWS, NESTED QUERIES AND JOIN QUERIES
Date :

AIM :
To implement views, nested queries and join queries.

THEORY:
SQL View

A view in SQL is a logical subset of data from one or more tables. View is used to restrict data
access.

CREATE or REPLACE view view_name AS SELECT column_name(s) FROM table_name


WHERE condition ;
Syntax for creating a View
Example code :

CREATE or REPLACE view sample AS SELECT empNo,Ename FROM Employee;

Syntax for Displaying a View

Syntax of displaying a view is similar to fetching data from table using Select statement.
Syntax:
SELECT * from view_name;

Types of View
There are two types of view,
 Simple View
 Complex View

Simple View Complex View


Created from one table Created from one or more table
23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM
19

Does not contain functions Contain functions


Does not contain groups of data Contains groups of data

CREATE A VIEW WITH SELECTED FIELDS:


SYNTAX:

SQL>CREATE [OR REPLACE] VIEW <VIEW NAME>AS SELECT


<COLUMN NAME1>…..FROM <TABLE NAME>;

Example :

CREATE or REPLACE view sample AS SELECT empNo,Ename FROM Employee;

INSERT STATEMENT SYNTAX:

SQL> INSERT INTO <VIEW_NAME> (COLUMN NAME1, …) VALUES(VALUE1,….);

Example :
Insert into sam (empno,ename) values(110,'mec');
DELETE STATEMENT SYNTAX:
SQL> DELETE <VIEW_NMAE>WHERE <COLUMN NMAE> =’VALUE’;

Example :

DELETE sam WHERE ename ='mec';

UPDATE STATEMENT:
A view can be updated under certain conditions:
The SELECT clause may not contain the keyword
DISTINCT. The SELECT clause may not contain summary
functions.
The SELECT clause may not contain set functions.
The SELECT clause may not contain set operators.
The SELECT clause may not contain an ORDER BY
clause. The FROM clause may not contain multiple
tables. The WHERE clause may not contain subqueries.
The query may not contain GROUP BY or
HAVING. Calculated columns may not be
updated.
All NOT NULL columns from the base table must be included in the view in
order for the INSERT queryto function.

UPDATE STATEMENT SYNTAX:


23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM
20

SQL>UPDATE <VIEW_NAME> SET< COLUMN NAME> = <COLUMN NAME>


+<VIEW>WHERE <COLUMN NAME>=VALUE;

DROP A VIEW:
Obviously, where you have a view, you need a wayto drop the view if it is no longer needed.
SYNTAX:
SQL> DROP VIEW <VIEW_NAME>

Example :

drop view sam;

SOLUTION:
CREATE A VIEW WITH SELECTED FIELDS:
CREATE TABLE Employee (EmpNO number(10),Ename Varchar(15),Job char(10),Deptno number(10));
INSERT INTO EMPLOYEE VALUES(101,'MANU','LECTURER',15000);
CREATE or REPLACE view sample AS SELECT empno,Ename FROM Employee; select * from sample;

UPDATE STATEMENT:
CREATE or REPLACE force view sam AS SELECT empNO,Ename FROM Employee; UPDATE sam set
empno = 105 WHERE ename = 'MANU';
select * from sam; select * from employee;

NESTED QUERIES

A nested query is a query that appears inside another query, and it helps retrieve data from multiple tables or
apply conditions based on the results of another query.
Q1: Display all employee names and salary whose salary is greater than minimum salary of the company and
job title starts with A.
1. Use select from clause.
2. Use like operator to match job and in select clause to get the result. Ans: SQL>
CREATE TABLE employees ( employee_id INT PRIMARY KEY, employee_name VARCHAR(255), salary
DECIMAL(10, 2),
job_title VARCHAR(100)
);

select * from employees;


SELECT employee_name, salary FROM employees
WHERE salary > (SELECT MIN(salary) FROM employees) AND job_title LIKE 'A%';

Q2: Issue a query to find all the employees who work in the same job as John Doe:
SQL>
SELECT * FROM employees

WHERE job_title = (SELECT job_title FROM employees WHERE employee_name = 'John Doe');
23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM
21

JOIN QUERIES:

A JOIN clause is used to combine rows from two or more tables, based on a related column between
them.
SYNTAX:

SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;

Example:

CREATE TABLE customers ( customer_id INT PRIMARY KEY, name VARCHAR(255)


NOT NULL,email VARCHAR(255) UNIQUE NOT NULL );
CREATE TABLE orders ( order_id INT PRIMARY KEY, customer_id INT NOT NULL, order_date
DATE NOT NULL, order_total DECIMAL(10,2) NOT NULL, FOREIGN KEY (customer_id)
REFERENCES customers(customer_id) );
SELECT [Link], [Link], orders.order_id, orders.order_date FROM customers
INNER JOIN orders ON customers.customer_id = orders.customer_id;

23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM


22

Result:

Thus views, nested queries and join queries were implemented Successfully.

Ex. No : 5
STUDY OF PL/SQL BLOCK
Date :

AIM :
To study PL/SQL Block.

THEORY:

PLSQL stands for "Procedural Language extensions to SQL", and can be used in Oracle
databases. PLSQL is closely integrated into the SQL language, yet it adds programming
constructs that are not native to SQL.

Advantages of PL/SQL
1. PL/SQL supports not only SQL data manipulation but also provides facilities of
conditional checking, branching and looping.
2. PL/SQL sends an entire block of statements to the Oracle engine at one time.
3. PL/SQL permits dealing with errors and displaying user friendly messages when the
error occurs.
4. Via PL/SQL all sorts of calculations can be done quickly without the use of
Oracle Engine
5. Applications written in PL/SQL are portable to any computer hardware and
operating system where Oracle is operational.
The different sections of PL/SQL block are as follows:
DECLARE SECTION
Declarations of memory variables, constants, cursors etc in PL/SQL

BEGIN
SQL executable statements PL/SQL
executable statements

EXCEPTION
SQL or PL/SQL code to handle errors that may arise during the execution of the code
blockStudyof PL/SQL block
23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM
23

In addition to SQL commands, PL/SQL can also process data using flow of statements.
The flow of control statements are classified into the following categories.
• Conditional control -Branching
• Iterative control - looping
• Sequential control

BRANCHING in PL/SQL:
Sequence of statements can be executed on satisfying certain
condition . If statements are being used and different forms of if are:
[Link]
IF
[Link]
3. ELSE IF
SELECTION IN PL/SQL(Sequential Controls)
SIMPLE CASE
Syntax:
CASE SELECTOR
WHEN Expr1 THEN statement1; WHEN Expr2 THEN statement2; ELSE
Statement n;
END CASE;

EXAMPLE :
DECLARE
day_of_week VARCHAR2(10) := 'Monday'; statement VARCHAR2(50);
BEGIN
CASE day_of_week WHEN 'Monday' THEN
statement := 'It''s the start of the week.';
WHEN 'Wednesday' THEN
statement := 'Halfway through the week!';
WHEN 'Friday' THEN
statement := 'TGIF! It''s Friday!'; ELSE
statement := 'It''s a regular day.'; END CASE;
DBMS_OUTPUT.PUT_LINE(statement); END;

ITERATIONS IN PL/SQL
Sequence of statements can be executed any number of times using loop construct. It is broadly
classified into:
• Simple Loop
• For Loop
• While Loop
SIMPLE LOOP
Syntax:
LOOP
statement1;
EXIT [ WHEN Condition]; END LOOP;

23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM


24

EXAMPLE :
DECLARE
counter NUMBER := 1; BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE('Iteration ' || counter); counter := counter + 1;
EXIT WHEN counter > 5; END LOOP;
END;

WHILE LOOP
Syntax
WHILE condition LOOP statement1;
statement2; END LOOP; EXAMPLE :
DECLARE
counter NUMBER := 1; BEGIN
WHILE counter <= 5 LOOP DBMS_OUTPUT.PUT_LINE('Iteration ' || counter); counter :=
counter + 1;
END LOOP; END;

FOR LOOP
Syntax:
FOR counter IN [REVERSE] LowerBound..UpperBound LOOP
statement1; statement2; END LOOP; EXAMPLE :
DECLARE
loop_counter NUMBER; BEGIN
FOR loop_counter IN 1..5 LOOP
DBMS_OUTPUT.PUT_LINE('Number: ' || loop_counter); END LOOP;
END;

23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM


25

Result:

PL/SQL blocks were implemented Successfully.

Ex. No : 6 HIGH LEVEL PROGRAMMING LANGUAGE


Date : EXTENSIONS(CONTROL STRUCTURES AND PROCEDURES)

AIM:
To Implement Procedures
THEORY:
Procedure is a subprogram used to perform a specific action. A subprogram is a named
block of PL/SQL. There are two types of subprograms in PL/SQL namely Procedures and
Functions. Every subprogram will have a declarative part, an executable part or body, and an
exception handling part, which is optional. Declarative part contains variable declarations.
Body of a subprogram contains executable statements of SQL and PL/SQL. Statements to
handle exceptions are written in exception part.
Procedure specification begins with CREATE and ends with procedure name or parameters
list. Procedures that do not take parameters are written without a parenthesis. The body of the
procedure starts after the keyword IS or AS and ends with keyword END.
Syntax for Procedure:
CREATE [OR REPLACE] PROCEDURE procedure_name [(parameter_name [IN | OUT | IN
OUT] type [, ...])] {IS | AS} BEGIN
procedure_body EXCEPTION
Exception handling END procedure_name;
Procedure is created using CREATE PROCEDURE statement.
OR REPLACE specifies the procedure is to replace an existing procedure if present. One can
use this option to modify an existing procedure.
A procedure may be passed multiple parameters. IN | OUT | IN OUT specifies the mode of the
parameter. Type specifies the datatype of the parameter.
IN - The parameter can be referenced by the procedure or function. The value of the parameter
cannot be overwritten by the procedure or function.
23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM
26

OUT - The parameter cannot be referenced by the procedure or function, but the value of the
parameter can be overwritten by the procedure or function.
IN OUT - The parameter can be referenced by the procedure or function and the value of the
parameter can be overwritten by the procedure or function.
Procedure body contains the SQL and PL/SQL statements to perform the procedure's task.
Exception Section:
The Exception section of a PL/SQL Block starts with the reserved keyword EXCPTION. This
section is optional. Any errors in the program can be handled in this section, so that the
PL/SQL Blocks terminates gracefully. If the PL/SQL Block contains exceptions that cannot be
handled, the Block terminates abruptly with errors.

Advantages:
When client executes a procedure or a function, the processing is done in the server. Server is
likely to me more powerful than the clients which in turn mean that stored procedures should
run faster. This reduces network traffic.
As the procedures/functions are stored in the Oracle database there is no need to transfer the
code from the clients to the database server or to transfer intermediate results from the server to
the clients. This results in much less network traffic and again improves scalability
The subprograms are compiled and stored in the Oracle database as stored programs and can be
invoked whenever required. As they are stored in compiled form when called, they only need
to be executed. Hence they save time needed for compilation. They allow breaking the
program into manageable modules. They provide reusability and maintainability for the code.
Disadvantages:
There is an overhead involved in embedding or calling PL/SQL procedures from SQL in
Oracle due to the context switching that the Oracle database has to perform. This may be
significant in terms of performance but usually this overhead is outweighed by performance
advantages of using PL/SQL.
More memory may be required on the Oracle database server when using Oracle PL/SQL
packages as the whole package is loaded into memory as soon as any object in the package is
accessed
PROCEDURE TO INSERT NUMBER
SQL> create table emp1(id number(3),First_name varchar2(20)); Table created.
SQL> insert into emp1 values(101,'Nithya'); 1 row created.
SQL> insert into emp1 values(102,'Maya'); 1 row created.
SQL> select * from emp1;
ID FIRST_NAME
------------------------
101 Nithya

23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM


27

102 Maya

SQL> set serveroutput on;


SQL> CREATE OR REPLACE PROCEDURE insert_num(p_num NUMBER) IS BEGIN
INSERT INTO emp1 (id, First_name) VALUES (p_num, USER);
END insert_num; Output:
Procedure created.
SQL> exec insert_num(3);

PL/SQL procedure successfully completed.

Result:
High level programming language extensions such as Control structures and Procedures were implemented
Successfully.

Ex. No : 7
IMPLEMENTATION OF FUNCTIONS
Date :

AIM :
To Implement Function
THEORY :
A function is a named PL/SQL Block which is similar to a procedure. The major difference between a
procedure and a function is, a function must always return a value, but a procedure may or may not return a
value.
Syntax for Function:
CREATE OR REPLACE FUNCTION function_name ( parameter1 datatype1,
parameter2 datatype2,
-- add more parameters as needed
) RETURN return_datatype IS
-- Declaration section variable1 datatype1; variable2 datatype2;
-- add more variables as needed
BEGIN
-- Execution section
-- Your logic here
-- Set values to variables, perform calculations, etc.
-- Return statement RETURN return_variable;
EXCEPTION
-- Exception section
RETURN default_value; END function_name;
Return Type: The header section defines the return type of the function. The return datatype can be any of
the oracle datatype like varchar, number etc.
The execution and exception section both should return a value which is of the datatype defined in the
header section.

SQL> CREATE OR REPLACE FUNCTION fact(n NUMBER) RETURN NUMBER IS


i NUMBER(10); f NUMBER := 1; BEGIN
FOR i IN 1..n LOOP
23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM
28

f := f * i; END LOOP; RETURN f;


END fact;
/
Function created.
SQL> select fact(4) from dual; FACT(4)
24

Result
Thus the functions were implemented successfully.

Ex. No : 8
IMPLEMENTATION OF TRIGGERES
Date :

Aim :
To implement of triggers

TRIGGER FOR DISPLAYING GRADE OF THE STUDENT


SQL> CREATE TABLE stdn (
rollno NUMBER(3), name VARCHAR2(50), m1 NUMBER(3),
m2 NUMBER(3), m3 NUMBER(3), tot NUMBER(4),
avrg NUMBER(4, 1),
result VARCHAR2(10)
);

SQL> CREATE OR REPLACE TRIGGER t1 BEFORE INSERT ON stdn


FOR EACH ROW BEGIN
:[Link] := :new.m1 + :new.m2 + :new.m3;
:[Link] := :[Link] / 3;
IF (:new.m1 >= 50 AND :new.m2 >= 50 AND :new.m3 >= 50) THEN
:[Link] := 'pass'; ELSE
:[Link] := 'Fail'; END IF;
END;
/

SQL> insert into stdn values(101,'SM',67,89,99,'','',''); 1 row created.


SQL> select * from stdn;
ROLLNO NA M1 M2 M3 TOT AVRG RESULT
101 SM 67 89 99 255 85 pass
23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM
29

PROGRAM TO INDICATE INVALID CONDITION USING TRIGGER


SQL> create table emp (name varchar(10),empno number(3),age number(3)); Table created.
SQL>
CREATE OR REPLACE TRIGGER t2 BEFORE INSERT ON emp
FOR EACH ROW
WHEN ([Link] > 100) BEGIN
RAISE_APPLICATION_ERROR(-20998, 'INVALID ERROR'); END;
/
Trigger created.
SQL> insert into emp values('nithya',101,24); 1 row created.
SQL> insert into emp values('nithya',101,103);
ERROR at line 1:
ORA-20998: INVALID ERROR ORA-06512: at "SCOTT.T2", line 2
ORA-04088: error during execution of trigger 'SCOTT.T2'

RESULT:
Thus the triggers were implemented successfully.

Ex. No : 9
DESIGN AND IMPLEMENTATION OF BANKING SYSTEM
Date :

AIM:
To design and implement banking System
STEPS:
1. Create the DB for banking system source request the using SQL
[Link] ODBC connection
3. Click add button and select oracle in ORA home 90 click finished
[Link] will appear give the data source name as oracle and give the user id as scott
5. Now click the test connection a window will appear with server and user name give user as scott and
password tiger Click ok.
[Link] Basic Application:-
Create Standard exe project in to and design ms from in request format.
To add ADODC Project Select Component and check ms ADO data control click ok.
Now the Control is added in the tool book.
Create Standard exe project in to.

[Link] CONTEOL FOR ACCOUNT FROM:- Click customs and property window and window will
appear and select ODBC data source name as oracle and click apply as the some window
CREATE A TABLE IN ORACLE
SQL>create table account(cname varchar(20),accno number(10),balance number);
Table Created
SQL> insert into account values('&cname',&accno,&balance);
Enter value for cname: Mathi
Enter value for accno: 1234 Enter value for balance: 10000
old 1: insert into account values('&cname',&accno,&balance)
new 1: insert into emp values('Mathi',1234,10000) 1 row created.
SOURCE CODE FOR FORM1
23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM
30

Private Sub ACCOUNT_Click() [Link]


End Sub
Private Sub EXIT_Click() Unload Me
End Sub Private Sub

TRANSACTION_Click()
[Link] End Sub
SOURCE CODE FOR FORM 2
Private Sub CLEAR_Click() [Link] = ""
[Link] = "" [Link] = "" End Sub
Private Sub DELETE_Click()
[Link] MsgBox "record deleted" [Link] If
[Link] = True Then [Link]
End If End Sub
Private Sub EXIT_Click() Unload Me
End Sub
Private Sub HOME_Click() [Link] End Sub
Private Sub

INSERT_Click() [Link] End Sub


Private Sub
TRANSACTION_Click()
[Link] End Sub
Private Sub UPDATE_Click() [Link] MsgBox "record updated successfully"
End Sub
SOURCE CODE FOR FORM 3
Private Sub ACCOUNT_Click() [Link]
End Sub
Private Sub CLEAR_Click() [Link] = ""
[Link] = "" End Sub
Private Sub DEPOSIT_Click()
Dim s As String s = InputBox("enter the amount to be deposited")
[Link] = Val([Link]) + Val(s) A = [Link] MsgBox "CURRENT BALANCE IS Rs" + Str(A)
[Link] [Link]
Sub Private Sub EXIT_Click() Unload Me End Sub Private Sub HOME_Click() [Link] End Sub
Private Sub
WITHDRAW_Click()
Dim s As String s = InputBox("enter the amount to be deleted")
[Link] = Val([Link]) - Val(s) A = [Link] MsgBox "current balance is Rs" + Str(A)
[Link] [Link] End Sub

OUTPUT:

23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM


31

Result:
Thus the banking system was designed and implemented successfully.

Ex. No : 10 DESIGN AND IMPLEMENTATION OF STUDENT INFORMATION


Date : SYSTEM

AIM:
To design and implement Student Information System.

STEPS:
1. Create a database for library which request the using SQL

2. Establish ODBC connection

3. In the administrator tools open data source ODBC

4. Click add button and select oracle in ORA home 90, click finish

5. A window will appear given the data source home as oracle and select TNS source name as lion and give
the used id as SWTT

6. ADODC CONTROL FOR library FORM:-

7. The above procedure must be follow except the table , A select the table as library

8. Write appropriate Program in form each from created in VB from each from created in VB form project.

i. ADMINISTRATOR Table
This table holds the profile information of the application super users otherwise known as system
administrators. They have control of the software meaning that they can perform additional tasks that other
23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM
32

users cannot ordinarily perform. Every software of this nature has such users and this one is no exception.
The table contains the following columns; ADMIN_ID, TITLE, FRIST_NAME, LAST_NAME, and
DEPARMENT_ID.

The column ADMIN_ID is the primary key column (primary key disallows duplicate values and nulls in a
column) every table should have a primary key column, as this acts like table indexing.
ii. ALL_COURSE Table

This table keeps the courses offered by students in different departments in the school. The table contains
the following columns; COURSE_ID, COURSE_TITLE, and COURSE_CODE. The COURSE_ID is the
primary key column.
iii. APP_USER_A Table

This table contains application login details for application administrators. The table columns are;
USRNAME, PASSWD and ADMIN_ID. The column ADMIN_ID is the primary key
column.
iv. APP_USER_L Table

This table contains application login details for application lecturers. The table columns are; USRNAME,
PASSWD and LECTURER_ID. The column LECTURER_ID is the primary key column.
v. APP_USER_S Table

This table contains application login details for application students.


The table columns are;
USRNAME, PASSWD and MATRIG_NO. The column MATRIG_NO is the primary key column.
vi. DEPARTMENTS Table

This table holds information about the schools departments. The table contains the following columns;
DEPARTMENT_ID and DEPARTMENT_NAME. The column DEPARTMENT_ID is the primary key
column.
vii. GRADES Table

This is more like the main table in the database as all other tables relate to this table directly or in some
other way. This table holds students examination records. The table contains the following columns;
GRADES_ID, SESSION1, REG_NUMBER, DEPARTMENT_ID, LEVEL1,
MATRIG_NO,FRIST_NAME,LAST_NAME,COURSE_CODE,GRADE,CREDIT_UNIT,
SCORE, LECTURER_ID and GRADE_POINT. The column GRADES_ID is the primary key column.
viii. LECTURERS Table

This table holds the profile information of the application lecturers. The table contains the following
columns; LECTURER_ID, TITLE, FRIST_NAME, LAST_NAME, and DEPARMENT_ID. The column
LECTUTER_ID is the primary key column.
ix. REG_TABLE Table

This table contains student‟s registration details i.e. if a student is registered for the semester this table is
used to store that information. The table contains the following columns; REG_ID, REG_NUMBER,
MATRIG_NO, FRIST_NAME,LAST_NAME,
LEVEL1, DEPARTMENT_ID and SESSION1. The column REG_ID is the primary key column.
x. STUDENTS Table

23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM


33

This table holds the profile information of the application students. The table contains the following
columns; MATRIG_NO, TITLE, FRIST_NAME, LAST_NAME, and

DEPARMENT_ID. The column MATRIG_NO is the primary key column.

RESULT:
Thus the student information system was designed and implemented successfully.

Ex. No : 11 DATABASE DESIGN AND IMPLEMENTATION PAY ROLL


Date : PROCESSING

AIM:
To Design the database and implement Pay Roll Processing
STEPS:
 Create a database for payroll processing which request the using SQL
 Establish ODBC connection
 In the administrator tools open data source ODBC
 Click add button and select oracle in ORA home 90, click finish
 A window will appear given the data source home as oracle and select TNS source name as lion and give
the used id as SWTT
 ADODC CONTROL FOR SALARY FORM:-
 The above procedure must be follow except the table , A select the table as salary
 Write appropriate Program in form each from created in VB from each from created in VB form project.

SQL>create table emp(eno number primary key,enamr varchar(20),age number,addr varchar(20),DOB


date,phno number(10));
Table created.
SQL>create table salary(eno number,edesig varchar(10),basic number,da number,hra number,pf
number,mc number,met number,foreign key(eno) references emp);

Table created.
TRIGGER to calculate DA,HRA,PF,MC SQL>
create or replace trigger employ 2 after insert on salary

23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM


34

3 declare
4 cursor cur is select eno,basic from salary;
5 begin
6 for cur1 in cur loop
7 update salary set
8 hra=basic*0.1,da=basic*0.07,pf=basic*0.05,mc=basic*0.03 where hra=0; 9 end loop;
10 end;
11 / Trigger created.

PROGRAM FOR FORM 1


Private Sub emp_Click() Form [Link] End
Sub Private
Sub exit_Click() Unload Me
End Sub Private Sub salary_Click() [Link]
End Sub
PROGRAM FOR FORM 2
Private Sub add_Click()
[Link] MsgBox "Record added" End Sub Private Sub clear_Click()
[Link] = "" [Link] = "" [Link] = "" [Link] = "" [Link] = "" [Link] = ""
End Sub Private Sub delte_Click() [Link] MsgBox "Record Deleted" If
[Link] = True
Then [Link] End If
End
Sub Private Sub exit_Click() Unload Me
End Sub
Private Sub main_Click() [Link]
End Sub
Private Sub modify_Click() [Link] End Sub
PROGRAM FOR FORM 3
Private Sub add_Click()
[Link] MsgBox "Record added"
End Sub
Private Sub clear_Click()
[Link] = ""
[Link] = ""
[Link]=""
[Link]=""
[Link] = ""
[Link] = ""
End
Sub
Private Sub delte_Click()
[Link] MsgBox "Record Deleted" If [Link] = True
Then [Link] End If
End Sub
Private Sub exit_Click() Unload Me
End Sub
Private Sub main_Click() [Link] End Sub
Private Sub modify_Click() [Link]
End Sub
23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM
35

OUTPUT:

RESULT:
Thus payroll system was designed and implemented successfully.

23ITC04 / DATABASE MANAGEMENT SYSTEMS LABORATORY– MEC, RASIPURAM

You might also like