Dbms Lab Spiral
Dbms Lab Spiral
NO:1
STUDY OF DDL AND DML COMMANDS
DATE:
AIM:
To execute the Data Definition Language (DDL) commands and Data Manipulation
Language (DML) Commands.
DATA DEFINITION LANGUAGE
1. Creating a Table:
Create command is used to create a table in the database.
Syntax:
create table tablename (column 1 datatype 1, …., column n datatype n);
2. DESC COMMAND
This command is used to view the structure of the table.
Syntax:
desc tablename; (or)describe tablename;
3. ALTERING A TABLE
a. The structure of the table can be changed using this command like add new column,
change the width of a datatype, change the datatype of a column.
a. Modify
Syntax:
alter table tablename modify (column datatype, …);
b. Add / Drop
Syntax:
alter table tablename add (column datatype, …);
alter table tablename drop columnname;
4. TRUNCATING A TABLE
This command is used to delete all records stored in a table, but the
structure of the table is retained.
Syntax:
truncate table tablename;
5. DROPPING A TABLE
This command is used to remove a table from the database.
Syntax: drop table tablename;
1. INSERT COMMANDS
1. Insert a row with values for columns in a table.
This insert command is used to add rows to a table in the database.
Syntax:
insert into tablename values (value1, value2,……, value n);
insert into tablename(column 1,column 2) values(value 1,value 2);
2. Insert a large number of rows.
This insert command is used to add multiple rows to a table in the
Database in user friendly manner..
Syntax:
insert into tablename values (&column1, &column 2,……, &column n);
1
2. SELECT COMMANDS
2
OUTPUT
1. Create EMP table.
SQL>create table emp(empno number(4), ename varchar2(10), job varchar2(9), mgr
number(4), hiredate date, sal number(7,2), comm Number(7,2), deptno number(3), age
number(3), esal number(10));
2.Get the description EMP table.
Name Null? Type
EMPNO NUMBER(4)
ENAME VARCHAR2(10)
JOB VARCHAR2(9)
MGR NUMBER(4)
HIREDATE DATE
SAL NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NUMBER(3)
AGE NUMBER(3)
ESAL NUMBER(10)
3. Create DEPT table.
SQL>create table dept(deptno number(2) , dname varchar2(14), loc varchar2(13));
4.Get the description DEPT table.
SQL>desc dept;
Name Null? Type
DEPTNO NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)
5. Insert records into EMP & DEPT.
SQL> insert into emp values(&empno,’&ename’,’&job’,&mgr,’&date’,&sal,&comm.
deptno,&age, &esal);
SQL>insert into dept values(&deptno,’&dname’,’&loc’);
6. List all employee details.
SQL>select * from emp;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO AGE ESAL
3
ENAME
SMITH
JONES
9. List the name and salary of the employees whose salary is more than 1000.
SQL >select ename,sal from emp where sal>1000;
ENAME SAL
ALLEN 1600
WARD 1250
JONES 2975
BLAKE 2850
10. List the names of employees who are managers
SQL >select ename from emp where job = ‘MANAGER’
ENAME
JONES
BLAKE
11. List the different jobs available in employee table.
SQL>select distinct job from emp;
JOB
CLERK
MANAGER
SALESMAN
3 rows selected.
12. Alter emp table to add city column which is of string data type.
SQL>Alter table emp add city varchar2(20);
Table altered
13. Alter dept table to change loc column size as 20.
SQL>Alter table dept modify city varchar2(30);
Table altered
14. Update the salary of the employee as 2500 whose job as manager.
SQL>update emp set esal=2500 where job =‘manager’;
15. Delete the employee’s record whose salary is above 2800.
SQL>delete emp where esal>2800;
1 row deleted.
16. Change the name of emp table as EMPLOYEE.
SQL>rename emp to employee;
Table renamed.
17. Delete all records from dept table.
SQL>truncate table dept;
Table truncated.
18. Delete dept table.
SQL>drop table dept;
Table dropped.
4
RESULT:
Thus the DDL and DML commands are executed successfully.
5
EX.NO:2 STUDY OF TRANSACTION AND DATA CONTROL
LANGUAGES
DATE:
AIM:
To study Data Control Language statements and Transactional Control Language
statements.
ILLUSTRATION / PROCEDURE:
TRANSACTION CONTROL LANGUAGE:
All changes made to the database is defined as a transaction. It is logical unit of work.
The transaction can made permanent to a database only they are committed. A transaction
begins with an executable SQL statement.
The two transaction control commands are:
1. COMMIT
2. SAVEPOINT
3. ROLLBACK
1. COMMIT:
This command is used to make all transaction changes permanent to the database.
Syntax:
COMMIT ;
2. SAVEPOINT:
It is only a marker. Save point are used to divide a lengthy transaction into smaller ones.
Syntax:
Savepoint id;
3. ROLLBACK:
Rollback commands undo all the changes made in the current transaction.
Syntax:
a. Rollback;
b. Rollback to Savepoint id1;
The first one will rollback (undo) the entire transaction and the last one will undo all changes
made after the creation of the save point id1.
DATA CONTROL LANGUAGE:
Data control language, the previous user with privileges commands the database
object (table, view, etc) of a user can’t be accessed by another user without the permission of
a user. The owner can allow other user to access his object as per his diversion the permission
given by a user to another is called privilege.
6
The Data Control Commands are:
i. GRANT Privilege
ii. REVOKE Privilege
Types of Privilege:
A permission granted to execute the various data definition command like Create
Table, Create Sequence, create session are called System Privilege.
Granting System Privilege:
Grant Command is used to give System Privilege to an oracle user.
Syntax:
GRANT system privilege TO user;
Object Privilege:
An Object Privilege enables a user to execute some commands on the database object
like table view sequence etc.
• Object privileges vary from object to object.
• An owner has all the privileges on the object.
• An owner can give specific privileges on that owner’s object.
Some of the object privileges are
i. Alter
ii. Insert
iii. Update
iv. Delete
v. Select
Syntax:
GRANT object_priv [(columns)]
ON object
TO {user|role|PUBLIC}
[WITH GRANT OPTION];
object_priv -- is an object privilege to be granted
ALL --specifies all object privileges
columns --specifies the column from a table or view on which privileges are
granted
ON object -- is the object on which the privileges are granted
TO --identifies to whom the privilege is granted
PUBLIC --grants object privileges to all users
WITH GRANT OPTION --allows the grantee to grant the object privileges to other users and
roles.
Example:
• Grant query privileges on the EMPLOYEES table.
GRANT select ON employees TO itc20,itc30;
7
Grant succeeded.
• Grant privileges to update specific columns to users and roles.
GRANT update (department_name, location_id) ON departments
TO itc43, itc50;
Grant succeeded.
Give a user authority to pass along privileges.
GRANT select, insert ON departments TO itc45 WITH GRANT OPTION;
Grant succeeded.
Revoking the permission:
Permission granted to a user can also be taken back by the granter. This can be done
by the REVOKE command.
• Privileges granted to others through the WITH GRANT OPTION clause are also
revoked.
Syntax:
REVOKE {privilege [, privilege...]|ALL}
ON object
FROM {user[, user...]|role|PUBLIC}
[CASCADE CONSTRAINTS];
Example:
REVOKE select, insert ON departments FROM itc20;
Revoke succeeded.
OUTPUT :
TCL
SQL> desc stud;
Name Null? Type
SNO NUMBER(3)
SNAME VARCHAR2(10)
BRANCH VARCHAR2(4)
SQL> insert into stud values(01,'Arun','cse');
1 row created.
SQL> insert into stud values(02,'babu','IT');
1 row created.
SQL> commit;
Commit complete.
SQL> select * from stud;
SNO SNAME BRAN
8
1 Arun cse
2 babu IT
SQL> insert into stud values(03,'chitra','IT');
1 row created.
SQL> select * from stud;
SNO SNAME BRAN
1 Arun cse
2 babu IT
3 chitra IT
SQL> rollback;
Rollback complete.
SQL> select * from stud;
SNO SNAME BRAN
1 Arun cse
2 babu IT
SQL> savepoint s1;
Savepoint created.
SQL> insert into stud values(04,'Devi','CSE');
1 row created.
SQL> select * from stud;
SNO SNAME BRAN
1 Arun cse
2 babu IT
4 Devi CSE
SQL> rollback to s1;
Rollback complete.
SQL> select * from stud;
SNO SNAME BRAN
1 Arun cse
2 babu IT
9
DCL
User it2a40:
SQL> grant all on student to it2a36;
Grant succeeded.
User it2a36:
SQL> select * from it2a40.student;
ROLL_NO NAME DEPT SEM1 SEM2 SEM3
4 chitra it 88.5 90 92
1 alex ece 92.3 90.5 89.3
2 bala ece 88.2 85 89.3
3 booba it 91.1 85 93
SQL> alter table it2a40.student add(avg number(10,3));
Table altered.
SQL> update it2a40.student set avg=91.2 where roll_no=1;
1 row updated.
SQL> update it2a40.student set avg=88.5 where roll_no=2;
1 row updated.
10
SQL> update it2a40.student set avg=89.9 where roll_no=3;
1 row updated.
SQL> update it2a40.student set avg=90.2 where roll_no=4;
1 row updated.
SQL> select * from it2a40.student;
ROLL_NO NAME DEPT SEM1 SEM2 SEM3 AVG
User it2a40:
SQL> revoke delete on student from it2a36;
Revoke succeeded.
User it2a36:
SQL> delete from it2a40.student where roll_no=2;
delete from it2a40.student where roll_no=2
ERROR at line 1:
ORA-00942: table or view does not exist
User it2a40:
SQL> revoke all on student from it2a36;
Revoke succeeded.
User it2a36:
SQL> select * from it2a40.student;
select * from it2a40.student
User it2a40:
11
SQL> grant select on student to it2a36;
Grant succeeded.
User - it2a36:
SQL> select * from it2a40.student;
ROLL_NO NAME DEPT SEM1 SEM2 SEM3 AVG
RESULT:
Thus the study of DCL commands and TCL commands was performed successfully.
12
EX.NO:3 DATABASE QUERYING-SIMPLE QUERIES, NESTED QUERIES,
DATE:
SUB QUERIES AND JOINS
AIM:
To query simple, nested, sub queries and joins
ILLUSTRATION / PROCEDURE:
SET OPERATIONS:
The SET operators combine the results of two or more component queries into one
result. Queries containing SET operators are called compound queries. Some of set operators
are,
UNION - Rows of first query plus rows of second query
UNION ALL - Rows of first query plus rows of second query, including all duplicates
INTERSECT – common rows from all queries
MINUS - All distinct rows that are selected by the first SELECT statement and not selected
in the second SELECT statement
Syntax:
select query set operator select query
JOINS:
An SQL join clause combines records from two or more tables in a database. It
creates a set that can be saved as a table or used as is. A JOIN is a means for combining fields
from two tables by using values common to each. ANSI standard SQL specifies four types of
Joins: INNER, OUTER, LEFT, and RIGHT. As a special case, a table (base table, view, or joined
13
column values for each matched pair of rows of A and B are combined into a result row. The
result of the join can be defined as the outcome of first taking the Cartesian product (or Cross
join) of all records in the tables (combining every record in table A with every record in table
B)—then return all records which satisfy the join predicate. Inner join is further classified as
equi-joins, as natural joins, or as cross-joins
Syntax:
Explicit Notation:
Select * from table name1 inner join table name2 on table1.fieldname=table2.fieldname;
Select * from table1 inner join table2 using(fieldname);
Implicit Notation
Select * from table1, table2 where table1.fieldname=table2.fieldname;
Equi Join
An equi-join is a specific type of comparator-based join, or theta join that uses only
equality comparisons in the join-predicate. Using other comparison operators (such as <)
disqualifies a join as an equi-join. The query shown above has already provided an example
of an equi-join:
Syntax:
Explicit Notation:
Select * from table1 join table2 on table1.fieldname=table2.fieldname;
Natural join
A natural join offers a further specialization of equi-joins. The join predicate arises
implicitly by comparing all columns in both tables that have the same column-names in the
joined tables. The resulting joined table contains only one column for each pair of equally-
named columns
Explicit Notation:
Select * from table1 natural join table2 on table1.fieldname=table2.fieldname;
Cross join
Cross Join returns the Cartesian product of rows from tables in the join. In other
words, it will produce rows which combine each row from the first table with each row from
the second table.
Explicit Notation:
Select * from table1 cross join table2 ;
Implicit Notation
Select * from table1,table2;
14
Outer joins
An outer join does not require each record in the two joined tables to have a matching
record. The joined table retains each record—even if no other matching record exists. Outer
joins subdivide further into left outer joins, right outer joins, and full outer joins, depending
on which table(s) one retains the rows from (left, right, or both).
The result of a left outer join (or simply left join) for table A and B always contains all
records of the "left" table (A), even if the join-condition does not find any matching record in
the "right" table (B). This means that a left outer join returns all the values from the left table,
plus matched values from the right table (or NULL in case of no matching join predicate).
Explicit Notation:
Select * from table1 left outer join table2 on table1.fieldname=table2.fieldname
Implicit Notation
SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column =
table2.column (+);
A right outer join (or right join) closely resembles a left outer join, except with the
treatment of the tables reversed. Every row from the "right" table (B) will appear in the
joined table at least once. If no matching row from the "left" table (A) exists, NULL will
appear in columns from A for those records that have no match in B.
Explicit Notation:
Select * from table1 right outer join table2 on table1.fieldname=table2.fieldname
Implicit Notation
Conceptually, a full outer join combines the effect of applying both left and right outer
joins. Where records in the FULL OUTER JOINed tables do not match, the result set will
have NULL values for every column of the table that lacks a matching row.
15
Explicit Notation:
Select * from table1 full outer join table2 on table1.fieldname=table2.fieldname
Self-join
A self-join is joining a table to itself means each row of the table is combined with
itself and with every other row of the table. The self join is viewed as join of two copies of
the same table.
SET OPERATIONS
1. Display the different designation in department 20 and 30.
SQL> select designation from emp where deptno=20
union
select designation from emp where deptno=30;
SQL> select designation from emp where deptno=20 union all select designation from emp
where deptno=30;
2. List the jobs common to department 20 and 30.
SQL> select designation from emp where deptno=20 intersect select designation from emp
where deptno=30;
3. List the jobs unique to department 20.
SQL> select designation from emp where deptno=20 minus select designation from emp
where deptno=10 minus select designation from emp where deptno=30;
(Or)
SQL> select designation from emp where deptno=20 minus select designation from emp
where deptno in (10,30);
JOINS:
Tables:
SQL> create table two(deptno number(4) primary key,deptname varchar(10));
Table created.
SQL> create table one(name varchar(10),deptno references two(deptno));
Table created.
Insert these values into table one and table two
SQL> select * from one;
NAME DEPTNO
anand 31
babu 32
chitra 32
3 rows selected.
SQL> select * from two;
DEPTNO DEPTNAME
31 sales
32 enggg
Inner join
i.SQL> select * from one, two where one.deptno=two.deptno;
ii.SQL> select * from one inner join two on one.deptno=two.deptno
16
Equi join
i.SQL> select * from one join two on one.deptno=two.deptno;
ii.SQL> select * from one inner join two using(deptno);
Natural join
i.SQL> select * from one natural join two;
Cross Join
i.SQL> select * from one cross join two;
ii.SQL> select * from one,two;
Left outer join
i. SQL> select * from one left outer join two on one.deptno=two.deptno;
ii. SQL> select * from one,two where one.deptno=two.deptno(+);
Right outer join
i. SQL> select * from one right outer join two on one.deptno=two.deptno;
ii. SQL> select * from one,two where one.deptno(+)=two.deptno;
Full outer join
i. SQL> select * from one full outer join two on one.deptno=two.deptno;
Self join
SQL> create table selfj(empno number(5),ename varchar(7),mgr number(5));
Table created.
Insert values for table selfj
SQL> select * from selfj;
EMPNO ENAME MGR
7839 kalyan
7566 jones 7839
7876 anand 7788
7934 babu 7782
7777 raja 7934
List out the names of manager with the employee record.
SQL> select worker.ename,manager.ename from selfj worker,selfj manager where
worker.mgr=manager.empno;
SUBQUERIES
A subquery is a SELECT statement that is embedded in a clause of another SELECT
statement. You can build powerful statements out of simple ones by using subqueries. A
Common use of subquery is to perform tests for
1. set memberships,
2.setcomparisons
3.set cardinality.
➢ The subquery (inner query) executes once before the main query.
➢ The result of the subquery is used by the main query (outer query).
➢ A subquery must be enclosed in parentheses.
➢ Place the subquery on the right side of the comparison condition for readability.
Note: Comparison conditions fall into two classes:
1. single-row operators (>, =, >=, <, <>, <=) and
17
2. multiple-row operators (IN, ANY, ALL).
The subquery is often referred to as a nested SELECT, sub-SELECT, or inner
SELECT statement. The subquery generally executes first, and its output is used to complete
the query condition for the main or outer query.
Subquery Syntax
SELECT select_list FROM table WHERE expr operator (SELECT select_list FROM
table);
Types of Subqueries
• Single-row subqueries: Queries that return only one row from the inner SELECT statement
• Multiple-row subqueries: Queries that return more than one row from the inner SELECT
Statement.
A single-row subquery
Subqueries that returns one row from the inner SELECT statement. This type of
subquery uses a single-row operator.
Multiple-Row Subqueries
Subqueries that return more than one row are called multiple-row subqueries. You use
a multiple-row operator, instead of a single-row operator, with a multiple-row subquery. The
multiple-row operator expects one or more values.
QUERIES:
1. Select loanno, branchname, amount from loan where amount=(select min(amount) from
loan)
18
2. Select sname, rollno, dept, marks from student where marks=(select min(marks) from
student group by dept;
3. Select sname, rollno, dept, marks from student where marks IN (select min(marks) from
student group by dept)
4. Select sname, rollno, dept, marks from student where marks NOT IN (select min(marks)
from student)
5. select * from loan where amount > ANY (select amount from loan where
branchname=’chennai’)
6. select * from loan where amount > ALL (select amount from loan where
branchname=’chennai’)
7. select * from loan where EXISTS (select * from borrower where
loan.loanno=borrower.loanno)
8. select * from loan where NOTEXISTS (select * from borrower where
loan.loanno=borrower.loanno)
9. select * from loan where EXCEPT (select * from borrower where
loan.loanno=borrower.loanno)
10. Find all customers who have both an account and a loan at the bank.
Select distinct cusname from customer where cusname IN (select cusname from depositor)
11. Find all customers who have a loan at the bank but do not have an account at the
bank.
Select distinct cusname from customer where cusname NOT IN (select cusname from
depositor)
12. Find the loanno,amount,branchname who have get second maximum loan amount
at the bank.
Select loanno, branchname, max(amount) from loan where amount<=(select max(amount)
from loan )
13. Write a query that displays the roll numbers and student names of all student who
studied in a department with any student whose name contains a S.
SELECT rollno, sname FROM student WHERE dept IN (SELECT dept FROM student
WHERE sname like ’%s%’);
14. List the employee names whose salary is greater than the lowest salary of an
employee belonging to department number 30.
SQL> select ename from emp
where sal>any
(select sal from emp where deptno=30);
15. List the employee details of those employees whose salary is greater than any of the
salesman.
SQL> select empno, ename, sal from emp where sal>any(
select sal from emp where job='asstprof');
16. List the employee names whose salary is greater than the highest salary of an
employee belonging to department number 20.
SQL> select ename from emp
where sal>all(select sal from emp where deptno=20);
19
RESULT:
Thus the database querying for simple, nested, sub queries and joins were performed
successfully.
20
EX.NO:4
mmmmmm
DATE:
CREATING INDEX AND DROP INDEX
AIM :
To write queries on views and indexes.
PROCEDURE :
A view is nothing more than a SQL statement that is stored in the database with an associated name.
A view is actually a composition of a table in the form of a predefined SQL query.
A view can contain all rows of a table or select rows from a table. A view can be created from one
or many tables which depends on the written SQL query to create a view.
Views, which are a type of virtual tables allow users to do the following −Structure data in a way
that users or classes of users find natural or intuitive.Restrict access to the data in such a way that a user
can see and (sometimes) modify exactly what they need and no more.Summarize data from various tables
which can be used to generate reports.
TABLE CREATION
SQL>create table customer(cname varchar(20),street
varchar(20)); SQL>insert into customer values(‘ajay’,’north
street’); SQL>insert into customer values(‘godson’,’east
street’); SQL>insert into customer values(‘madhan’,’church
street’); SQL>insert into customer values(‘vijay’,’west street’);
SQL>select * from customer;
1. Create a view from single table containing all columns from the base
table. SQL>create view view1 as select * from customer;
SQL>select * from view1;
2. Create a view from single table with selected columns.
SQL>create view view2 as select cname,street from
customer; SQL>select * from view2;
TABLE CREATION
SQL>create table depositor(accno number,brname varchar(20));
SQL>insert into depositor values(101,’nazareth’);
SQL>insert into depositor values(102,’sattankulam’);
SQL>insert into depositor values(103,’mudhalur’);
21
SQL>select * from depositor;
SQL>create table account(accno number,cname varchar(20));
SQL>insert into account values(101,’ajay’);
SQL>insert into account values(102,’godson’);
SQL>insert into account values(105,’darwin’);
SQL>select * from account;
3. Create a view from two tables with selected columns.
SQL>create view xyz as select brname,cname from depositor d, account a where d.accno=a.accno;
SQL>select * from xyz;
TABLE CREATION
SQL>create table borrower(loanno number,brname varchar(20));
SQL>insert into borrower values(1001,’nazareth’);
SQL>insert into borrower values(1002,’sattankulam’);
SQL>insert into borrower values(1003,’mudhalur’);
SQL>select * from borrower;
SQL>create table loan(loanno number,cname varchar(20));
SQL>insert into loan values(1001,’ajay’);
SQL>insert into loan values(1002,’godson’);
SQL>insert into loan values(1005,’darwin’);
SQL>select * from account;
4. Create a view from two or more tables with union operator.
SQL> create view lmn as select brname,cname from depositor,account where depositor.accno=
account.accno union select brname,cname from borrower,loan where borrower.loanno=loan.loanno;
SQL> select * from lmn;
5. Create a view from another view.
SQL>create view view3 as select cname from xyz where brname=’nazareth’;
6. Check all DML commands with above views.
SQL> insert into view1 values (‘darwin’,’church
street’); 1 row created;
SQL>update view1 set street=’main road’ where cname like ‘ajay’;
1 row updated.
Note: Update command does not works for all queries on views.
SQL>delete from view1 where cname like ‘godson’;
1 row deleted.
22
7. Drop view which you
generated. SQL>drop
view view1;
View dropped;
23
Removing an Index: Remove an index from the data dictionary by using the DROP INDEX command.
Syntax :
DROP INDEX
index;
DROP INDEX
sp1;
RESULT :
Thus the program to implement view and indexes was studied and executed successfully.
24
EX.NO:5 IMPLICIT AND EXPLICIT CURSORS
DATE:
AIM:
PROCEDURE:
Cursor in SQL
A cursor is a temporary work area created in the system memory when a SQL statement is executed. A cursor
contains information on a select statement and the rows of data accessed by it. This temporary work area is
used to store the data retrieved from the database, and manipulate this data. A cursor can hold more than one
row, but can process only one row at a time. The set of rows the cursor holds is called the active set.
Cursor uses
The major function of a cursor is to retrieve data, one row at a time, from a result set. Cursors are used when
the user needs to update records in a singleton fashion or in a row by row manner, in a database table.
Implicit cursors
These are created by default when DML statements like, INSERT, UPDATE, and DELETE statements
are executed. They are also created when a SELECT statement that returns just one row is executed.
Explicit cursors
They must be created when you are executing a SELECT statement that returns more than one row.
Even though the cursor stores multiple records, only one record can be processed at a time, which is
called as current row. When you fetch a row the current row position moves to next row.
IMPLICIT CURSORS:
%FOUND
%NOTFOUND
%ROWCOUNT
%ISOPEN
25
Create and insert the values for customers table:
Create Procedure
DECLARE
total_rows
number(2); BEGIN
UPDATE customers
IF sql%notfound THEN
dbms_output.put_line('no customers
updated');
total_rows := sql
%rowcount;
END;
Outp
ut:
Execute Query
26
Explicit Cursors
Steps:
c_id customers.id%type;
c_name customers.name
%type; c_addr
customers.address%type
; CURSOR c_customers
is
SELECT id, name, address FROM
customers;
BEGIN OPEN
c_customers
; LOOP
FETCH c_customers into c_id,
c_name, c_addr; EXIT WHEN
c_customers
%notfound;
dbms_output.put_
line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE
c_customers;
END;
/
27
OUTPUT:
RESULT:
Data base created and applied Implicit and Explicit Cursors in a database.
28
EX.NO:6
PROCEDURES AND FUNCTIONS
DATE:
AIM:
To create a database and apply Procedures and Functions.
CREATING A PROCEDURE:
In MySQL, a procedure can also be created. A procedure can return one or more than one value through
parameters or may not return at all. The procedure can be used in SQL queries.
Syntax
CREATE PROCEDURE procedure_name[ (parameter datatype [, parameter
datatype]) ] BEGIN
Declaration_secti on
Executable_secti on
END;
Parameter
EXAMPLE:
create database
db1; use db1;
CREATE TABLE Student_Details(Stu_ID int, Name varchar(255), Address
varchar(255)); Insert into Student_Details values(1,'Ramesh','Erode');
29
SELECT * FROM Student_Details;
END$$
call get_student();
OUTPUT:
1 Ramesh Erode
11 Arun Erode
21 Kumar Tirupur
31 Prakash Erode
FUNCTIONS:
Creating a function
In MySQL, Function can also be created. A function always returns a value using the return
statement. The function can be used in SQL queries.
Syntax
CREATE FUNCTION function_name [ (parameter datatype [, parameter
datatype]) ] RETURNS return_datatype
BEGIN
Declaration_secti
on
Executable_secti
on END;
Parameter:
30
EXAMPLE:
create database
db1; use db1;
SET GLOBAL
log_bin_trust_function_creators=1;
DELIMITER $$
CREATE FUNCTION mark_check(Stu_ID int, Name varchar(20), Marks int, Age
int) RETURNS text
BEGIN
IF Marks>250 THEN
insert into Student_Marks (Stu_ID, Name, Marks, Age) values (Stu_ID, Name, Marks,
Age); RETURN 'Inserted Successfully';
else
RETURN 'Sorry Marks Less than
250'; END IF;
END;
$$
SELECT
mark_check(4,"Kamalesh",220,25);
SELECT
mark_check(4,"Kamalesh",275,25);
select* from Student_Marks;
31
OUTPUT:
1 Ramesh 280 24
2 Suresh 320 23
3 Kamesh 300 25
2 Suresh 320 23
3 Kamesh 300 25
4 Kamalesh 275 25
RESULT:
Database created successfully. Procedures and Functions are executed successfully.
32
EX.NO:7
EXECUTING TRIGGERS
DATE:
AIM:
PROCEDURE:
TRIGGER
In MySQL, trigger can also be created. There are 6 type of triggers that can be made they
are:-
• After/Before insert
• After/Before update
• After/Before delete
Syntax:
CREATE TRIGGER
trigger_name
AFTER/BEFORE INSERT
ON table_name
FOR EACH ROW BEGIN
--variable declarations
--trigger
code END;
Parameter:
trigger_name: name of the trigger to be created.
EXAMPLE:
Step 1: Create a table, for example, student and insert the records.
create table student(id int, name varchar(20));
insert into student values(1,
"Ramesh"); insert into student
values(2, "Suresh");
33
insert into student values(3, "Kamesh");
Step 2: Create another table, for example, student1 and don't insert the records.
create table student1(s_id int auto_increment PRIMARY KEY, id int, action varchar(20), rdate
TRIGGER student_insert
FOR EACH
ROW BEGIN
NOW()); END;
//
select * from
student1;
OUTPUT:
1 Ramesh
2 Suresh
3 Kamesh
4 Kamalesh
RESULT:
34
EX.NO:8
EXECEPTION HANDLING
DATE:
AIM:
PROCEDURE:
PL / SQL Query:
DECLARE
a NUMBER;
b NUMBER;
c NUMBER;
BEGIN
a:=:a;
b:=:b; c:=a/b;
dbms_output.put_line('Result : '||c);
EXCEPTION
WHEN ZERO_DIVIDE
THEN RAISE_APPLICATION_
ERROR(-20003,'Invalid Input');
END;
/
Output1:
Output2:
Output 3:
35
PROGRAM-2: DUPLICATE VALUE EXCEPTION
TABLE CREATION:
QUERY:
(
CREATE TABLE employee (
eid INT PRIMARY KEY, ename VARCHAR(10),
age INT,
sal NUMBER
);
OUTPUT:
Table created .
PL / SQL Query:
DECLARE
eno NUMBER;
name VARCHAR2(10); age NUMBER;
sal NUMBER;
BEGIN
eno:=:eno;
name:=:name;
age:=:age; sal:=:sal;
END;
36
Input 1:
Submit
:ENO 1
:NAME KIRTHEESH
20
:AGE
45000
:SAL
Output 1
Input 2:
Submit
:ENO 1
:NAME RUPESH
25
:AGE
50000
:SAL
Output 2
Inserted
Statement processed.
:ENO 2
:NAME BALA
:AGE 20
:SAL 45000
Output 3
Query:
Select * from employee
Input 4
:ENO 3
SAI
:NAME
20
:AGE
45000
:SAL
RESULT:
Thus the PL/SQL statement that handles exceptions were successfully
executed and verified.
37
EX.NO:10
PL/SQL HOST BLOCK
DATE:
AIM:
To Study about PL/SQL block.
DESCRIPTION:
PL/SQL
PL/SQL stands for Procedural Language extension of SQL.
38
Exception Section
The Exception section of a PL/SQL Block starts with the reserved keyword
EXCEPTION. 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.
Every statement in the above three sections must end with a semicolon ; . PL/SQL
blocks can be nested within other PL/SQL blocks. Comments can be used to document code.
A Sample PL/SQL Block Looks like:
DECLARE
Variable declaration
BEGIN
Program Execution
EXCEPTION
Exception handling
END;
PL/SQL Block Structure:
DECLARE
v_variable VARCHAR2(5);
BEGIN
SELECT
column_name INTO
v_variable FROM
table_name;
EXCEPTION
WHEN exception_name THEN
...
END;
Block Types
ANONYOUMS
[DECLARE] BEGIN
s- anonyoums
statements
39
[EXCEPTION]
END;
1. Procedur
e PROCEDURE
name IS
BEGIN
--statements
[EXCEPTION]
END;
PROCEDURE name
2. Functio
n FUNCTION
name
RETURN
datatype IS
BEGIN
--statements
RETURN
value;
[EXCEPTIO
N] END;
RESULT:
Thus the PL/SQL host blocks are studied.
40