Top Banner
CS1256 – DATABASE MANAGEMENT SYSTEMS LABORATORY IV th SEMESTER CSE (Applicable to the Students admitted in the year 2009-2010/ Regulation 2008-Annauniversity of technology Tiruchirappalli ) ACADEMIC YEAR: 2010 – 2011 Prepared by Ms.M.ZAINAB HASEENA , Lecturer / CSE Authorized by Prof.K.PETCHIAPPAN Head of the Department Computer Science and Engineering DEPARTMENT St. MICHAEL COLLEGE OF ENGINEERING AND TECHNOLOGY (An ISO 9001: 2008 Certified Institution) (Affiliated to Anna University of Technology, Tiruchirappalli & Approved by AICTE, New Delhi) St.Santhiyagappar Nagar, Kalayarkoil, Sivagangai District 630 551 Founder Photo LAB MANUAL CUM OBSERVATION NOTE TUV Logo College Logo
95
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: DBMS Lab Manual

CS1256 – DATABASE MANAGEMENT SYSTEMS LABORATORY

IVth SEMESTER CSE

(Applicable to the Students admitted in the year 2009-2010/Regulation 2008-Annauniversity of technology Tiruchirappalli)

ACADEMIC YEAR: 2010 – 2011

Prepared by

Ms.M.ZAINAB HASEENA ,

Lecturer / CSE

Authorized by

Prof.K.PETCHIAPPAN

Head of the Department

Computer Science and Engineering

DEPARTMENT

OF

COMPUTER SCIENCE AND ENGINEERING

St. MICHAEL COLLEGE OF ENGINEERING AND TECHNOLOGY(An ISO 9001: 2008 Certified Institution)

(Affiliated to Anna University of Technology, Tiruchirappalli & Approved by AICTE, New Delhi)

St.Santhiyagappar Nagar, Kalayarkoil, Sivagangai District 630 551

FounderPhoto

LAB MANUAL CUM OBSERVATION NOTE

TUVLogo

CollegeLogo

Page 2: DBMS Lab Manual

CS1256 – DBMS Lab

OVERVIEW

(About the Subject)

File-Based Approaches 

File-based approaches to data storage are based on relatively simple data structures, such as the Indexed Sequential Access Method (ISAM), and are usually implemented for a single application. Files are generally created on an as needed basis to service the data needs of an application.  The files are associated with an application.  The same data may be repeated on many files and stored under different names.  For example, an accounting application may refer to customer name while a purchasing application may refer to buyer name.  The physical storage characteristics of the same data may be different for different applications.  For example, one application may allow 20 characters for name while another application allows 25 characters for the same name.  Different business units are responsible for different data. Disadvantages of a File-Based Approach

 Updates to files may result in inconsistent data across the organization.  For example, if an accounting application updates a customer name without notifying other application areas that also maintain customer name, customer name will be stored differently for different applications. A file-based data storage approach makes it difficult for other applications to access data not owned by their application.  Data owned by other applications may be stored in a format not consistent with the retrieval capabilities of another application. File-based approaches to data storage are tied to applications rather than the entities to which the files refer.  File-based approaches do not recognize relationships between entities until such information is needed by an application. Database Approaches

 Database approaches to data storage support the sharing of data across multiple applications with multiple users.  Databases are structured in a way that is meaningful to an organization.  For example, if an organization maintains information on suppliers and the geographic areas they service, there would be a link in the database between the suppliers and geographic areas.  Databases reduce data redundancy.

SMCET / CSE Department

Page 3: DBMS Lab Manual

CS1256 – DBMS Lab

 A Database Management System (DBMS) is the software that handles all database accesses.  A DBMS presents a logical view of the data to the users.  How this data is stored and retrieved is hidden from the users.  A DBMS ensures that the data is consistent across the database and controls who can access what data.

St. MICHAEL COLLEGE OF ENGINEERING AND TECHNOLOGY

(An ISO 9001: 2008 Certified Institution) (Affiliated to Anna University of Technology, Tiruchirappalli & Approved

by AICTE, New Delhi)St.Santhiyagappar Nagar, Kalayarkoil, Sivagangai District 630 551

Department of Computer Science and Engineering

CS1256 – DATABASE MANAGEMENT SYSTEMS LABORATORY

IVth SEMESTER CSE

ACADEMIC YEAR: 2010 – 2011

SMCET / CSE Department

LAB MANUAL CUM OBSERVATION NOTE

CollegeLogo

Page 4: DBMS Lab Manual

CS1256 – DBMS Lab

NAME OF THE STUDENT : ______________________________

REGISTER NUMBER : ______________________________

BRANCH : ______________________________

YEAR/SEMESTER/ SECTION : ______________________________

SYLLABUS

CS1256 – DATABASE MANAGEMENT SYSTEMS LABORATORY

L T P C0

0 3 2

LIST OF EXPERIMENTS

1. Data Definition, Table Creation, Constraints,2. Insert, Select Commands, Update and Delete Commands.3. Nested Queries and Join Queries4. Views5. High level programming language extensions (Control

structures, Proceduresand Functions).6. Front end tools7. Forms8. Triggers9. Menu Design10. Reports.11. Database Design and implementation (Mini Project).

SOFTWARE REQUIREMENTS

Front end : VB/VC ++/JAVA

Back end : Oracle 11g, my SQL, DB2

Platform : Windows 2000 Professional/Windows XP

Oracle server could be loaded and can be connected from individual PCs.

SMCET / CSE Department

Page 5: DBMS Lab Manual

CS1256 – DBMS Lab

INDEX

Ex. No.

DATE TITLE OF THE EXPERIMENT

MARKS SIGNATURE

OB

SE

RV

AT

ION

(3

0)

PE

RF

OR

MA

NC

E

(40)

VIV

A (

10)

RE

CO

RD

(2

0)

TO

TA

L(1

00)

SMCET / CSE Department

Page 6: DBMS Lab Manual

CS1256 – DBMS Lab

Faculty In-Charge Head of the Department

Ex.No-1 Data Definition, Table Creation, Constraints

Data Definition language:

Statement Description

CREATE TABLE Creates a table

ALTER TABLE Modifies table structures

DROP TABLE Removes the rows and table structure

RENAME Changes the name of a table, view,sequence, or synonym

TRUNCATE Removes all rows from a table andreleases the storage space

Data Definition Language (DDL): statements are used to define the database structure or schema.

Examples: CREATE, ALTER, DROP statements

DDL COMMANDS

SMCET / CSE Department

Page 7: DBMS Lab Manual

CS1256 – DBMS Lab

CREATE TABLEThis statement is used to create a table. The syntax for this command is

create table tablename (colname1 datatype [constraint], colname2 datatype [constraint]);

ALTER TABLEThis command is used to add, drop columns in a table. The syntax for this command is

alter table tablename add colname1 datatype [constraint];alter table tablename drop column colname1;

DROP TABLEThe syntax for this command is-

drop table tablename;

TRUNCATE TABLE

TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be fired. As such, TRUCATE is faster and doesn't use as much undo space as a DELETE.

The syntax for TRUNCATE TABLE is

TRUNCATE TABLE "table_name"

RENAME TABLE

*    All indexes, columns, default columns, constraints, referential authorization, rules, and user authorities tables dependent on a renamed table will be renamed.    *   RENAME statement is not allowed for IMAGE/SQL tables.    *  When using RENAME command, data and grants made for tables are carried forward for the new name. No unload, load data, or recreating index is necessary.    *  All views dependent on a renamed table will be dropped.    * If a table has check constraints, then that table cannot be renamed.

RENAME TABLE dbname.user to users;

SQL Constraints

Types of SQL Constraints

- NOT NULL - UNIQUE

SMCET / CSE Department

Page 8: DBMS Lab Manual

CS1256 – DBMS Lab

- CHECK - Primary Key - Foreign Key

Each type of SQL Constraint is described in below with example.

SQL NOT NULL Constraint.

By default, a column can hold NULL value. If we not want to allow NULL or empty value in a column of our table, then we need to place an SQL Constraint on this column specifying that NULL empty column is now not an allowable value.

For example, in the following statement,

Example of NOT NULL Constraint

CREATE TABLE Employees (empID integer NOT NULL, FirstName varchar (30) NOT NULL, LastName varchar(30));

Columns "empID" and "FirstName" cannot include NULL, while "LastName" can include NULL, while inserting the record in this table we must provide empID and FirstName after this SQL NOT NULL Constraints apply.

SQL UNIQUE Constraint.

The UNIQUE SQL constraint ensures that all values in a column are distinct and unique values repetition will not allow after applying SQL UNIQUE Constraint.

For example, the following statement explains real example of SQL UNIQUE Constraints.

Example of SQL UNIQUE Constraint

CREATE TABLE Employees (empID integer UNIQUE, FirstName varchar (30), LastName varchar(30));

Column "empID" cannot include duplicate values, while such constraint does not hold for columns "FirstName" and "LastName" so these last two can hold duplication.

SMCET / CSE Department

Page 9: DBMS Lab Manual

CS1256 – DBMS Lab

Please note that a column that is specified as a primary key must also be unique. At the same time, a column that's unique may or may not be a primary key.

SQL CHECK Constraint.

The SQL CHECK constraint ensures that all values in a column satisfy certain conditions, suppose we are wishing to enter some conditional record like age of employ not less then 20 so we need to verify it with SQL CHECK Constraint.

For example, in the following statement explains how to use the SQL CHECK Constraint in our queries.

Example of SQL CHECK Constraint

CREATE TABLE Employees (empID integer CHECK (empID > 10), FirstName varchar (30), LastName varchar(30));

Write SQL queries for DDL commands and Constraints

AIM:To write the SQL queries for DDL commands and

constraints.

SQL QUERIES:

Create table:

create table emp(emp_id number(5),emp_name varchar(20),location varchar(20));

Table created.

Alter table:

alter table emp add (gender varchar(10));

Table altered.

Descripe the structure of table

desc emp;

SMCET / CSE Department

Page 10: DBMS Lab Manual

CS1256 – DBMS Lab

Name Null? Type

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

EMP_ID NUMBER(5)

EMP_NAME VARCHAR2(20)

LOCATION VARCHAR2(20)

GENDER VARCHAR2(10)

Modify the column data type:

alter table emp modify (emp_id varchar(5));

Table altered.

Modify the column size:

alter table emp modify(emp_id varchar(10));

Table altered.

Drop the column from table:

alter table emp drop column gender;

Table altered.

Rename the table:

rename emp to employee;

Table renamed.

Truncate the table:

truncate table employee;

Table truncated.

Drop the Table:

drop table employee;

Table dropped.

Not Null Constrint :

Create table with NOT NULL constraint

SMCET / CSE Department

Page 11: DBMS Lab Manual

CS1256 – DBMS Lab

create table stu1(stu_id number(10),stu_name varchar(20) NOT NULL,phone_no number(15));

Table created.

insert into stu1(stu_id,stu_name,phone_no)values(1,'Raja',9898989898);

1 row created.

insert into stu1(stu_id,stu_name,phone_no)values(2,'Venkat',NULL);

1 row created.

insert into stu1(stu_id,stu_name,phone_no)values(1,NULL,99945);

Error: ORA-01400: cannot insert NULL into ("SYSTEM"."STU1"."STU_NAME")

Primary key Constrint:

create table staff(staff_id number(5) primary key,staff_name varchar(10),gender varchar(5));

Table created.

insert into staff(staff_id,staff_name,gender)values(1,'suresh','male');

ERROR at line 1:

ORA-00001: unique constraint (SCOTT.SYS_C00813) violated

insert into staff(staff_id,staff_name,gender)values(1,'suresh','male');

Error: ORA-00001: unique constraint (SYSTEM.SYS_C004026) violated

insert into staff(staff_id,staff_name,gender)values(2,'suresh','male');

ERROR at line 1:

ORA-00001: unique constraint (SCOTT.SYS_C00813) violated

insert into staff(staff_id,staff_name,gender)values(NULL,'suresh','male');

ERROR at line 1:

ORA-01400: cannot insert NULL into ("SCOTT"."STAFF"."STAFF_ID")

Unique Constrint:

SMCET / CSE Department

Page 12: DBMS Lab Manual

CS1256 – DBMS Lab

create table stu(stu_id number(10),stu_name varchar(20) NOT NULL,phone_no number(15),email varchar(15) UNIQUE);

Table created.

insert into stu(stu_id,stu_name,phone_no,email)values(1,'raja',NULL,'sur_ra@gmail');

1 row created.

insert into stu(stu_id,stu_name,phone_no,email)values(2,'ravi',NULL,'sur_ra@gmail');

Error:ORA-00001: unique constraint (SYSTEM.SYS_C004025) violated

insert into stu(stu_id,stu_name,phone_no,email)values(2,'mano',NULL,NULL);

1 row created.

insert into stu(stu_id,stu_name,phone_no,email)values(3,'venkat',NULL,NULL);

1 row created.

Check Constrint:

create table empsal(emp_id varchar(10),emp_name varchar(20),salary number(15)check(salary>0));

Table created.

Result:

The SQL queries for DDL commands and constraints are executed in oracle server and the results are verified.

Ex.No-2 Insert, Select Commands, Update and Delete

Commands.

DML - stands for Data Manipulation Language, its the part of SQL that deals with querying, updating, deleting and inseting records in tables, views.

SMCET / CSE Department

Page 13: DBMS Lab Manual

CS1256 – DBMS Lab

The following types of actions may be performed using DML commands:

SELECT - extracts data from a database UPDATE - updates data in a database

DELETE - deletes data from a database

INSERT INTO - inserts new data into a database

1) Select - This command is used to fetch a result set of records from a table, view or a group of tables, views by making use of SQL joins.

Retrieval of data using SQL statements can be done by using different predicates along with it like WhereGroup ByHavingOrder By

SQL SELECT Syntax

SELECT column_name(s)FROM table_name

And

SELECT * FROM table_name

2) Insert - This command is used to add record(s) to a table. While inserting a record using the insert statement, the number of records being entered should match the columns of the table.

The first form doesn't specify the column names where the data will be inserted, only their values:

INSERT INTO table_nameVALUES (value1, value2, value3,...)

The second form specifies both the column names and the values to be inserted:

INSERT INTO table_name (column1, column2, column3,...)VALUES (value1, value2, value3,...)

SMCET / CSE Department

Page 14: DBMS Lab Manual

CS1256 – DBMS Lab

3) Update - This command is used to edit the record(s) of a table. It may be used to update a single row based on a condition, all rows, or a set of rows based on a condition.

It is used along with the set clause. Optionally, a where clause may be used to match conditions.

SQL UPDATE Syntax

UPDATE table_nameSET column1=value, column2=value2,...WHERE some_column=some_value

Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated!

4) Delete - This command is used to remove record(s) from a table. All records may be removed in one go, or a set of records may be deleted based on a condition.

SQL DELETE Syntax

DELETE FROM table_nameWHERE some_column=some_value

Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted

Write SQL queries for insert, select and update commands

SMCET / CSE Department

Page 15: DBMS Lab Manual

CS1256 – DBMS Lab

AIM

To compile and write queries for insert, select, update and delete

SQL QUERIES:

Table creation with constraints:

create table student(stu_id varchar(10)primary key,stu_name varchar(20)NOT NULL,gender varchar(10),location varchar(20),sem_mark number(5));

Table created.

Insert values:

insert into student(stu_id,stu_name,gender,location,sem_mark)values('cs01','Raja','male','madurai',543);

1 row created.

insert into student(stu_id,stu_name,gender,location,sem_mark)values('cs02','Abinya','female','trichy',523);

1 row created.

insert into student(stu_id,stu_name,gender,location,sem_mark)values('cs03','Babu','male','trichy',483);

1 row created.

insert into student(stu_id,stu_name,gender,location,sem_mark)values('cs04','David','male','madurai',383);

1 row created.

insert into student(stu_id,stu_name,gender,location,sem_mark)values('cs05','Ganga','female','chennai',583);

1 row created.

SMCET / CSE Department

Page 16: DBMS Lab Manual

CS1256 – DBMS Lab

insert into student(stu_id,stu_name,gender,location,sem_mark)values('cs06','jeeva','male','coimbatore',289);

1 row created.

insert into student(stu_id,stu_name,gender,location,sem_mark)values('cs07','Karthika','female','coimbatore',489);

1 row created.

insert into student(stu_id,stu_name,gender,location,sem_mark)values('cs07','kannan','male','erode',339);

Error:ORA-00001: unique constraint (SYSTEM.SYS_C003997) violated

insert into student(stu_id,stu_name,gender,location,sem_mark)values('cs08','kannan','male','erode',339);

1 row created.

insert into student(stu_id,stu_name,gender,location,sem_mark)values('cs09','Sathya','female','chennai',323);

1 row created.

insert into student(stu_id,stu_name,gender,location,sem_mark)values('cs09',NULL,'female','chennai',323);

Error:ORA-01400: cannot insert NULL into ("SYSTEM"."STUDENT"."STU_NAME")

insert into student(stu_id,stu_name,gender,location,sem_mark)values('cs10','Prabhu','male','chennai',NULL);

1 row created.

insert into student(stu_id,stu_name,gender,location,sem_mark)values('cs11','Aravind','male','chennai',183);

1 row created.

SMCET / CSE Department

Page 17: DBMS Lab Manual

CS1256 – DBMS Lab

insert into student(stu_id,stu_name,gender,location,sem_mark)values('cs12','Babu','male','chennai',163);

1 row created.

select command:

select * from student;

STU_ID STU_NAME GENDER LOCATION SEM_MARK

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

cs01 Raja male madurai 543

cs02 Abinya female trichy 523

cs03 Babu male trichy 483

cs04 David male madurai 383

cs05 Ganga female chennai 583

cs06 jeeva male coimbatore 289

cs07 Karthika female coimbatore 489

cs08 kannan male erode 339

cs09 Sathya female chennai 323

cs10 Prabhu male chennai

cs11 Aravind male chennai 183

cs12 Babu male chennai 163

12 rows selected.

select stu_name,sem_mark from student;

STU_NAME SEM_MARK

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

Raja 543

Abinya 523

Babu 483

SMCET / CSE Department

Page 18: DBMS Lab Manual

CS1256 – DBMS Lab

David 383

Ganga 583

jeeva 289

Karthika 489

kannan 339

Sathya 323

Prabhu

Aravind 183

Babu 163

12 rows selected.

ARITHMETIC OPERATORS:

Operator Description

+ Add

- Subtract

* Multiply

/ Divide

select stu_name,sem_mark,sem_mark+10 from student;

STU_NAME SEM_MARK SEM_MARK+10

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

Raja 543 553

Abinya 523 533

Babu 483 493

David 383 393

Ganga 583 593

jeeva 289 299

SMCET / CSE Department

Page 19: DBMS Lab Manual

CS1256 – DBMS Lab

Karthika 489 499

kannan 339 349

Sathya 323 333

Prabhu

Aravind 183 193

Babu 163 173

12 rows selected.

select stu_name,sem_mark,sem_mark/7 as avg from student;

STU_NAME SEM_MARK AVG

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

Raja 543 77.571429

Abinya 523 74.714286

Babu 483 69

David 383 54.714286

Ganga 583 83.285714

jeeva 289 41.285714

Karthika 489 69.857143

kannan 339 48.428571

Sathya 323 46.142857

Prabhu

Aravind 183 26.142857

Babu 163 23.285714

12 rows selected.

Using the Concatenation Operator:

SMCET / CSE Department

Page 20: DBMS Lab Manual

CS1256 – DBMS Lab

select stu_name||' is from '||location from student;

STU_NAME||'ISFROM'||LOCATION

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

Raja is from madurai

Abinya is from trichy

Babu is from trichy

David is from madurai

Ganga is from chennai

jeeva is from coimbatore

Karthika is from coimbatore

kannan is from erode

Sathya is from chennai

Prabhu is from chennai

Aravind is from chennai

Babu is from chennai

12 rows selected.

select location from student;

LOCATION

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

madurai

trichy

trichy

madurai

chennai

coimbatore

SMCET / CSE Department

Page 21: DBMS Lab Manual

CS1256 – DBMS Lab

coimbatore

erode

chennai

chennai

chennai

chennai

12 rows selected.

ELIMINATING DUPLICATE ROWS:

select distinct location from student;

LOCATION

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

chennai

coimbatore

erode

madurai

trichy

WHERE Clause:

select * from student where location='chennai';

STU_ID STU_NAME GENDER LOCATION SEM_MARK

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

cs05 Ganga female chennai 583

cs09 Sathya female chennai 323

cs10 Prabhu male chennai

cs11 Aravind male chennai 183

cs12 Babu male chennai 163

Comparison Conditions:

SMCET / CSE Department

Page 22: DBMS Lab Manual

CS1256 – DBMS Lab

Operator Meaning

= Equal to

> Greater than

>= Greater than or equal to

< Less than

<= Less than or equal to

<> Not equal to

select * from student where sem_mark<500;

STU_ID STU_NAME GENDER LOCATION SEM_MARK

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

cs03 Babu male trichy 483

cs04 David male madurai 383

cs06 jeeva male coimbatore 289

cs07 Karthika female coimbatore 489

cs08 kannan male erode 339

cs09 Sathya female chennai 323

cs11 Aravind male chennai 183

cs12 Babu male chennai 163

8 rows selected.

select * from student where sem_mark>300;

STU_ID STU_NAME GENDER LOCATION SEM_MARK

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

cs01 Raja male madurai 543

cs02 Abinya female trichy 523

SMCET / CSE Department

Page 23: DBMS Lab Manual

CS1256 – DBMS Lab

cs03 Babu male trichy 483

cs04 David male madurai 383

cs05 Ganga female chennai 583

cs07 Karthika female coimbatore 489

cs08 kannan male erode 339

cs09 Sathya female chennai 323

8 rows selected.

select * from student where sem_mark<300;

STU_ID STU_NAME GENDER LOCATION SEM_MARK

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

cs06 jeeva male coimbatore 289

cs11 Aravind male chennai 183

cs12 Babu male chennai 163

select * from student where location!='chennai';

STU_ID STU_NAME GENDER LOCATION SEM_MARK

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

cs01 Raja male madurai 543

cs02 Abinya female trichy 523

cs03 Babu male trichy 483

cs04 David male madurai 383

cs06 jeeva male coimbatore 289

cs07 Karthika female coimbatore 489

cs08 kannan male erode 339

7 rows selected.

SMCET / CSE Department

Page 24: DBMS Lab Manual

CS1256 – DBMS Lab

Other Comparison Conditions

Operator Meaning

BETWEEN ...AND... Between two values (inclusive),

IN(set) Match any of a list of values

LIKE Match a character pattern

IS NULL Is a null value

select * from student where sem_mark between 400 and 500;

STU_ID STU_NAME GENDER LOCATION SEM_MARK

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

cs03 Babu male trichy 483

cs07 Karthika female coimbatore 489

select * from student where stu_id in('cs01','cs05','cs09');

STU_ID STU_NAME GENDER LOCATION SEM_MARK

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

cs09 Sathya female chennai 323

cs05 Ganga female chennai 583

cs01 Raja male madurai 543

select * from student where stu_id not in('cs01','cs05','cs09');

STU_ID STU_NAME GENDER LOCATION SEM_MARK

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

cs02 Abinya female trichy 523

cs03 Babu male trichy 483

cs04 David male madurai 383

cs06 jeeva male coimbatore 289

SMCET / CSE Department

Page 25: DBMS Lab Manual

CS1256 – DBMS Lab

cs07 Karthika female coimbatore 489

cs08 kannan male erode 339

cs10 Prabhu male chennai

cs11 Aravind male chennai 183

cs12 Babu male chennai 163

9 rows selected.

select stu_name from student where stu_name like 'A%';

STU_NAME

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

Abinya

Aravind

select stu_name from student where stu_name like '_r%';

STU_NAME

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

Prabhu

Aravind

select stu_name from student where stu_name like '%u';

STU_NAME

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

Babu

Prabhu

Babu

select stu_id,stu_name from student where sem_mark is NULL;

STU_ID STU_NAME

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

cs10 Prabhu

Logical Conditions

SMCET / CSE Department

Page 26: DBMS Lab Manual

CS1256 – DBMS Lab

Operator Meaning

AND Returns TRUE if both component conditions are true

OR Returns TRUE if either component condition is true

NOT Returns TRUE if the following condition is false

select stu_id,stu_name,gender,sem_mark from student where sem_mark>500 and gender='female';

STU_ID STU_NAME GENDER SEM_MARK

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

cs02 Abinya female 523

cs05 Ganga female 583

select stu_name from student order by stu_name desc ;

STU_NAME

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

kannan

jeeva

Sathya

Raja

Prabhu

Karthika

Ganga

David

Babu

Babu

Aravind

Abinya

SMCET / CSE Department

Page 27: DBMS Lab Manual

CS1256 – DBMS Lab

12 rows selected.

UPDATE:

UPDATE table SET column = value [, column = value, ...][WHERE condition];

update student set location='madurai' where stu_id='cs09';

1 row updated.

DELETE COMMAND:

DELETE [FROM] table [WHERE condition];

delete from student where stu_id=’cs09’;

1 row deleted.

Select * from student;

STU_ID STU_NAME GENDER LOCATION SEM_MARK

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

cs01 Raja male madurai 543

cs02 Abinya female trichy 523

cs03 Babu male trichy 483

cs04 David male madurai 383

cs05 Ganga female chennai 583

cs06 jeeva male coimbatore 289

cs07 Karthika female coimbatore 489

cs08 kannan male erode 339

cs10 Prabhu male chennai

cs11 Aravind male chennai 183

cs12 Babu male chennai 163

11 rows selected.

SMCET / CSE Department

Page 28: DBMS Lab Manual

CS1256 – DBMS Lab

Result:

The SQL queries for insert, select, update and delete commands are executed in oracle server and the results are verified.

Ex-no-3 Nested Queries and Join Queries

SQL Subquery

Subquery or Inner query or Nested query is a query in a query. A subquery is usually added in the WHERE Clause of the sql statement. Most of the time, a subquery is used when you know how to search for a value using a SELECT statement, but do not know the exact value.

Subqueries are an alternate way of returning data from multiple tables.

Subqueries can be used with the following sql statements along with the comparision operators like =, <, >, >=, <= etc.

SELECT INSERT

UPDATE

DELETE

SQL JOIN

The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a relationship between certain columns in these tables.

Tables in a database are often related to each other with keys.

A primary key is a column (or a combination of columns) with a unique value for each row. Each primary key value must be unique within the table. The purpose is to bind data together, across tables, without repeating all of the data in every table.

SMCET / CSE Department

Page 29: DBMS Lab Manual

CS1256 – DBMS Lab

Different SQL JOINs

Before we continue with examples, we will list the types of JOIN you can use, and the differences between them.

JOIN: Return rows when there is at least one match in both tables LEFT JOIN: Return all rows from the left table, even if there are

no matches in the right table

RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table

FULL JOIN: Return rows when there is a match in one of the tables

SQL INNER JOIN

The INNER JOIN keyword return rows when there is at least one match in both tables.SQL INNER JOIN Syntax

SELECT column_name(s)FROM table_name1INNER JOIN table_name2ON table_name1.column_name=table_name2.column_name

SQL LEFT JOIN

The LEFT JOIN keyword returns all rows from the left table (table_name1), even if there are no matches in the right table (table_name2).

SQL LEFT JOIN Syntax

SELECT column_name(s)FROM table_name1LEFT JOIN table_name2ON table_name1.column_name=table_name2.column_name

SQL RIGHT JOIN

The RIGHT JOIN keyword Return all rows from the right table (table_name2), even if there are no matches in the left table (table_name1).

SQL RIGHT JOIN Syntax

SELECT column_name(s)FROM table_name1RIGHT JOIN table_name2

SMCET / CSE Department

Page 30: DBMS Lab Manual

CS1256 – DBMS Lab

ON table_name1.column_name=table_name2.column_name

SQL FULL JOIN

The FULL JOIN keyword return rows when there is a match in one of the tables.

SQL FULL JOIN Syntax

SELECT column_name(s)FROM table_name1FULL JOIN table_name2ON table_name1.column_name=table_name2.column_name

Write Nested queries and joined queries for oracle server

AIMTo study about Nested queries and join queries

SQL QUERIES:

Main Query

Which employees have salaries greater than Om’s salary?

Subquery:

What is Om’s salary?

Syntax

SELECT select_list FROM table WHERE expr operator (SELECT select_list FROM table);

Tables used:

1.employee

2.employee_salary

Create table 1:

SMCET / CSE Department

Page 31: DBMS Lab Manual

CS1256 – DBMS Lab

create table employee(emp_name varchar(20),city varchar(20));

Table created.

Insert values:

insert into employee(emp_name,city)values('Hari','Pune');

1 row created.

insert into employee(emp_name,city)values('Om','Mumbai');

1 row created.

insert into employee(emp_name,city)values('Smith','Nashik');

1 row created.

insert into employee(emp_name,city)values('Jay','Solapur');

1 row created.

Create table 2:

create table employee_salary(emp_name varchar(10),dept varchar(10),salary number(10));

Table created.

Insert values:

insert into employee_salary(emp_name,dept,salary)values('Hari','Computer',10000);

1 row created.

insert into employee_salary(emp_name,dept,salary)values('Om','IT',7000);

1 row created.

insert into employee_salary(emp_name,dept,salary)values('Billi','Computer',8000);

1 row created.

insert into employee_salary(emp_name,dept,salary)values('Jay','IT',5000);

1 row created.

SMCET / CSE Department

Page 32: DBMS Lab Manual

CS1256 – DBMS Lab

To find the employee names who have get the salary higher than Om’s Salary?

select emp_name,salary from employee_salary where salary>(select salary from employee_salary where emp_name='Om');

EMP_NAME SALARY

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

Hari 10000

Billi 8000

To find Min salary in the table:

Select min(salary) from employee_salary;

MIN(SALARY)

-----------

5000

To find the employee details who get lowest salary in the company?

select * from employee_salary where salary=(select min(salary) from employee_salary);

EMP_NAME DEPT SALARY

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

Jay IT 5000

To find the employee details who get Highest salary in the company?

select * from employee_salary where salary=(select max(salary) from employee_salary);

EMP_NAME DEPT SALARY

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

Hari Computer 10000

Join queries:

Inner Join:

SMCET / CSE Department

Page 33: DBMS Lab Manual

CS1256 – DBMS Lab

select employee.emp_name,employee_salary.salary from employee innerjoin employee_salary on employee.emp_name=employee_salary.emp_name;

select * from employee innerjoin employee_salary on employee.emp_name=employee_salary.emp_name;

Full Outer join:

select * from employee full outer join employee_salary on employee.emp_name=employee_salary.emp_name;

Left outer join

select * from employee leftouterjoin employee_salary on employee.emp_name=employee_salary.emp_name;

Right outer join:

select * from employee right outer join employee_salary on employee.emp_name=employee_salary.emp_name;

Result:

The SQL nested queries and joined queries are executed in oracle server and the results are verified.

Ex-no-4 View

View

A view is a virtual table that consists of columns from one or more tables. Though it is similar to a table, it is stored in the database. It is a query stored as an object. Hence, a view is an object that derives its data from

SMCET / CSE Department

Page 34: DBMS Lab Manual

CS1256 – DBMS Lab

one or more tables. These tables are referred to as base or underlying tables.

Once you have defined a view, you can reference it like any other table in a database.

A view serves as a security mechanism. This ensures that users are able to retrieve and modify only the data seen by them. Users cannot see or access the remaining data in the underlying tables. A view also serves as a mechanism to simplify query execution. Complex queries can be stored in the form as a view, and data from the view can be extracted using simple queries.

SQL CREATE VIEW Statement

In SQL, a view is a virtual table based on the result-set of an SQL statement.

A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database.

You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were coming from one single table.

SQL CREATE VIEW Syntax

CREATE VIEW view_name ASSELECT column_name(s)FROM table_nameWHERE condition

SQL Updating a View

You can update a view by using the following syntax:

SQL CREATE OR REPLACE VIEW Syntax

CREATE OR REPLACE VIEW view_name ASSELECT column_name(s)FROM table_nameWHERE condition

SQL Dropping a View

You can delete a view with the DROP VIEW command.

SQL DROP VIEW Syntax

SMCET / CSE Department

Page 35: DBMS Lab Manual

CS1256 – DBMS Lab

DROP VIEW view_name

Write views for DDL commands in SQL queries

AIM:To studies about views for DDL commands

SQL QUERIES:

Top-N Analysis

SMCET / CSE Department

Page 36: DBMS Lab Manual

CS1256 – DBMS Lab

Top-N queries finds the n largest or smallest values of a column

for example

-what are the 5 best students in the class

-what are the 5 worst students in the class

select rownum as rank,stu_name,sem_mark from(select stu_name,sem_mark from student order by sem_mark)where rownum<=3;

select rownum as rank,stu_name,sem_mark from(select stu_name,sem_mark from student order by sem_mark desc)where rownum<=3;

create view sur as select * from employee_salary;

View created.

create view sur1 as select emp_name,salary from employee_salary where salary=7000;

View created.

desc sur1;

Name Null? Type

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

EMP_NAME VARCHAR2(10)

SALARY NUMBER(10)

select * from sur1;

EMP_NAME SALARY

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

Om 7000

create view sur2 as select emp_name name,salary+1000 new_salary from employee_salary;

View created.

desc sur2;

SMCET / CSE Department

Page 37: DBMS Lab Manual

CS1256 – DBMS Lab

Name Null? Type

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

NAME VARCHAR2(10)

NEW_SALARY NUMBER

select * from sur2;

NAME NEW_SALARY

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

Hari 11000

Om 8000

Billi 9000

Jay 6000

drop table:

drop view view name;

drop view sur1;

View dropped.

Result:

The Views for DDL commands in SQL queries are executed in oracle server and the results are verified.

Ex-no:5 High level programming language extensions

SMCET / CSE Department

Page 38: DBMS Lab Manual

CS1256 – DBMS Lab

(Control structures, Procedures and Functions).

Conditional Control (Selection): This structure tests a condition, depending on the condition is true or false it decides the sequence of statements to be executed. Example IF-THEN, CASE and searched CASE statements.

Syntax for IF-THEN

IF THEN Statements END IF;

IF-THEN-ELSE:

IF THEN

Statements

ELSE

statements

END IF;

IF-THEN-ELSIF:

IF THEN

Statements

ELSIF THEN

Statements

ELSE

Statements

END IF;

Iterative Control

SMCET / CSE Department

Page 39: DBMS Lab Manual

CS1256 – DBMS Lab

LOOP statement executes the body statements multiple times. The statements are placed between LOOP – END LOOP keywords.

The simplest form of LOOP statement is an infinite loop. EXIT statement is used inside LOOP to terminate it.

Syntax for LOOP- END LOOP

LOOP

Statements

END LOOP;

Example:

BEGIN

LOOP

DBMS_OUTPUT.PUT_LINE (‘Hello’);

END LOOP;

END;

PL/SQL Procedure

A stored procedure or in simple a proc is a named PL/SQL block which performs one or more specific task. This is similar to a procedure in other programming languages. A procedure has a header and a body. The header consists of the name of the procedure and the parameters or variables passed to the procedure. The body consists or declaration section, execution section and exception section similar to a general PL/SQL Block. A procedure is similar to an anonymous PL/SQL Block but it is named for repeated usage.

We can pass parameters to procedures in three ways. 1) IN-parameters2) OUT-parameters3) IN OUT-parameters

A procedure may or may not return any value.

General Syntax to create a procedure is:

SMCET / CSE Department

Page 40: DBMS Lab Manual

CS1256 – DBMS Lab

CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters]

IS

Declaration section

BEGIN

Execution section

EXCEPTION

Exception section

END;

IS - marks the beginning of the body of the procedure and is similar to DECLARE in anonymous PL/SQL Blocks. The code between IS and BEGIN forms the Declaration section.

The syntax within the brackets [ ] indicate they are optional. By using CREATE OR REPLACE together the procedure is created if no other procedure with the same name exists or the existing procedure is replaced with the current code.

PL/SQL Functions

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.

The General Syntax to create a function is:

CREATE [OR REPLACE] FUNCTION function_name [parameters] RETURN return_datatype; IS Declaration_section BEGIN Execution_section Return return_variable; EXCEPTION exception section Return return_variable; END;

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

SMCET / CSE Department

Page 41: DBMS Lab Manual

CS1256 – DBMS Lab

2) The execution and exception section both should return a value which is of the datatype defined in the header section.

Write PL/SQL programs in Oracle Server

AIM:To write the High level programming language extensions

(Control structures, procedures and functions) in Oracle server. PROGRAM:

PL/SQL Program to find the addition of 2 numbers:

set serveroutput on;declarea number;b number;c number;begina:=&a;b:=&b;c:=a+b;dbms_output.put_line('addition'||c);end;/Enter value for a: 6old 6: a:=&a;new 6: a:=6;Enter value for b: 8old 7: b:=&b;new 7: b:=8;addition14

PL/SQL procedure successfully completed.

PL/sql sum of series(1+2+3++…..+n)Program:set serveroutput on;declaren number:=&n;i number:=1;x number:=0;beginloopx:=x+i;exit when i=n;i:=i+1;

SMCET / CSE Department

Page 42: DBMS Lab Manual

CS1256 – DBMS Lab

end loop;dbms_output.put_line('sum='||x);end;/Enter value for n: 5old 2: n number:=&n;new 2: n number:=5;sum=15PL/SQL procedure successfully completed.

PL/SQL Program to find the biggest of three numbers:

set serveroutput on;declarea number;b number;c number;begina:=&a;b:=&b;c:=&c;if (a>b) thendbms_output.put_line('The biggest value is a='||a);elsif (b>c) thendbms_output.put_line('The biggest value is b='||b);elsedbms_output.put_line('The biggest value is c='||c);end if;end;/Enter value for a: 5old 6: a:=&a;new 6: a:=5;Enter value for b: 1old 7: b:=&b;new 7: b:=1;Enter value for c: 2old 8: c:=&c;new 8: c:=2;The biggest value is a=5

PL/SQL procedure successfully completed.

PROCEDURE:

PL/SQL Program to find the Factorial of a given number using Procedure

set serveroutput on; create or replace procedure fact(f in number)

SMCET / CSE Department

Page 43: DBMS Lab Manual

CS1256 – DBMS Lab

as fact number; begin fact:=1; for i in 1..f loop fact:=fact*i; end loop; dbms_output.put_line(f||'!'|| fact); end fact;/Procedure created

To ExecuteExec fact(5)5!120

PL/SQL procedure successfully completed.

FUNCTION:

CREATE OR REPLACE FUNCTION tax(p_value IN NUMBER)RETURN NUMBER ISBEGINRETURN (p_value * 0.08);END tax;

/Function created

select emp_name,salary,tax(salary) from employee_salary;

EMP_NAME SALARY TAX(SALARY)---------- --------- -----------Hari 10000 800Om 7000 560Billi 8000 640Jay 5000 400

RESULT:

The control structures, procedures and functions are executed in Oracle server and the output is verified.

SMCET / CSE Department

Page 44: DBMS Lab Manual

CS1256 – DBMS Lab

EX-NO-6 FRONT END TOOLS

AIM:

To study the front end tools of oracle developer suite and their functions.

INTRODUCTION:

A collection of tools represented by iconic buttons in the user interface that allow a report developer to perform tasks, such as drawing a rectangle in the Paper Layout view or creating a query in the Data Model view.

Main Toolbar

The main toolbar is located at the top of the Reports Builder window, directly beneath the menu bar:

New button. Displays the New Report dialog box.

Open button. Displays the Open dialog box.

Save button. Saves the report. If you haven't saved the report before, the Save As dialog box displays.

Print button. Prints the paper report.

Mail button. Displays the Mail dialog box.

Connect button. Displays the Connect dialog box.

Cut button. Deletes the currently selected item and temporarily places it in the clipboard.

Copy button. Temporarily places a copy of the selected item in the clipboard.

Paste button. Pastes the item in the clipboard in current location of the cursor.

SMCET / CSE Department

Page 45: DBMS Lab Manual

CS1256 – DBMS Lab

Undo button. Undoes the last action performed.

Redo button. Performs the last action again.

Run Web Layout button. Runs the current report to the Web browser.

Run Paper Layout button. Runs the current report to the Paper Design view in Reports Builder.

Paper Layout View Tool Palette

The Paper Layout view tool palette is a vertical group of tools located on the left-hand side of the Paper Layout view.

Select: Deselects any selected tool to turn off the current tool.

Magnify: Zooms in the view on the clicked object.

Frame Select tool. Selects all objects within the selected frame or

repeating frame, depending upon their explicit anchors.

Reshape tool. Enables to reshape the selected object.

Rectangle: Draws a rectangle object.

Ellipse: Draws an ellipse object.

Polygon: Draws a multisided object. The object must be closed, unlike a

polyline object.

Rounded rectangle: Draws a rounded rectangle object.

Text: Creates a boilerplate text object

Radio Button: To give the user an option of selecting either Male or

Female.

Image item: To display the images in the paper layout screen

List item: To list out the data items

Rotate: Enables to rotate the direction of the selected object.

Line: Draws a line object.

Arc: Draws an arc image.

Polyline: Draws an open multilined object. Use the mouse to create the

multiple lines.

Freehand: Draws a line where you drag the mouse.

SMCET / CSE Department

Page 46: DBMS Lab Manual

CS1256 – DBMS Lab

Frame: Draws a frame.

Repeating Frame tool. Draws a repeating frame.

Graph: Displays the Graph Wizard so that you can to define a graph that

will be inserted into the layout.

Check Box: is a graphical user interface element (widget) that permits

the user to make multiple selections from a number of options.

Normally, check boxes are shown on the screen as a square box that

can contain white space (for false) or a tick mark or X (for true), as

pictured

Chart Item: Displays the datas in chart format

Hierarchial tree: Displays the data in tree structure

Stacked canvas The stacked canvas is extension of content canvas which

can be display or hide dynamically. The main advantage of stacked

canvas is to extend the size of the content cavas.Fill color:

Line Color: selects the color to line

Text Color: selects the color to text

SMCET / CSE Department

Page 47: DBMS Lab Manual

CS1256 – DBMS Lab

RESULT:

Thus the front end tools of oracle developer suite have been studied.

EX-NO-7 FORMS

DESCRIPTION:

Oracle Forms is a software product for creating screens that interact with an Oracle database. It has a IDE including an object navigator, property sheet and code editor that uses PL/SQL. It was originally developed to run server-side in character mode terminal sessions. It was ported to other platforms, including Windows, to function in a client–server environment. Later versions were ported to Java where it runs in a Java EE container and can integrate with Java and web services.

The primary focus of Forms is to create data entry systems that access an Oracle database.

Oracle Forms Builder is an Oracle tool that helps us to create forms. We can use

Oracle Forms Builder to:

• Design and customize the forms.• Add various functionality, like radio buttons, combo boxes,

and list of values to make the forms and reports more user friendly.

Components of Oracle Forms Builder

SMCET / CSE Department

Page 48: DBMS Lab Manual

CS1256 – DBMS Lab

Object Navigator: In this component we can view all the objects, add newobjects and name/rename the objects. (F3 hot key)Layout Editor: This component helps us to design the forms and add

variousobjects to them such as push buttons and list boxes. (F2 hot key)

How it works

Oracle Forms accesses the Oracle database and generates a screen that presents the data. The source form (*.fmb) is compiled into an "executable" (*.fmx), that is run (interpreted) by the forms runtime module. The form is used to view and edit data in database-driven applications. Various GUI elements, such as buttons, menus, scrollbars, and graphics can be placed on the form.

The environment supplies built-in record creation, query, and update modes, each with its own default data manipulations. This minimizes the need to program common and tedious operations, such as creating dynamic SQL, sensing changed fields, and locking rows.

As is normal with event driven interfaces, the software implements event-handling functions called triggers which are automatically invoked at critical steps in the processing of records, the receipt of keyboard strokes, and the receipt of mouse movements. Different triggers may be called before, during, and after each critical step.

Each trigger function is initially a stub, containing a default action or nothing. Programming Oracle Forms therefore generally consists of modifying the contents of these triggers in order to alter the default behavior. Some triggers, if provided by the programmer, replace the default action while others augment it.

As a result of this strategy, it is possible to create a number of default form layouts which possess complete database functionality yet contain no programmer-written code at all.

Design a form for Student table in oracle under windows

SMCET / CSE Department

Page 49: DBMS Lab Manual

CS1256 – DBMS Lab

AIM:

To create a new form for “Student” Table and format the data fields appropriately.

STEPS FOR CREATING FORMS:

To log on to Oracle Forms Builder, go to Start > Programs > Oracle Developer Suite > Forms Developer > Forms Builder

We will see the window for Oracle Form Builder with the sub-window for Object Navigator.

To Create a Data Block for STUDENT, First, double click Data Block in the Object Navigator.

We will see the sub-window for New Data Block. Select “Use the Datablock Wizard” and click OK.

We will now see the Welcome to the Data Block Wizard

SMCET / CSE Department

Page 50: DBMS Lab Manual

CS1256 – DBMS Lab

Window. Click Next to proceed.

Select “Table or View” and click Next.

Select a table or a view (this form will be created based on this selection) by click on “Browse” to look at the list of tables and views in the database.

Once we click browse, the connect window will appear. Type username, password and database to connect to the database, then click “Connect”.

Username: systemPassword: oracleDatabase: XE

We will now see the Tables window. Select current users and tables. Then Select STUDENT” in the list of tables created in the database and click OK.

We will now see the selected table and its available columns on the screen. Click on the double right arrow for selecting all the columns in to the database items. Then click Next.

We will now see the window for entering a name of the data block. Click Next to accept the default values.

We will now see the Congratulations window. Select “Create the data block, then call the Layout Wizard” and click on Finish.

We will now see the Welcome to the Layout Wizard Window. Click Next to proceed.

We will now see the window that prompts us to select canvas name and canvas type that we want to lay out the data block’s items. Click Next to accept the default values.

Select the items that we would like to show in the form. Then click on Next to continue.

The window with the prompt for the height and width of the items will appear. Click Next to accept the default values.

Select the layout style of the block. Select Form and click Next.

Select a title for the form that we are creating. Type in “Student Records” and Click Next to continue.

SMCET / CSE Department

Page 51: DBMS Lab Manual

CS1256 – DBMS Lab

We will now see the Congratulations window. Click on Finish to view the form.

We will now see the layout editor of the form that we have created. (we can now add various objects like push buttons, combo boxes and radio buttons to the form to make it more graphical and user friendly.)

Right click on the frame and select Property Palette from the popup menu. In the property palette, Set Update Layout = Manually.

In the object navigator, right click on the Window1 and select Property Palette from the popup menu. Then set Title = Student. We can now format the data fields manually.

Save the form by clicking on the Save icon on the toolbar or using Ctrl+S hot key.

Compile Module by clicking on the Compile Module icon on the toolbar or using Ctrl+T hot key.

Run the form by clicking on the Run Form icon on the toolbar or using Ctrl+R hot key.

SMCET / CSE Department

Page 52: DBMS Lab Manual

CS1256 – DBMS Lab

RESULT:

Thus the forms in oracle under windows has been designed and the output is verified.

SMCET / CSE Department

Page 53: DBMS Lab Manual

CS1256 – DBMS Lab

Ex-no-8 TRIGGER

INTRODUCTION

SQL trigger is an SQL statements or a set of SQL statements which is stored to be activated or fired when an event associating with a database table occurs. The event can be any event including INSERT, UPDATE  and DELETE. Sometimes a trigger is referred as a special kind of stored procedure in term of procedural code inside its body. The difference between a trigger and a stored procedure is that a trigger is activated or called when an event happens in a database table, a stored procedure must be called explicitly. For example you can have some business logic to do before or after inserting a new record in a database table.

Before applying trigger in your database project, you should know its pros and cons to use it properly.

Advantages of using SQL trigger

SQL Trigger provides an alternative way to check integrity. SQL trigger can catch the errors in business logic in the database

level.

SQL trigger provides an alternative way to run scheduled tasks. With SQL trigger, you don’t have to wait to run the scheduled tasks. You can handle those tasks before or after changes being made to database tables.

SQL trigger is very useful when you use it to audit the changes of data in a database table.

Disadvantages of using SQL trigger

SQL trigger only can provide extended validation and cannot replace all the validations. Some simple validations can be done in the application level.  For example, you can validate input check in the client side by using javascript or in the server side by server script using PHP or ASP.NET.

SQL Triggers executes invisibly from client-application which connects to the database server so it is difficult to figure out what happen underlying database layer.

SQL Triggers run every updates made to the table therefore it adds workload to the database and cause system runs slower.

SMCET / CSE Department

Page 54: DBMS Lab Manual

CS1256 – DBMS Lab

Trigger Limitations

CREATE TRIGGER must be the first statement in the batch and can apply to only one table.

A trigger is created only in the current database; however, a trigger can reference objects outside the current database.

If the trigger schema name is specified to qualify the trigger, qualify the table name in the same way.

The same trigger action can be defined for more than one user action (for example, INSERT and UPDATE) in the same CREATE TRIGGER statement.

INSTEAD OF DELETE/UPDATE triggers cannot be defined on a table that has a foreign key with a cascade on DELETE/UPDATE action defined.

Any SET statement can be specified inside a trigger. The SET option selected remains in effect during the execution of the trigger and then reverts to its former setting.

When a trigger fires, results are returned to the calling application, just like with stored procedures. To prevent having results returned to an application because of a trigger firing, do not include either SELECT statements that return results or statements that perform variable assignment in a trigger. A trigger that includes either SELECT statements that return results to the user or statements that perform variable assignment requires special handling; these returned results would have to be written into every application in which modifications to the trigger table are allowed. If variable assignment must occur in a trigger, use a SET NOCOUNT statement at the start of the trigger to prevent the return of any result sets.

Although a TRUNCATE TABLE statement is in effect a DELETE statement, it does not activate a trigger because the operation does not log individual row deletions. However, only those users with permissions to execute a TRUNCATE TABLE statement need be concerned about inadvertently circumventing a DELETE trigger this way.

The WRITETEXT statement, whether logged or unlogged, does not activate a trigger.

PL/SQL Triggers

Triggers are basically PL/SQL procedures that are associated with tables, and are called

SMCET / CSE Department

Page 55: DBMS Lab Manual

CS1256 – DBMS Lab

whenever a certain modification (event) occurs. The modification statements may include

INSERT, UPDATE, and DELETE.

The general structure of triggers is:

CREATE [OR REPLACE]TRIGGER trigger_nameBEFORE (or AFTER)INSERT OR UPDATE [OF COLUMNS] OR DELETEON tablename[FOR EACH ROW [WHEN (condition)]]BEGIN...END;The usual CREATE OR REPLACE we have already seen with procedures and functions... TRIGGERspecifies just what type of object we are creating.

The BEFORE (or AFTER) in the trigger definition refers to when you want to run the trigger,either before the actual database modification (update, delete, insert) or after.

The list of various statements, INSERT OR UPDATE [OF COLUMNS] OR DELETE refers tostatements that trigger this trigger. You can specify all three, or just one. Let’s say youwanted the trigger to fire only when you do a delete; well, then you’d only specify a DELETEin the list.

On some table specifies that the trigger is associated with such table. As we shall seelater, this does not necessarily has to be a table, but could also be a view.

There are several types of triggers; ones for each row and others per statement. Forexample, when you’re doing an update, you can have a trigger fire once for each thing beingupdated (if you update 20 rows, the thing would fire 20 times), or you can have it fire justonce per statement (if a single update statement is updating 20 rows, the trigger would firejust once). This is what that FOR EACH ROW in the trigger definition means.

The PL/SQL block (between BEGIN and END) is a usual code block where you can place

SMCET / CSE Department

Page 56: DBMS Lab Manual

CS1256 – DBMS Lab

PL/SQL commands. The only limitation is that you cannot use COMMIT (or ROLLBACK) forobvious reasons.

Execute trigger statements for the employee salary calculation in oracle server

AIM:

To Create and execute the trigger statement for the employee salary calculation

Create table:

create table empplo(idno number(5),name varchar(20),basicpay number(10),hra number(10),da number(10),ded number(10),netpay number(10),grosspay number(10));

Table created.

SMCET / CSE Department

Page 57: DBMS Lab Manual

CS1256 – DBMS Lab

Create Trigger:

create trigger trigger5 after insert on empplo

begin

update empplo set hra=basicpay*8/100;

update empplo set da=basicpay*25/100;

update empplo set grosspay=basicpay+hra+da;

update empplo set netpay=grosspay-ded;

end;

/

Trigger created.

Insert the values:

SQL> insert into empplo(idno,name,basicpay,ded)values(1,'suresh',20000,500);

1 row created.

SQL> insert into empplo(idno,name,basicpay,ded)values(2,'raju',25000,600);

1 row created.

SQL> insert into empplo(idno,name,basicpay,ded)values(3,'ravi',30000,700);

1 row created.

SQL> insert into empplo(idno,name,basicpay,ded)values(4,'shobana',35000,800);

1 row created.

SQL> select * from empplo;

IDNO NAME BASICPAY HRA DA DED NETPAY GROSSPAY

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

SMCET / CSE Department

Page 58: DBMS Lab Manual

CS1256 – DBMS Lab

1 suresh 20000 1600 5000 500 26100 26600

2 raju 25000 2000 6250 600 32650 33250

3 ravi 30000 2400 7500 700 39200 39900

4 shobana 35000 2800 8750 800 45750 46550

RESULT:

Thus the triggers in SQL are executed and the output is verified..

Ex-no-9 MENUS

SMCET / CSE Department

Page 59: DBMS Lab Manual

CS1256 – DBMS Lab

Description:

Menus are features that are available in nearly all programs nowadays . Making menus is very easy in Visual Basic using the menu editor .To start the menu editor you go to Tools | Menu Editor or pressing Ctrl and e achieves the same results .The menu editor now appears , here is what is displayed on screen.

Here is a run down of the important features

Caption : this is the name that the user will see 

Name : this is the name that the programmer uses , we use the mnu prefix for all menu items (mnuFile)

Shortcut : this assigns a shortcut to a menu item  this is a combination of keys which access a menu item for example Ctrl + c is commonly used for copy 

Checked : this allows the programmer to place a check beside a menu item , this is unchecked by default

SMCET / CSE Department

Page 60: DBMS Lab Manual

CS1256 – DBMS Lab

Enabled : This specifies whether the menu item is accessible to the user , if this is checked the menu item is grayed out and inaccessible.

Visible: this determines whether the menu item is visible if this is not checked then the menu item will not appear at run time.

WindowList : determines whether the menu item applies to an MDI document (Word and Excel are examples of MDI applications)

HelpContextID : this matches a help description if you have any in your programIndex : this specifies a menus index in a control array.

You will also have noticed the arrows these are used to manipulate manu items the up and down arrows move the menu items up and down the list and the left / right arrows are used to indent the menu items.

Now we will create a simple menu .

1. In the caption box type &File2. In the name box type mnuFile

3. click on the next button the blue bar moves down ready for the next item to be entered

4. Click the right arrow button

5. In the caption type -

6. In the Name box type mnuSeperator

7. press the next button

8. In the caption box type &Exit

9. in the name box type mnuFileExit

10. click on OK

SMCET / CSE Department

Page 61: DBMS Lab Manual

CS1256 – DBMS Lab

Design an application form containing menu with two top-level items.

Aim:

To develop an application form containing a menu with two top-level items, File and Help.

Steps: 

1. Start a new VB project and invoke the Menu Editor using either method shown above (click the Menu Editor toolbar icon or select the Menu Editor option from the Tools menu).

2. For "Caption", type &File (by placing the ampersand to the left of the "F", we establish "F" as an access key for the File item it enables the user to drop down the File menu by keying "Alt+F" on the keyboard in addition to clicking the "File" item with the mouse).

  For "Name", type mnuFile. Click the Next button.

3. Click the "right-arrow" button (shown circled below). A ellipsis (...) will appear as the next item in the menu list, indicating that this item is a level-two item (below "File").

For "Caption", type &New; for "Name", type mnuNew, and for "Shortcut", select Ctrl+N. By specifying a shortcut, you allow the user to access the associated menu item by pressing that key combination. So here, you are providing the user three ways of invoking the "New" function: (1) clicking File, then clicking New on the menu; (2) keying Alt+F,N (because we set up an access key for "N" by placing an ampersand to left of "N" in "New"); or (3) keying Ctrl+N. Click the Next button.

4. For "Caption", type &Open; for "Name", type mnuOpen, and for "Shortcut", select Ctrl+O. Click the Next button.

5. For "Caption", type - (a hyphen), and for "Name", type mnuFileBar1. A single hyphen as the Caption for a menu item tells VB to create a separator bar at that location. Click the Next button.

SMCET / CSE Department

Page 62: DBMS Lab Manual

CS1256 – DBMS Lab

6. For "Caption", type &Save; for "Name", type mnuSave, and for "Shortcut", select Ctrl+S. Click the Next button.

7. For "Caption", type Save &As ..., and for "Name", type mnuSaveAs. Click the Next button.

8. For "Caption", type -, and for "Name", type mnuFileBar2. Click the Next button.

9. For "Caption", type &Print;for "Name", type mnuPrint; and for "Shortcut", select Ctrl+P.

Click the Next button.

10. For "Caption", type -; and for "Name", type mnuFileBar3. Click the Next button.

11. For "Caption", type E&xit, and for "Name", type mnuExit. Click the Next button

12. Click the "left-arrow" button (shown circled below). The ellipsis (...) no longer appears, meaning we are back to the top-level items.

For "Caption", type &Help; and for "Name", type mnuHelp.

13. For "Caption", type &Help; and for "Name", type mnuHelp.

14. At this point, we are done creating our menu entries, so click the OK button. That will dismiss the menu editor and return focus to the VB IDE.

 15. Back in the VB IDE, your form will now have a menu, based on what you have set up in the Menu Editor. If you click on a top-level menu item (File for example), the level-two menu will drop down:

SMCET / CSE Department

Page 63: DBMS Lab Manual

CS1256 – DBMS Lab

16. Click on the New menu item. The code window for the mnuFileNew_Click event opens, as shown below. Note: Click is the only event that a menu item can respond to.

  In thePlace mnuFileNew_Click event, place the code you want to execute when the user clicks the New menu item. Since this is just a demo, we will place a simple MsgBox statement in the event procedure: 

MsgBox "Code for 'New' goes here.", vbInformation, "Menu Demo"

17. Code similar MsgBox statements for the Open, Save, Save As, and Print menu items:

 

Private Sub mnuFileOpen_Click() 

MsgBox "Code for 'Open' goes here.", vbInformation, "Menu Demo"

End Sub

 Private Sub mnuFileSave_Click() 

MsgBox "Code for 'Save' goes here.", vbInformation, "Menu Demo"

 End Sub

 Private Sub mnuFileSaveAs_Click() 

MsgBox "Code for 'Save As' goes here.", vbInformation, "Menu Demo"

End Sub

 Private Sub mnuFilePrint_Click()

 MsgBox "Code for 'Print' goes here.", vbInformation, "Menu Demo"

 End Sub

 

18. For the Exit menu item Click event, code the statement Unload Me.

 

Private Sub mnuFileExit_Click()

 Unload Me

SMCET / CSE Department

Page 64: DBMS Lab Manual

CS1256 – DBMS Lab

End Sub

 

19. For the About menu item Click event, code as shown below:

 

Private Sub mnuHelpAbout_Click()

MsgBox "Menu Demo" & vbCrLf _

& "Copyright " & Chr$(169) & " 2004 thevbprogrammer.com", , _

"About"

End Sub

20. Run the program. Note how the code executes when you click on the various menu items. Also test the use of the access keys (e.g., Alt+F, N) and shortcut keys (e.g., Ctrl-O).

  21. Save the program and exit VB.

OUTPUT:

SMCET / CSE Department

Page 65: DBMS Lab Manual

CS1256 – DBMS Lab

SMCET / CSE Department

Page 66: DBMS Lab Manual

CS1256 – DBMS Lab

RESULT:

Thus the menus can be designed in oracle under windows.

Ex-no-10 REPORTS

DESCRIPTION:

Specifically, this will involve: • Using the Data Model Wizard • Using the Layout Editor to customize the report

Data Model Wizard:

The Entity Data Model Wizard is used to generate an .edmx file. For more information, see .edmx File Overview (Entity Framework). The Entity Data Model Wizard allows you to create a model from an existing database, or to generate an empty model.

The Entity Data Model Wizard starts after you add an ADO.NET Entity Data Model, item template to your project. The Entity Data Model Wizard then launches the ADO.NET Entity Data Model Designer (Entity Designer) after it finishes generating an .edmx file.

The Entity Data Model Wizard guides you through the following steps:

1. Choose Model Contents

By selecting Generate from database, you can generate an .edmx file from an existing database. In the next steps, the Entity Data Model Wizard will guide you through selecting a data source, database, and database objects to include in the conceptual model.

SMCET / CSE Department

Page 67: DBMS Lab Manual

CS1256 – DBMS Lab

By selecting Empty model, you can add an .edmx file that contains empty conceptual model, storage model, and mapping sections to your project. Select this option if you plan to use the Entity Designer to build your conceptual model and later generate a database that supports the model. For more information, see How to: Generate a Database from a Conceptual Model (Entity Data Model Tools).

2. Choose Your Data Connection

You can select an existing connection from the drop-down list of connections, or click New Database Connection to open the Connection Properties dialog box and create a new database connection.

3. Choose Your Database Objects

You can select tables, views, and stored procedures to include in the .edmx file.

Beginning with Visual Studio 2010, the Choose Your Database Objects dialog box also allows you to perform the following customizations:

o Apply English-language rules for singulars and plurals to entity, entity set, and navigation property names when the .edmx file is generated.

o Include foreign key columns as properties on entity types.

For more information, see Choose Your Database Objects Dialog Box (Entity Data Model Wizard).

Upon closing, the Entity Data Model Wizard creates an .edmx file that contains the model information. The .edmx file is used by the Entity Designer, which enables you to view and edit the conceptual model and mappings graphically.

The Entity Data Model Wizard also creates a source code file that contains the classes that are generated from the CSDL content of the .edmx file. The source code file is automatically generated and is updated when the .edmx file changes.

SMCET / CSE Department

Page 68: DBMS Lab Manual

CS1256 – DBMS Lab

Create a report based on the existing student table

AIM:

To create reports based on the existing STUDENT table.

Steps for Creating a report (based on STUDENT table)

To log on to Oracle Reports Builder, go to Start > Programs > OracleDeveloper Suite > Reports Developer > Reports Builder

We will see the welcome screen. To create a new report, Select “Use the Report Wizard” and click OK.

We will now see the Welcome to the Report Wizard Window. Click Next to proceed.

The Report type page appears, which allows us to specify how the report output appears in the Reports Builder environment. Select "Create both Web and Paper Layout" and then click Next.

SMCET / CSE Department

Page 69: DBMS Lab Manual

CS1256 – DBMS Lab

The Style page appears, which allows us to specify the report title and style. Type “Student Information” in the Title box, and select the "Tabular" option, and then click Next.

The Data source page appears, which allows us to specify the source of the report data. Select "SQL Query", and then click Next.

The Data page appears, which allows to type a SQL query. Type the following query to retrieve the report data fields, and then click Next.

Select * from STUDENT;

Once we click next, the connect window will appear. Type username, password and database to connect to the database, then click “Connect”.

Username: systemPassword: oracleDatabase: XE

The Fields page appears, showing the fields the query returns. The Fields page allows to select one or more fields in the Available Fields list to display in the report. Click the “>>” button to select all query fields for the report. Click Next.

The Totals page appears, allowing you to specify one or more fields for which we might want to calculate a total.

Select "std_id" in the available fields, then click "Count>" to count the number of students.

Select "mark1" in the available fields, then click "Minimum>" to calculate the minimum marks.

Select "mark1" in the available fields, then click "Maximum>" to calculate the maximum marks. And so on.

The Labels page appears, which allows to specify the report labels and field widths. Modify the field labels, and then click "Next".

The template page appears, which allows to select a report template to define the characteristics of the report appearance. Select the "Predefined template" option and choose a template, then click Next.

We will now see the Congratulations window. Click on Finish.

The report appears in the Report Editor - Page Design window. Save the report.

Click “Page Layout” icon on the toolbar to format the layout of the report

SMCET / CSE Department

Page 70: DBMS Lab Manual

CS1256 – DBMS Lab

SMCET / CSE Department

Page 71: DBMS Lab Manual

CS1256 – DBMS Lab

RESULT:

Thus the report can be generated for the existing database table.

SMCET / CSE Department

Page 72: DBMS Lab Manual

CS1256 – DBMS Lab

DO’S

Leave your belongings in the racks outside the Lab.

Maintain proper dress code (ID card).

Sign in the Login Register.

Before commencing experiment, ensure that the systems and peripherals

etc., are in correct order.

Take the Assigned system.

Maintain silence inside the Lab.

While leaving the lab chairs should be properly arranged.

Shutdown the system properly.

DON’T’S

Don’t wear shoes / chappals inside the Lab.

Don’t delete folder/files, unless instructed.

Don’t tamper the stickers meant for the system identification.

Don’t adjust monitor settings / Position.

Don’t use internet during Lab hours without the concerned faculty’s

knowledge.

Don’t allow other students to sit near you or to chat with you.

Don’t allow other students to operate your systems.

Vision

To equip our students to face the future challenges in

technological developments and deliver the bounties of frontier

knowledge for the benefit of human kind.

Mission

To facilitate students to learn and imbibe discipline, culture and

spirituality, besides encouraging our students to acquire latest

SMCET / CSE Department

Page 73: DBMS Lab Manual

CS1256 – DBMS Lab

technological developments and to facilitate the college to emerge as a

centre of excellence which produces dedicated Engineers and intellectual

leaders.

ST. MICHAEL GROUP OF INSTITUTIONS

St. Michael College of Engineering and Technology

Kalayarkoil

Fatima Michael College of Engineering and Technology

Madurai

Michael Institute of Management

Madurai

St. Michael Polytechnic College

Kalayarkoil

Roseline College of Education

Sivagangai

St. Michael Teacher Training Institute

Kalayarkoil

Sahayamatha Teacher Training Institute

Kalayarkoil

Roseline Teacher Training Institute

Sivagangai

Fatima Teacher Training Institute

Ramanathapuram

St. Michael Matriculation Higher Secondary School

Madurai

St. Michael Matriculation School

Sivagangai

Pope John Paul II Middle School

Ramanathapuram

SMCET / CSE Department

College Address

St.Santhiagapar Nagar,Kalayarkoil-630 551Sivagangai District, Tamilnadu.

Ph:(04575)-232009,232010

Mobile:098421 44567, 099427 96745, 099427 96744

E-mail:[email protected]

Visit: www.smcet.edu.in

Page 74: DBMS Lab Manual

CS1256 – DBMS Lab

SMCET / CSE Department