Вы находитесь на странице: 1из 27

DMBS Lab Manual

Data base Concepts

Data It is a set of facts and figures. It is like raw materials of data items with are numbers, alphabets and other symbols. Ex : 101, Ashok, MCA, 20000.00 etc. Information It is collection of meaningful and relevant data items. When data is processed we get information. Field or Column To prepare information, data items are organized in the form of fields. Ex : Rno Name Course Fee 101 Venu MCA 20000.00 102 Madhav MBA 20000.00 Record or Row A Record is a set Ex : Rno 101 102 of related fields which provide complete information. Name Venu Madhav Course MCA MBA Fee 20000.00 20000.00

Table Table is a collection of related records. Data is organized in a Table in the form of Rows and Columns. Ex : Rno Name Course Fee 101 Venu MCA 20000.00 102 Madhav MBA 20000.00 Data base It is a collection of relevant and meaningful data. Data base organize large amount of data systematically. It is also called collection of Tables which store data. Ex : School Data base, College Data base, Company Data base etc. Data base Management We perform many operations on the data. These are called Data operations. Ex : Insert Storing Data Select Displaying Data Update Modifying Data Delete Removing Data We also create Tables in the Data base. DBMS Data base Management Systems It is a software which help us to create, manage and maintain the Data base. It provides many tools to perform Data Operations and other transactions easily. It acts like a mediator between the Data base and the user. Ex : dBase, FoxPro, MS-Access, Oracle, SQL-Server.

SQL Structured Query Language (SQL) is a language that provides an interface to a RDBMS. It is called a data base language.

By P.Ashok

M.Tech (CSE)

SR Engineering College

DMBS Lab Manual

SQL statements performs all data base operations. It is a non procedural language. Combination of SQL statements is called a Query. Query is a request to the data base to perform an operation like displaying, inserting, updating and deleting data. 1. 2. 3. 4. 5. Components of SQL DDL Data Definition Language. DML Data Manipulation Language. DCL Data Control Language. TCL Transaction Control Language. DQL Data Query Language.

Data Definition Language (DDL) It provides commands to create, modify and delete data base objects like tables. Commands 1. Create 2. Alter 3. Describe 4. Truncate 5. Drop Data Manipulation Language (DML) It provides commands to modify the data in the table of a data base. Commands 1. Insert 2. Update 3. Delete Data Control Language (DCL) It provides commands to control data access of a table in the data base. Commands 1. Grant 2. Revoke Transaction Control Language (TCL) It provides commands to control data transaction take place in a session. Commands 1. Commit 2. Save point 3. Roll back Data Query Language (DQL) It provides commands to display data from a table in the data base. Commands Select

By P.Ashok

M.Tech (CSE)

SR Engineering College

DMBS Lab Manual

Week 1 Creation, altering and dropping of tables and inserting rows into a table (use constraints while creating tables) examples using SELECT command. Task 1: ER Model E-R (Entity-Relationship) Diagram is used to represents the relationship between the table. The symbols used in E-R diagrams are: SYMBOL 1. Rectangle PURPOSE Represent Entities entities in

2. Ellipse

Represent attributes.

3. Rambus (Diamond)

Represent Relationship Sets.

4. Arrow

Arrow represents flow structured analysis is a set of tools

BUS Entity: This entity having information about the buses like Bus Number, Source, Destination. Destination Source bustype

Starttime

BusNo

Bus

departuretime

PASSENGER Entity: This entity stores the passenger details like Passport Id, Name, Age, Gender and Address.

Ppno

Name

Age

Gender

Passenger

Address

Ticketno By P.Ashok SR Engineering College

M.Tech (CSE)

DMBS Lab Manual

TICKET Entity: A passenger can reserve a ticket for a particular bus on specified date and multiple seats also reserved. seats Amount BusNo

JourneyDate

Ticketno

Ticket

Task 2: Concept Design with ER Model The entity-relationship (E-R) data model is based on a perception of a real world that consists of a collection of basic objects, called entities, and of relationships among these objects. An entity is a thing or object in the real world that is distinguishable from other objects. For example, each person is an entity, and bank accounts can be considered as entities. Entities are described in a database by a set of attributes. For example, the attributes account-number and balance may describe one particular account in a bank, and they form attributes of the account entity set. A relationship is an association among several entities. The overall logical structure (schema) of a database can be expressed graphically by an E-R diagram, where Rectangles represent entity sets, Ellipses represent attributes, Diamonds represent relationships among entity sets, Lines link attributes to entity sets and entity sets to relationships.

By P.Ashok

M.Tech (CSE)

SR Engineering College

DMBS Lab Manual

Task 3: Relational Model The relational model uses a collection of tables to represent both data and the relationships among those data. Each table has multiple columns, and each column has a unique name. The relational model is an example of a record-based model. Record-based models are so named because the database is structured in fixed-format records of several types. Each table contains records of a particular type. Each record type defines a fixed number of fields, or attributes. The columns of the table correspond to the attributes of the record type. Bus BusNo 10 20 Source HNK WGL Destination HYD VZG BusType AC Non-AC StartTime 07:00:00 08:00:00 DepartureTime 10:00:00 20:00:00

Passenger Ppno 1 2 Name Venu Latha Age 25 21 M F Gender Address HNK WGL Ticketno 11 12

Ticket Ticketno 11 12 JourneyDate 10-01-2012 12-01-2012 Seats 2 1 Amount 200 250 BusNo 10 20

Task 4: Normalization Normalization is the process of efficiently organizing data in a database. There are two goals of the normalization process: eliminating redundant data (for example, storing the same data in more than one table) and ensuring data dependencies make sense (only storing related data in a table). Both of these are worthy goals as they reduce the amount of space a database consumes and ensure that data is logically stored. The Normal Forms The database community has developed a series of guidelines for ensuring that databases are normalized. These are referred to as normal forms and are numbered from one (the lowest form of normalization, referred to as first normal form or 1NF) through five (fifth normal form or 5NF). In practical applications, you'll often see 1NF, 2NF, and 3NF along with the occasional 4NF. First Normal Form (1NF) First normal form (1NF) sets the very basic rules for an organized database: Eliminate duplicative columns from the same table. Create separate tables for each group of related data and identify each row with a unique column or set of columns (the primary key).

By P.Ashok

M.Tech (CSE)

SR Engineering College

DMBS Lab Manual

Second Normal Form (2NF) Second normal form (2NF) further addresses the concept of removing duplicative data: Meet all the requirements of the first normal form. Remove subsets of data that apply to multiple rows of a table and place them in separate tables. Create relationships between these new tables and their predecessors through the use of foreign keys. Third Normal Form (3NF) Third normal form (3NF) goes one large step further: Meet all the requirements of the second normal form. Remove columns that are not dependent upon the primary key. Fourth Normal Form (4NF) Finally, fourth normal form (4NF) has one additional requirement: Meet all the requirements of the third normal form. A relation is in 4NF if it has no multi-valued dependencies. Passenger Ppno Name Age Gender Address

Ticket Ppno Tno

Task 5: Practicing DDL Commands in MySQL Creating Database create database roadwaytravels; Using Database use roadwaytravels; Creating Bus table create table bus(busno integer primary key, source varchar(20), destination varchar(20)); Modifying Bus table structure alter table bus add(bustype varchar(20),starttime time, departuretime time); Creating Ticket table create table ticket(ticketno integer primary key, journeydate date, seats integer, amount integer, busno integer references bus(busno)); Creating Passenger table create table passenger(ppno integer primary key, ticketno integer references ticket(ticketno), name varchar(20), age integer, gender varchar(1), adresss varchar(20));

By P.Ashok

M.Tech (CSE)

SR Engineering College

DMBS Lab Manual

Creating Reservation table create table reservation(pnrno integer primary key, ppno integer references passenger(ppno), status varchar(1)); Task 6: Practicing DML Commands in MySQL Insert data into Bus table insert into bus values(10,Hanamkonda,Hyderabad,NON-AC,07:00:00,10:00:00); insert into bus values(20,Hanamkonda,Karimnagar,NON-AC,08:00:00,09:00:00); insert into bus values(30,Hyderabad,Kurnool,AC,09:00,14:00:00); insert into bus values(40,Hyderabad,Bangalore,AC,02:00:00,14:00:00); insert into bus values(50,Hanamkonda,Bangalore,AC,02:00:00,18:00:00); Insert data into Ticket table insert into ticket values(1,10-01-12,2,100,10); insert into ticket values(2,11-01-12,3,150,20); insert into ticket values(3,12-01-12,1,50,30); insert into ticket values(4,13-01-12,2,100,10); insert into ticket values(5,14-01-12,3,150,50); Insert data into Passenger table insert into passenger values(100,1,Ramesh,45,M,Hanamkonda); insert into passenger values(101,2,Geetha,36,F,Hanamkonda); insert into passenger values(102,3,Ram,30,M,Hyderabad); insert into passenger values(103,4,Ravi,50,M,Hyderabad); insert into passenger values(104,5,Seetha,32,F,Hanamkonda);

By P.Ashok

M.Tech (CSE)

SR Engineering College

DMBS Lab Manual

Week 2 Queries (along with sub Queries) using ANY, ALL, IN, EXISTS, NOTEXISTS, UNION, INTERSET, MINUS. A). Querying in MySQL Operators Operators are special symbols which are used for calculations and comparisons on the data of a table. Ex : +, -, *, /, <, >, = There are 4 types operators. 1. Arithmetic Operators. 2. Relational or Comparison Operators. 3. Logical Operators. 4. Set Operators. Relational Operators 1) = Equal 2) != Not Equal 3) < Less than 4) <= Less than or Equal 5) > Greater than 6) >= Greater than or Equal 7) BETWEEN It compare the field value with in the given range. 8) IN It compare the field value with in the given set of values. 9) LIKE It used to compare character type data. 10) IS NULL It check whether a field has a value or not. If the value is 0 then it assumes value exist in the field. NULL means there should not be any value in a field, even 0. Logical Operators 1. AND It returns true when all the conditions are true. 2. OR It returns true when any one condition is true. 3. NOT It works in opposite way of given condition. Set Operators Set Operators are used to display data from a set of multiple queries. 1. Union 2. Union All 3. Intersect 4. Minus Union It compare all records of 2 given queries. It produce distinct rows only. Duplicate rows are not displayed, means if a row is retrieved from 2 queries is not listed second time. Union All It compare all records of 2 given queries.

that a

By P.Ashok

M.Tech (CSE)

SR Engineering College

DMBS Lab Manual

But it display duplicate rows also. That means if a row is retrieved from 2 queries, that is listed 2 times. Intersect It compare all records of 2 given queries. It produce only common rows of 2 queries. That means a row displayed when it is retrieved from 2 queries only. Minus It compare all records of 2 given queries. It produce rows which are retrieved from first query but not second query. 1. Display unique PPNO of all passenger Select distinct ppno from passenger; 2. Display names of male passenger Select name from passenger where gender=m; 3. Display ticket no and names of all passenger Select ticketno, name from passenger; 4. Display the source and destination having journey time more than 2 hours Select source, destination from bus where timediff(departuretime,starttime)>2; 5. Find ticket numbers of the passengers whose name start with A and end with H Select ticketno from passenger where name like A%H; 6. Display names of passengers whose age between 20 and 25 Select name from passenger where age between 20 and 25; 7. Display names of passengers whose name starts with R Select name from passenger where name like R%; 8. Display sorted list of passengers names Select name from passenger order by name; 9. Display names of passenger who are traveling in AC or NONAC Select name from passenger where busno in(select busno from bus where bustype in (AC,Non-AC)); Queries on Set Operators 1. Display Data of Clerks or Deptno 30 select * from emp where deptno=30 union select * from emp where job='CLERK'; 2. Display Data of Clerks and Deptno 30 select * from emp where deptno=30 intersect select * from emp where job='CLERK'; 3. Display Data of Clerks but not Deptno 30 select * from emp where job='CLERK' minus select * from emp where deptno=30;

By P.Ashok

M.Tech (CSE)

SR Engineering College

DMBS Lab Manual

10

Week 3 Queries using Aggregate functions (COUNT, SUM, AVG, MAX and MIN), GROUP BY, HAVING and Creation and dropping of Views. Group Functions These functions work on a set of values only. 1. 2. 3. 4. 5. It returns one result for all rows of a table. sum() avg() min() max() count()

Group by Clause It is use full to select the data based on given category wise while applying Group functions. Syntax: select columns, group-function group by column; Having Clause It is use full to select the data based on given condition from a category while applying Group functions. It filter the data by applying condition with distinct rows of a particular category. Syntax: select columns, group-function group by column having condition; A). Queries on Group Functions Calculating sum of salaries select sum(sal) from emp; Calculating Average of salaries select avg(sal) from emp; Calculating Minimum of salaries select min(sal) from emp; Calculating Maximum of salaries select max(sal) from emp; Calculating Number of Employees select count(empno) from emp; Calculating Number of Employees with comm select count(comm) from emp; Calculating Number of Employees with out comm select count(empno)-count(comm) from emp; /* Calculating sum of salaries Department wise */ select deptno,sum(sal) from emp group by deptno; /* Calculating Average of Salaries Department wise */ select deptno,avg(sal) from emp group by deptno;

By P.Ashok

M.Tech (CSE)

SR Engineering College

DMBS Lab Manual

11

/* Calculating Minimum of Salaries Department wise */ select deptno,min(sal) from emp group by deptno; /* Calculating Maximum of Salaries Department wise */ select deptno,max(sal) from emp group by deptno; /* Calculating Number of Employees Department wise */ select deptno,count(empno) from emp group by deptno; /* Using Sum(),Avg(),Min(),Max(),Count() Department wise */ select deptno,sum(sal),avg(sal),min(sal),max(sal),count(empno) from emp group by deptno; /* Displaying Department with sum(sal) above 10000 */ select deptno,sum(sal) from emp group by deptno having sum(sal)>=10000; /* Displaying Department with Employees above 5 */ select deptno,count(empno) from emp group by deptno having count(empno)>=5; /* Counting Employees with commision Department wise */ select deptno,count(empno),count(comm) from emp group by deptno; /* Counting Number of Departments */ select count(distinct deptno) from emp; /* Counting Number of Jobs */ select count(distinct job) from emp; B). Views  View logically represents subsets of data from one or more tables.  But it is a logical structure only.  It take the data from tables when it is called.  View can be created from one or more tables.  Creating Views is a good idea while working with many tables.  When a query is sent to a view, it get data from tables then display it. Queries on Views /* View with selectd columns */ create view v1 as select empno,ename from emp; /* Displaying Data from above View */

By P.Ashok

M.Tech (CSE)

SR Engineering College

DMBS Lab Manual

12

select * from v1; /* View with selectd data */ create view v2 as select * from emp where deptno=20; /* Displaying Data from above View */ select * from v2; /* Drop a View */ Drop view v2;

By P.Ashok

M.Tech (CSE)

SR Engineering College

DMBS Lab Manual

13

Week 4 Queries using Conversion functions (to_char, to_number and to_date), string functions (Concatenation, lpad, rpad, ltrim, rtrim, lower, upper, initcap, length, substr and instr), date functions (Sysdate, next_day, add_months, last_day, months_between, least, greatest, trunc, round, to_char, to_date) A). Conversion Functions /* To Demo to_number() */ select to_number('5') from dual; /* To Demo to_char() */ select to_char(1575,'$9,999') from dual; /* To Demo to_date() */ select to_date('03/08/81','DD/MM/YY') from dual; /* To Demo to_char() */ select sysdate, to_char(sysdate,'DD-MM-YY'), to_char(sysdate,'DD-MON-YYYY'), to_char(sysdate,'DD-MONTH-YYYY') from dual; /* To Demo to_char() */ select hiredate, to_char(hiredate,'DD-MM-YY') DD_MM_YY, to_char(hiredate,'DD-MON-YYYY') DD_MON_YYYY, to_char(hiredate,'DD-MONTH-YYYY') DD_MONTH_YYYY from emp; B). String Functions /* To Demo length() */ select length('Ashok') from dual; /* To Demo length() */ select ename,length(ename) from emp; /* To Demo ascii() */ select ascii('A'),ascii('Z') from dual; /* To Demo chr() */ select chr(65),chr(97) from dual; /* To Demo lpad(),rpad() */ select lpad('Ashok',10,'*'),rpad('Ashok',10,'*') from dual; /* To Demo lpad() */

By P.Ashok

M.Tech (CSE)

SR Engineering College

DMBS Lab Manual

14

select ename, lpad(ename,10,'*') from emp; /* To Demo rpad() */ select ename, rpad(ename,10,'*') from emp; /* To Demo ltrim(),rtrim() */ select ltrim('NISHANTH','N'),rtrim('ASHOK','OK') from dual; /* To Demo upper(),lower(),intcap() */ select upper('ashok'),lower('ASHOK'),initcap('ashok') from dual; /* To Demo upper(),lower(),initcap() */ select ename, upper(ename),lower(ename),initcap(ename) from emp; /* To Demo substr() */ select substr('Ashok Kumar',7,5) from dual; C). Date Functions /* To Demo add_months */ select sysdate,add_months(sysdate,3) from dual; /* To Demo months_between */ select months_between('3-aug-08',sysdate) from dual; /* To Demo last_day */ select sysdate,last_day(sysdate) from dual; /* Displaying last day of Hiredate */ select empno,ename,hiredate, last_day(hiredate) from emp; /* To Demo next_day */ select sysdate,next_day(sysdate,'sunday') from dual; /* To Demo round function */ select sysdate,round(sysdate,'day'),round(sysdate,'month'),round(sysdate,'year') from dual;

By P.Ashok

M.Tech (CSE)

SR Engineering College

DMBS Lab Manual

15

Week 5 Creation of simple PL/SQL program which includes declaration section, executable section and exception Handling section. PL/SQL PL/SQL means Procedural Language/Structured Query Language . Advantages 1. SQL has no programming techniques like condition checking, looping and branching etc. PL/SQL provides all these features. 2. PL/SQL reduce network traffic by making single call for many statements. 3. It allow the user to handle errors. PL/SQL Block Structure PL/SQL block of code is divided into 4 sections. 1. Declare Section Code block starts with a declare section. Variables, objects are declared and initialized. 2. Begin Section It consist set of SQL and PL/SQL statements. Data manipulations, looping, branching are specified here. 3. Exception Section It deal with handling of errors. It is optional. 4. End Section It indicate end of PL/SQL block. PL/SQL Data-types PL/SQL allows to use all data-types available in SQL. Ex: Number, Varachar2, Date etc. Apart from above there are 2 new data-types. Ex: 1. %type 2. %rowtype 1. %type It declare a variable based on a given column type of a table. Syntax : variable table.column%type; Ex : eno emp.empno%type; 2. %rowtype It declare a variable based on a given table record type. It can store a complete record of a table. Syntax : variable table%rowtype; Ex : rec emp%rowtype; Now rec can store one record from emp table. A). PL/SQL program to display data from EMP table. declare eno emp.empno%type:=&empno; rec emp%rowtype; begin select * into rec from emp where empno=eno; dbms_output.put_line(' Emp No = '||rec.empno); dbms_output.put_line(' Emp Name = '||rec.ename); dbms_output.put_line(' Emp Job = '||rec.job); dbms_output.put_line(' Emp Salary = '||rec.sal); exception when no_data_found then

By P.Ashok

M.Tech (CSE)

SR Engineering College

DMBS Lab Manual

16

dbms_output.put_line(' Employee Record Not Found '); end; B). PL/SQL program which Insert data into table and use COMMIT, ROLLBACK and SAVEPOINT in PL/SQL block. begin insert into emp(empno,ename,job,sal) values(101,KIRAN,CLERK,5000); commit; insert into emp(empno,ename,job,sal) values(102,VENU,MANAGER,9000); savepoint sp1; insert into emp(empno,ename,job,sal) values(103,MADHU,SALESMAN,6000); rollback to sp1; end;

By P.Ashok

M.Tech (CSE)

SR Engineering College

DMBS Lab Manual

17

Week 6 A). Develop a program that includes the features If Else. declare a number(2):=&a; b number(2):=&b; begin if a>b then dbms_output.put_line(a||' Greater than '||b); else dbms_output.put_line(b||' Greater than '||a); end if; end; B). Develop a program that includes the features while-loop. /* Printing Square Roots by While-Loop */ declare range number(3):=&range; i number(3):=1; s number(7,2):=0; begin while i<=range loop s:=sqrt(i); dbms_output.put_line(' Square Root of '||i||' = '||s); i:=i+1; end loop; end;

By P.Ashok

M.Tech (CSE)

SR Engineering College

DMBS Lab Manual

18

Week 7 Program development using USER defined Exceptions User Defined Exceptions It helps to validate the data. User defined exceptions are declared in the Declare section of PL/SQL block. Exception key word is used to create User defined exceptions. Ex : Declare <Exception-name> Exception; User defined exception is raised when any condition is violated with the help of Raise keyword. Ex : If <condition> Then Raise <user exception-name> Endif; Exception When <user exception-name> Then <statements> /* PL/SQL program for User Defined Exception ' comm_is_null ' & Updating Comm */ declare eno emp.empno%type:=&empno; rec emp%rowtype; comm_is_null exception; begin select * into rec from emp where empno=eno; if rec.comm is null then raise comm_is_null; else dbms_output.put_line(' Comm Already Exist '); end if; exception when comm_is_null then update emp set comm=500 where empno=eno; dbms_output.put_line(' Comm Updated '); end;

By P.Ashok

M.Tech (CSE)

SR Engineering College

DMBS Lab Manual

19

Week 8 Programs development using creation of procedures, passing parameters IN and OUT of PROCEDURES. Procedures - Functions A Procedure or Function is a set of SQL and PL/SQL statements. It performs a specific task. Procedure or Function has 3 parts. 1. Declarative Part It has declarations of variables, constants, cursors etc. It can have parameters also. 2. Executable Part It performs assign values, control execution and manipulate data. 3. Exception Handling Part It is optional and it deal with exceptions. Advantages 1. Security User can get permissions on Procedures and Functions instead of Tables. 2. Performance No need of compilation every time. It reduce disk I/O. 3. Memory Less amount of memory is required. 4. No need to write repeated code for same kind of operations. Procedure Vs Function A Function must return a value. A Procedure need no return a value and if required it can return multiple values by declaring many OUT parameters. Procedure Parameter Modes A Procedure can have parameters with different modes. Parameter mode specify functionality of a parameter. Ex : 1. IN  Parameter accepts a value. 2. OUT  Parameter returns a value. 3. INOUT  Parameter accepts and returns value. Creating Procedure Syntax : create or replace procedure <name>(<parameters>) is or as <variable>; Begin Statements Exception Statements End; Executing Procedure Syntax : SQL>exec <procedure-name>(<parameters>); Ex : SQL>exec add(10,20); Deleting a Procedure Syntax : SQL>drop procedure <name>; Ex: SQL>drop procedure p1; A). /* Procedure to display Employee Data */ create or replace procedure pr3(eno emp.empno%type) is rec emp%rowtype; begin

By P.Ashok

M.Tech (CSE)

SR Engineering College

DMBS Lab Manual

20

select * into rec from emp where empno=eno; dbms_output.put_line(' Emp No = '||rec.empno); dbms_output.put_line(' Emp Name = '||rec.ename); dbms_output.put_line(' Emp Job = '||rec.job); dbms_output.put_line(' Emp Salary = '||rec.sal); exception when no_data_found then dbms_output.put_line(' Employee Record Not Found '); end; /* Checking Procedure to display Employee Data */ declare eno emp.empno%type:=&eno; begin pr3(eno); end; B). /* Procedure to Add 2 values with Parameter Modes (IN,OUT) */ create or replace procedure prc1(a in number,b in number,c out number) is begin c:=a+b; dbms_output.put_line(' Addition = '||c); end; /* Checking Procedure to Add 2 values with Parameter Modes (IN,OUT) */ declare a number:=&a; b number:=&b; c number; begin prc1(a,b,c); end;

By P.Ashok

M.Tech (CSE)

SR Engineering College

DMBS Lab Manual

21

Week 9 Program development using creation of stored functions, invoke functions in SQL Statements and write complex functions. Creating Function Syntax : create or replace function <name>(<parameters>) return <type> is or as <variable>; Begin Statements Exception Statements End; Executing Function SQL>variable n; SQL>exec n:=add(10,20); SQL>print n; Deleting a Function Syntax : SQL>drop function <name>; Ex: SQL>drop function f1; /* Function to Update Employee Salary */ create or replace function fn2(eno emp.empno%type,ts emp.sal%type) return emp.empno%type is tsal emp.sal%type; begin select sal into tsal from emp where empno=eno; tsal:=tsal+ts; update emp set sal=tsal where empno=eno; return tsal; end; /* Checking Function to Update Employee Salary */ declare n emp.empno%type:=&n; s emp.sal%type:=&s; ns emp.sal%type; begin ns:=fn2(n,s); dbms_output.put_line(' New Salary = '||ns); end;

By P.Ashok

M.Tech (CSE)

SR Engineering College

DMBS Lab Manual

22

Week 10 Program development using creation of package specification, package bodies, private objects, package variables and cursors and calling stored packages. Packages A Package is an object which can holds other objects with in it. Objects of a Package are Procedures and Functions. It helps to create reusable and encapsulated blocks. A Package has 2 parts. 1. Package Specification It has Package name, other objects and their declarations. 2. Package Body It consist definition of objects in side of a Package. Advantages of Packages 1. It enable to develop efficient modules. 2. It allow overloading of Procedure and Functions with same name. 3. It improve performance by loading multiple objects into memory at a time. 4. It promote code reuse . Creating a Package Package Specification Syntax : Create or replace package <name> is procedure specification function specification End; Package Body Syntax : Create or replace package body <name> is procedure body function body End; Executing a Package Syntax : SQL>exec <package>.<procedure>; SQL>exec <package>.<function>; /* Package with 2 Display Procedures to take Empno, Ename */ create or replace package pack2 is procedure display(n emp.empno%type); procedure display(nm emp.ename%type); end; /* Package Body with 2 Display Procedures to take Empno, Ename */ create or replace package body pack2 is procedure display(n emp.empno%type) is rec emp%rowtype; begin select * into rec from emp where empno=n; dbms_output.put_line(' Emp No = '||rec.empno); dbms_output.put_line(' Emp Name = '||rec.ename); dbms_output.put_line(' Emp Job = '||rec.job);

By P.Ashok

M.Tech (CSE)

SR Engineering College

DMBS Lab Manual

23

dbms_output.put_line(' Emp Salary = '||rec.sal); exception when no_data_found then dbms_output.put_line(' Employee Record Not Found '); end; procedure display(nm emp.ename%type) is rec emp%rowtype; begin select * into rec from emp where ename=nm; dbms_output.put_line(' Emp No = '||rec.empno); dbms_output.put_line(' Emp Name = '||rec.ename); dbms_output.put_line(' Emp Job = '||rec.job); dbms_output.put_line(' Emp Salary = '||rec.sal); exception when no_data_found then dbms_output.put_line(' Employee Record Not Found '); end; end; /* Checking Package Body with 2 Display Procedures to take Empno, Ename */ declare en emp.empno%type:=&eno; enm emp.ename%type:='&ename'; begin pack2.display(en); pack2.display(enm); end;

By P.Ashok

M.Tech (CSE)

SR Engineering College

DMBS Lab Manual

24

Week 11 Develop programs using a CURSOR. Cursor Cursor is a memory area where data of a query is stored. Data retrieved from a table is stored in Cursor. Types of Cursor There are 2 types of Cursor. 1. Implicit Cursor 2. Explicit Cursor Cursor Attributes There are used to get status of a Cursor. 1. %ISOPEN 2. %FOUND 3. %NOTFOUND 4. %ROWCOUNT 1. Implicit Cursor It is created by Oracle for internal processing. It managed by Oracle Engine. Implicit Cursor Attributes 1. SQL%ISOPEN Returns True if Cursor is opened. 2. SQL%FOUND Returns True if Cursor has some data. 3. SQL%NOTFOUND Returns True if Cursor has no data 4. SQL%ROWCOUNT Returns no of records in a Cursor. 2. Explicit Cursor It is created by user for external requirements. It can have data of a table for processing temporarily. Steps 1. Declare a Cursor in Declare Section. Syntax : Cursor <name> is select statement; Ex : Cursor c1 is select * from emp; 2. Open the Cursor. Syntax : Open <cursor-name>; Ex : Open c1; 3. Fetch data from Cursor into variables. Syntax : Fetch <cursor-name> into <variable>; Ex : Fetch c1 into rec; 4. Process the data with the help a loop. 5. Exit from the loop after processing. 6. Close the Cursor. Syntax : Close <cursor-name>; Ex : Close c1; Explicit Cursor Attributes 1. c1%ISOPEN Returns True if Cursor is opened. 2. c1%FOUND Returns True if Cursor has some data. 3. c1%NOTFOUND Returns True if Cursor has no data 4. c1%ROWCOUNT Returns no of records in a Cursor.

By P.Ashok

M.Tech (CSE)

SR Engineering College

DMBS Lab Manual

25

/* Explicit Cursor to display Employee data using Simple Loop */ declare cursor c1 is select * from emp; rec emp%rowtype; rows number(2); begin open c1; loop fetch c1 into rec ; exit when c1%notfound; dbms_output.put_line(rec.empno||' - '||rec.ename||' - '||rec.job||' - '||rec.sal); end loop; rows:=c1%rowcount; dbms_output.put_line('Number of Records = '||rows); close c1; end; Parameter Cursor It has a parameter to accept user defined values. Contents of this type of cursor will change automatically. Syntax : Cursor <name>(Parameter) is select statement; Ex : Cursor c1(dno number) is select * from emp where deptno=dno; /* Parameter Cursor to display employees of given deptno */ declare cursor c4(dno number) is select * from emp where deptno=dno; begin for i in c4(&dno) loop dbms_output.put_line(i.empno||' - '||i.ename||' - '||i.job||' - '||i.sal); end loop; close c4; end;

By P.Ashok

M.Tech (CSE)

SR Engineering College

DMBS Lab Manual

26

Week 12 Develop Programs using Triggers. Triggers Triggers are the procedures which are executed automatically by Oracle Engine. Trigger is raised in response to an event. Event can be any DML statement like Insert, Update, Delete. Uses of Triggers 1. Trigger can permit DML operations in specified time only. Ex : We can restrict operations on Sunday. 2. Trigger can monitor the operations by a user. 3. Trigger can enforce security authentications. Types of Triggers Based on number times that a Trigger is executed, there are 2 types of Triggers. 1. Row Triggers It is executed for every row affected by a DML statement. 2. Statement Triggers It is executed only once no matter how many row affected by a DML statement. Based on the time that a Trigger is executed it is 2 types. 1. Before Triggers It is executed before the DML operation. 2. After Triggers It is executed after the DML operation. Creating Triggers Syntax : Create or replace trigger <name> before/after insert/update/delete on <table> for each row Begin Statements Exception Statements End; A). Create a Trigger to update COMM automatically when SAL is updated and test it. /* Trigger to update COMM */ create or replace trigger tg2 before update on emp for each row begin if :old.comm is not null then :new.comm:=:new.sal*10/100; end if; end; /* Testing Trigger to update COMM */ update emp set sal=2000 where empno=7844; /* Checking COMM updated by trigger */ Select * from emp where empno=7844;

By P.Ashok

M.Tech (CSE)

SR Engineering College

DMBS Lab Manual

27

B). Create a Trigger to backup data to other table when deleted. /* Create backup table */ Create table empbkp as select empno, ename, job, sal, comm from emp; Delete from empbkp; /* Trigger to backup the data when deleted */ create or replace trigger tg3 before delete on emp for each row begin insert into empbkp values(:old.empno,:old.ename,:old.job,:old.sal,:old.comm); end; /* Testing Trigger to backup the data when deleted */ delete from emp where empno=7844; /* Check backup table for deleted data*/ select * from empbkp;

By P.Ashok

M.Tech (CSE)

SR Engineering College

Вам также может понравиться