Sunteți pe pagina 1din 114

Introduction to Oracle

An Oracle database is a collection of data treated as a unit. The purpose of a database is to store and retrieve related information. A database server is the key to solving the problems of information management.In general, a server reliably manages a large amount of data in a multiuser environment so that many users can concurrently access the same data. All this is accomplished while delivering high performance. A database server also prevents unauthorized access and provides efficient solutions for failure recovery. Oracle Database is the first database designed for enterprise grid computing, the most flexible and cost effective way to manage information and applications. Enterprise grid computing creates large pools of industrystandard, modular storage and servers. With this architecture, each new system can be rapidly provisioned from the pool of components. There is no need for peak workloads, because capacity can be easily added or reallocated from the resource pools as needed. The database has logical structures and physical structures. Because the physical and logical structures are separate, the physical storage of data

can be managed without affecting the access to logical storage structures

Oracle Database Features


Oracle includes several software mechanisms to fulfill the following important requirements of an information management system:

Data concurrency of a multiuser system must be maximized. Data must be read and modified in a consistent fashion. The data a user is viewing or changing is not changed (by other users) until the user is finished with the data. High performance is required for maximum productivity from the many users of the database system.

This contains the following sections:


Concurrency Read Consistency Locking Mechanisms Quiesce Database Real Application Clusters Portability

Concurrency A primary concern of a multiuser database management system is how to control concurrency, which is the simultaneous access of the same data by many users. Without adequate concurrency controls, data could be updated or changed improperly, compromising data integrity. One way to manage data concurrency is to make each user wait for a turn. The goal of a database management system is to reduce that wait so it is either nonexistent or negligible to each user. All data manipulation language statements should proceed with as little interference as possible, and destructive interactions between concurrent transactions must be prevented. Destructive interaction is any interaction that incorrectly updates data or incorrectly alters underlying data structures. Neither performance nor data integrity can be sacrificed.
2

Read Consistency Read consistency, as supported by Oracle, does the following:

Guarantees that the set of data seen by a statement is consistent with respect to a single point in time and does not change during statement execution (statement-level read consistency) Ensures that readers of database data do not wait for writers or other readers of the same data Ensures that writers of database data do not wait for readers of the same data Ensures that writers only wait for other writers if they attempt to update identical rows in concurrent transactions

The simplest way to think of Oracle's implementation of read consistency is to imagine each user operating a private copy of the database, hence the Locking Mechanisms Oracle also uses locks to control concurrent access to data. When updating information, the data server holds that information with a lock until the update is submitted or committed. Until that happens, no one else can make changes to the locked information. This ensures the data integrity of the system. Oracle provides unique non-escalating row-level locking. Unlike other data servers that escalate locks to cover entire groups of rows or even the entire table, Oracle always locks only the row of information being updated. Because Oracle includes the locking information with the actual rows themselves, Oracle can lock an unlimited number of rows so users can work concurrently without unnecessary delays.There are two types of locking:Automatic Locking Manual Locking

Quiesce Database

Database administrators occasionally need isolation from concurrent non-database administrator actions, that is, isolation from concurrent non-database administrator transactions, queries, or PL/SQL statements. One way to provide such isolation is to shut down the database and reopen it in restricted mode. You could also put the system into quiesced state without disrupting users. In quiesced state, the database administrator can safely perform certain actions whose executions require isolation from concurrent non-DBA users.
Real Application Clusters Real Application Clusters (RAC) comprises several Oracle instances running on multiple clustered computers, which communicate with each other by means of a so-called interconnect. RAC uses cluster software to access a shared database that resides on shared disk. RAC combines the processing power of these multiple interconnected computers to provide system redundancy, near linear scalability, and high availability. RAC also offers significant advantages for both OLTP and data warehouse systems and all systems and applications can efficiently exploit clustered environments. Portability Oracle provides unique portability across all major platforms and ensures that your applications run without modification after changing platforms. This is because the Oracle code base is identical across platforms, so you have identical feature functionality across all platforms, for complete application transparency. Because of this portability, you can easily upgrade to a more powerful server as your requirements change.

Client Server Architecture


Client-server architecture can be considered as a network environment that exchanges information between a server machine and a client machine where server has some resources that can be shared by different clients. In a Client/server architecture individual computers (known as clients) are connected to a central computer which is known as ?server?. Let?s take an example of a file server to understand the core process of a client/server network, the file server acts as a storage space on the network for the files, spreadsheets, databases, etc. Instead of storing these records on every individual computer, the file server allows the clients to store their files on one central computer and make them sharable. The client-server architecture is beneficial in reducing the multiple iterations of a single file and allowing the organization to have one centralized point for every computer to access the same file.

The interaction between a lamp and an electrical socket can be considered as a interaction between client and server is just like. In the example the electrical socket is just like a server and the lamp works like a client. Types of client server architecture 1) Two tier architectures In two tier client/server architectures, the user interface is placed at user's desktop environment and the database management system services are usually in a server that is a more powerful machine that provides services to the many clients. Information processing is split between the user system interface environment and the database management server environment. The database management server supports for stored procedures and triggers. Software vendors provide tools to simplify development of applications for the two tier client/server architecture. 2) Three tier architectures The three tier architecture is introduced to overcome the drawbacks of the two tier architecture. In the three tier architecture, a middleware is used between the user system interface client environment and the database management server environment. These middleware are implemented in a variety of ways such as transaction processing monitors, message servers or application servers. The
6

middleware perform the function of queuing, application execution and database staging. In addition the middleware adds scheduling and prioritization for work in progress. The three tier client/server architecture is used to improve performance for large number of users and also improves flexibility when compared to the two tier approach. The drawback of three tier architectures is that the development environment is more difficult to use than the development of two tier applications. i) Three tier with message server. In this architecture, messages are processed and prioritized asynchronously. Messages have headers that include priority information, address and identification number. The message server links to the relational DBMS and other data sources. Messaging systems are alternative for wireless infrastructures. ii) Three tier with an application server This architecture allows the main body of an application to run on a shared host rather than in the user system interface client environment. The application server shares business logic, computations and a data retrieval engine. In this architecture applications are more scalable and installation costs are less on a single server than maintaining each on a desktop client.

History of Oracle
The different prodects related to oracle are developed during different years.These years are:

1977: Larry Ellison and friends founded Software Development Laboratories. 1979: SDL changed its company-name to "Relational Software, Inc." (RSI) and introduced its product Oracle V2 as an early commercially available relational database system. The version did not support transactions, but implemented the basic SQLfunctionality of queries and joins. (RSI never released a version 1 - instead calling the first version version 2 as a marketing gimmick.)[40] 1982: RSI in its turn changed its name, becoming known as "Oracle Corporation",[41] to align itself more closely with its flagship product.

1983: The company released Oracle version 3, which it had re-written using the C programming language and which supportedCOMMIT and ROLLBACK functionality for transactions. Version 3 extended platform support from the [41] existing Digital VAX/VMSsystems to include Unix environments. 1984: Oracle Corporation released Oracle version 4, which supported read-consistency. 1985: Oracle Corporation released Oracle version 5, which supported the clientserver modela sign of networks becoming more widely available in the mid-1980s. 1986: Oracle version 5.1 started supporting distributed queries. 1988: Oracle RDBMS version 6 came out with support for PL/SQL embedded within Oracle Forms v3 (version 6 could not store PL/SQL in the database proper), row-level locking and hot backups.[42] 1989: Oracle Corporation entered the application products market and developed its ERP product, (later to become part of the Oracle EBusiness Suite), based on the Oracle relational database. 1990: the release of Oracle Applications release 8[41] 1992: Oracle version 7 appeared with support for referential integrity, stored procedures and triggers. 1997: Oracle Corporation released version 8, which supported objectoriented development and multimedia applications. 1999: The release of Oracle8i aimed to provide a database interoperating better with the Internet (the i in the name stands for "Internet"). The Oracle8i database incorporated a native Java virtual machine (Oracle JVM, also known as "Aurora".[43]). 2000: Oracle E-Business Suite 11i pioneers integrated enterprise application software[41] 2001: Oracle9i went into release with 400 new features, including the ability to read and write XML documents. 9i also provided an option for Oracle RAC, or "Real Application Clusters", a computercluster database, as a replacement for the Oracle Parallel Server(OPS) option.

2003: Oracle Corporation released Oracle Database 10g, which supported regular expressions. (The g stands for "grid"; emphasizing a marketing thrust of presenting 10g as "grid computing ready".) 2005: Oracle Database 10.2.0.1also known as Oracle Database 10g Release 2 (10gR2)appeared. 2006: Oracle Corporation announces Unbreakable Linux[41] 2007: Oracle Database 10g release 2 sets a new world record TPC-H 3000 GB benchmark result[44] 2007: Oracle Corporation released Oracle Database 11g for Linux and for Microsoft Windows. 2008: Oracle Corporation acquires BEA Systems. 2010: Oracle Corporation acquires Sun Microsystems. 2011: Oracle Corporation acquires web content management system FatWire Software.

Versions of Oracle
Oracle has many versions whish are listed below:Oracle products follow a custom release numbering and naming convention. With the Oracle RDBMS 10g release, Oracle Corporation began using the "10g" label in all versions of its major products, although some sources refer to Oracle Applications Release 11i as Oracle 11i. The suffixes "i" and "g" do not actually represent a low-order part of the version number, as letters typically represent in software industry version numbering; that is, there is no predecessor version of Oracle 10g called Oracle 10f. Major database-related products and some of their versions include:

Oracle Application Server 10g (also known as "Oracle AS 10g"): a middleware product; Oracle Applications Release 11i (aka Oracle e-Business Suite, Oracle Financials or Oracle 11i): a suite of business applications; Oracle Developer Suite 10g (9.0.4); Oracle JDeveloper 10g: a Java integrated development environment;

Since version 5, Oracle's RDBMS release numbering has used the following codes: Oracle v5 Oracle v6 Oracle7: 7.0.167.3.4 Oracle8 Database: 8.0.38.0.6 Oracle8i Database Release 1: 8.1.5.08.1.5.1 Oracle8i Database Release 2: 8.1.6.08.1.6.3 Oracle8i Database Release 3: 8.1.7.08.1.7.4 Oracle9i Database Release 1: 9.0.1.09.0.1.5 (patchset as of December 2003) Oracle9i Database Release 2: 9.2.0.19.2.0.8 (patchset as of April 2007) Oracle Database 10g Release 1: 10.1.0.210.1.0.5 (patchset as of February 2006) Oracle Database 10g Release 2: 10.2.0.110.2.0.5 (patchset as of April 2010) Oracle Database 11g Release 1: 11.1.0.611.1.0.7 (patchset as of September 2008) Oracle Database 11g Release 2: 11.2.0.111.2.0.3 (patchset as of September 2011)

The version-numbering syntax within each release follows the pattern: major.maintenance.application-server.component-specific.platform-specific. For example, "10.2.0.1 for 64-bit Solaris" means: 10th major version of Oracle, maintenance level 2, Oracle Application Server (OracleAS) 0, level 1 for Solaris 64-bit.
10

The Oracle Administrator's Guide offers further information on Oracle release numbers. Oracle Server Features This chapter provides an overview of some of the features of the Oracle server. The topics include:

Internet Computing and Distributed Databases Advanced Queuing Overview Data Warehousing Overview Data Access Overview Database Security Overview Database Backup and Recovery Overview Introduction to Oracle9i Data Guard LogMiner SQL-Based Log Analyzer Overview

Q 1create table student with columns rollno(primary key),name(not null),address,fathername,marks and perform following queries on it :Ans. create table student2002(rollno number(3) primary key,name varchar(10) NOT NULL,address varchar(10),fathername varchar(10),marks number(8)); desc student2002;

11

1.insert 5 records in the table insert into student2002 values(1,'ram','ldh','rajesh',56); insert into student2002 values(2,'sam','ldh','rajat',67); insert into student2002 values(3,'sid','chd','sumit',78); insert into student2002 values(4,'ashu','jal','anurag',54); insert into student2002 values(5,'harry','chd','shabir',75); select * from student2002;

2.update rollno 2s name to shabir kumar update student2002 set name='shabir' where rollno=2;

12

select * from student2002;

3.update rollno 5s address update student2002 set address='ldh' where rollno=5; select * from student2002;

4.rollno and names of student whose marks <20 select rollno,name from student2002 where marks<60;

5.show details of all students select * from student2002;

13

6.show the details of rollno select * from student2002 where rollno=2;

Q6. Create two tables ,one table named student with columns rollno(primarykey),name(notnull),add(notnull),phoneno, second table named stu_marks with columns rollno(foreign key),marks,status. Ans. Create table student ( rollno number(2) primary key,name varchar(10) NOT NULL ,father name varchar(10),address varchar(10),phoneno Number(10)); Create table stu_marks ( rollno number(2),marks number(2),status
14

varchar(5),constraints fk_student foreign key(rollno) references student(rollno)); student table

Rollno Name 1 2 3 4 5 Raja Samita Mandeep Kiran Har

Marks 300 323 543 200 400

Address phoneno Ldh Ldh Chd Jal Chd 3425780 2356320 5435634 3254345 6321905

Stu_marks table Rollno Marks 1 2 3 4 5 301 302 303 304 305 status fail pass fail pass fail

Q6. show marks and rollno of students who are passed


15

Ans. Select rollno,marks from stu_marks where status= pass; Q7. Show roll no and name of student who are fail Ans. Select rollno,marks from stu_marks where status= fail; Q8.update marks of rollno 5 to 500 Ans. Update stu_marks set marks=500 where rollno=2; Q9. show details of students whose marks are < 400 Ans. Select * from stu_marks where marks<400; Q10.update name of roll no 2 to ram kumar Ans.update student set name= ramkumar where rollno=2;

Q create table student and execute following queries:Create table student (rno number(2),name varchar(10),eng number(3),math number(3),pbi number(3)); Rno 1 2 3 name Harman Eng 56 Math 67 76 68 Pbi 65 87 56

Mandeep 87 Kiran 67

16

Aman

45

97

78

1.show number of students whose marks >50% and marks <80% Select name,(eng+math+pbi)/300*100 AS percentage from student where (eng+math+pbi)/300*100 BETWEEN 50 AND 80

Name

Percentage

Harman 62.666666666 Kiran 63.666666666 Aman 73.333333333 2.calculate average marks,total marks Select SUM(eng+math+pbi),SUM(eng+math+pbi)/3 AS average from student; 3.show names of student whose total marks are greater than 200 Select rno,name,eng+math+pbi from student where eng+math+pbi>200 Rno 2 4 Name Mandeep Aman Eng+math+pbi 250 220

4.calculate minimum and maximum marks Select MAX(eng+math+pbi),MIN(eng+math+pbi) from student;

17

5.show rno,marks,total marks and percentage Select rno,eng+math+pbi as total_marks,(eng+math+pbi)/300 *100 from student; Q.Create a table named emp with columns eno,ename,salary,desi. Ans. Create table emp(eno number(2),ename varchar(10),salary number(10),desi varchar(10)); Q12.List ename of employees whose salary is greater than 20000 Ans. select ename from emp where salary >20000;

Q13. List ename,designation,salary of an employeeof dept no 10 and whose salary is greater than 20000. Ans. Select ename,designation,salary from emp where deptno=10 and salary>20000; Q14. List all columns whose department other than 10 Ans.select * from emp where DeptnoNOT IN (10); Q15.list all employees whose ename starts with A and end with N. Ans. Select * from emp where ename LIKE A%N;

18

Q16.list all employees whose designation is clerk or manager. Ans. Select * from emp where designation= clerk OR designation= manager; Q17.list all employees whose salary lies between 1250 and 3000 Ans. Select * from emp where salary BETWEEN 1250 and 3000; Q18.list all employees who are not clerks Ans. Select ename from emp where designation!= clerk; Q19.list all employees who has two l in their name. Ans.select ename from emp where ename like %l%l%; Q20.List all the employees who is getting commission Ans. Select ename from emp where comm. IS NOT NULL; Q21.list all the employees according to date of joining. Ans.select ename,hiredate from emp ORDER BY date; Q22.List last three character of ename of employees. Ans.Select ename from emp where ename LIKE _ _ _; Q23.List hiredate of each each employee in the format of DD/MM/YYYY. Ans.select ename,hiredate To_char(hiredate : DD/MM/YYYY) from emp; Q24.List the number of months between the system data and date of joining of the employee. Ans.select hiredate ,MONTHS_BETWEEN(sysdate,hiredate) from emp; Q25.List the current system date. Ans.select To_char (system, HH:SS:MM) from dual;

19

Q26.Using decode function list designaton as President as P and Manager as M. Ans.select desi DECODE ( desi, President, P, Manager, M) from emp; Q27.List all the employees information in which null values in comm Changes to 99. Ans.select ename, comm. NVL2(comm.,99) from emp; Q28.List the maximum ,minimum and average of salaries. Ans.select MAX(salary),MIN(salary),AVG(salary) from emp; Q29.Count the number of designation titles in emp table. Ans.select COUNT(*),COUNT(DINTINCT desi) from emp; Q30.List all the who joined in 1987. Ans.select ename from emp where hiredate LIKE %87; Qlist the sum of sal and comm. of all employees Ans. Select SUM(sal),SUM(comm) from emp; Q find the date 7 days after the todays date Ans. Select sysdate+7 from dual; 31.Create three tables:1.SUPP table(Sid,Sname,Location)where SID is the primary key 2.PARTS table(Pid,Pname,Colour,Weight,City)where Pid is the primary key 3.SUP_PART table(Sid,Pid,Quantity) where (Sid,Pid) is the primary key and Sid and Pid as foreign key to SUPP and PARTS tables respectively.

20

Ans.1. create table SUPP (Sid number(2) primary key,Sname varchar(10),Location varchar(10));

Sid 10 30 20 pid 11 12 13 14

Sanme Pen Paper pencil Pname Hfg Fhh Fj Fh

loc Ldh jal chd colour Red Blue Green Pink

2.create table PARTS (Pid number(2) primary key,Pname varchar(10),Colour varchar(10),Weight number(2),City varchar(3)); weight 20kg 2kg 16kg 15kg city Ldh Chd Jal chd

3.create table SUP_PART(Sid number(2) primary key,Pd number(2) primary key,Quantity number(2), constraint fk foreign key (Sid) references SUPP (Sid),constraint fk foreign key(Pid) references PARTS(Pid)); Perform following commands in above tables:1.list all parts information whose colour is RED. Select Pid from PARTS where Colour LIKE RED; 2.List all suppliers whose name start with S and Loc ends with R. Select Sname from SUPP where Sname LIKE A% location LIKE %R;

21

3.Get the total quantity supplier by each supplier Select SUM(Quantity) from SUPP_PARTS; 4.Get the total quantity whose suppliers s2 and Part p2 Select SUM(Quantity) from SUPP_PARTS Where Sid=s2 OR Pid= p2; Q create table organization and execute following queries:create table organisation (eno number(4),name varchar(10),job varchar(10),deptno number(3),salary number(10)); desc organisation;

insert into organisation values(1,'rajesh','clerk',10,20000); insert into organisation values(2,'ram','manager',20,30000); insert into organisation values(3,'sam','salesman',10,40000); insert into organisation values(4,'sham','clerk',30,20000); insert into organisation values(5,'ritu','manager',40,50000); select * from organisation;

22

1.total number of employees in organisation select count(eno) from organisation ;

2.total number of employees in deptno 10 only select count(eno) from organisation where deptno=10;

3.count number of clerk in deptno 10 select count(eno) from organisation where job='clerk' and deptno=10;

23

4.calculate total and average salary of deptno 10 select sum(salary),avg(salary) from organisation where deptno=10;

5.total salary withdrawn by clerk select sum(salary) from organisation where job='clerk';

6.calculate total and average salary and count number of manager in deptno 20 select count(eno),sum(salary),avg(salary) from organisation where job='manager' and deptno=20;

7.count number of manager whose salary is > than 50000 and they work in deptno 10 select count(eno) from organisation where salary>20000 and deptno=10;

24

8.calculate maximum sal withdrawn by manager select max(salary) from organisation where job='manager';

9.calculate minimum sal withdrawn by organization select min(salary) from organisation;

10.calculate max and min sal of clerks Select min(salary),max(salary) from organization where job= clerk; Qcreate table BCA and perform following queries create table BCA123(rollno number(3),name varchar(10),class varchar(6),status varchar(6)); desc BCA123;

25

1.insert records into it insert into BCA123 values(10,'a','bca1','pass'); insert into BCA123 values(20,'b','bca2','pass'); insert into BCA123 values(30,'c','bca2','fail'); insert into BCA123 values(40,'d','bca3','pass'); insert into BCA123 values(50,'e','bca3','fail'); select * from BCA123;

2.count number of students in each class select class,count(class) from BCA123 group by class;

2.count number of students who has failed in each class


26

select count(rollno) from BCA123 where status='fail';

Qcreate table emp and perform following queries :create table emp321 (eno number(3),ename varchar(10),sal number(10),desi varchar(10)); desc emp321;

insert into emp321 values(11,'rajesh',10000,'clerk'); insert into emp321 values(12,'raj',20000,'manager'); insert into emp321 values(13,'ram',10000,'clerk'); insert into emp321 values(14,'sam',30000,'manager'); insert into emp321 values(15,'sham',40000,'ceo'); select * from emp321;

alter table emp321 add(deptno number(3)); update emp321 set deptno=10 where eno=11; update emp321 set deptno=10 where eno=12; update emp321 set deptno=20 where eno=13; update emp321 set deptno=30 where eno=14; update emp321 set deptno=30 where eno=15;
27

select * from emp321;

1.find total salary and total number of employees having salary>15000 Select sal,count(eno) from emp321 group by deptno having salary>15000 ; 2.find total number of clerks in each dept select desi,count(desi) from emp321 where desi='clerk' group by desi;

SUB queries Q show name,salary,dept of the employee whose salary is greater than employee no 2 s salary select eno,name,salary,deptno from organisation where salary> (select salary from organisation where eno=2);

28

GROUP and HAVING CLAUSE 1.count number of clerks in emp table Select job,count(desi) from emp where desi= clerk GROUP BY JOB; 2.count number of clerks in each dept Select deptno,count(job) from emp where desi= clerk GROUP BY DEPT; 3.count the number of employees in table job wise Select job,count(job) from emp GROUP BY JOB; 4.To find total salary paid to each job title within each dept Select deptno,SUM(sal) from emp GROUP BY deptno; 5.to count the number of employees under each job title with each dept Select deptno,COUNT(eno) from emp GROUP BY deptno;

SET OPERATORS Qshow eno and name of employees who work for deptno 10 or in deptno 30 select eno,name from organisation where deptno=10 UNION select eno,name from organisation where deptno=30;

29

Qshow eno and name of employees who work for deptno 10 and deptno 40 select eno,name from organisation where deptno=10 MINUS select eno,name from organisation where deptno=40;

Qcreate table BCA1 and BCA2 and perform following queries create table BCA1st (rno number(2),name varchar(10),marks number(5),status varchar(10));

1.insert records into it Insert into bca1st values(10,'har',15,'fail'); insert into bca1st values(11,'mani',45,'pass'); insert into bca1st values(12,'ram',65,'pass'); insert into bca1st values(13,'sam',13,'fail'); select * from BCA1st;
30

create table BCA2nd (rno number(2),name varchar(10),marks number(5),status varchar(10)); desc BCA2nd;

insert into bca2nd values(1,'rani',34,'fail'); insert into bca2nd values(2,'rajni',56,'pass'); insert into bca2nd values(3,'clark',45,'pass'); insert into bca2nd values(4,'ritz',67,'pass'); select * from BCA2nd;

31

2.show rno,name of students who have failed in BCA1 and BCA2 select rno,name from BCA1st where status='fail' UNION select rno,name from BCA2nd where status='fail';

Q32. Create table MCA has columns applicantid(primary key) ,name,eligibility only BCA,Bsc(it),phoneno.apply check constraint on eligibility column at column level and table level. Ans. At column level Create table MCA (applicant number(2) primary key,name varchar(8),eligibility varchar(6) constraint ck_check(eligibility IN (BCA, Bsc(it) ))); At table level Create table MCA (applicantid number(2),name varchar(8),eligibility varchar(6),phoneno number(10),constraint pk_primary key (applicantid),constraint ck_check(eligibility IN(BCA, Bsc(it) ))); Q38.Execute following queries on EMP and DEPT tables. a) List employees information of all employees who work in
32

CHICAGO. Ans. Select ename,desi from EMP where deptno IN (select deptno from DEPT where Loc= CHICAGO); b) List all employees who do not work in the samedepartment as that of its maneger. Ans.select * from emp e1 where deptno NOT IN (select deptno from emp e2 where e2.empno=e1.manager); b) List all employees who earn more than the average salary of all emplyees. Ans.select ename,deptno,salary from e1 where salary >(select AVG(salary) from emp e2 where e1.deptno=e2.deptno); c)List all employees which is same as those of employees whose name end with R. Ans. select empno,ename from emp where ename LIKE %R;

Q39.Cosider two tables

Eno 10 11 12 13 14

Name Ram Riya Sita Pam Kim

deptno 101 102 103 104 105

Sal 20000 10000 30000 20000 40000

EMP DEPT Dno 101 102 103 104 105 Dname IT Sci Acc Sci IT Loc Ldh Ldh Jal Jal Chd

33

Perform following operations on these tables:a) List number of employees of in Acc department table Ans. select name,sal from EMP ,DEPT where dname= Acc AND EMP.deptno=DEPT.dno; b) List names of employees where sal>maximum sal of deptno=20; Ans.select name,sal from EMP where sal>(select MAX(sal) from EMP where deptno=20); Q33.create table BCA2 columns= rno(only 1 to 40)(primary key),name(start with A or S),marks,status(pass,fail,absent). Ans. At column level Create table BCA2 (rno number(2) primary key constraint ck_check (rollno BETWEEN (1 AND 40)),name varchar(8) constraint ck_ckeck(name LIKE (%A OR S%)),marks number(2),status varchar(6) constraint ck_check (statu IN (pass, fail, absent))); At table level Create table BCA2 (rno number(2) ,name varchar(8) ,marks number(2),status varchar(6),constraint pk_primary key(rno),constraint ck_check(rno BETWEEN (1 AND 40)), constraint ck_ckeck(name LIKE (%A OR S%)), constraint ck_check (statu IN (pass, fail, absent)));

Q34. Creating a new table from existing table Consider a table named : BCA

34

rno

name

marks

class

Create two tables from this table: 1. BCA1 table with columns rno,name,marks 2. BCA2 table with columns rno,marks Ans. Create table BCA1 (rollno,name,marks) as select rno,name,marks from BCA. Create table BCA2 (rollno,marks) as select rno,marks from BCA. Q35. Adding new columns in the existing table Q1.Add a new column address in table BCA Ans. Alter table BCA add (address varchar(10)); Q2. Add two columns address and phno in BCA table. Ans. Alter table BCAadd(addressvarchar(10),phnonumber(10)); Q36.Adding constraint in existing table. Ans. 1.Alter table emp add (constraint ck_check (name LIKE S %), Constraint ck_check (rollno BETWEEN 1 AND 40));

35

2.Alter table emp add(constraint fk_foreign key(deptno) references dept(did)); 3.Alter table dept add(constrain uk_unique key(did)); Q37.Various clauses of select statement To view all rows and columns Select * from BCA2; To view selected columns and all rows Select rollno, name from BCA2; To view selected columns and selected rows Select name from BCA2 where rollno=1; Q create view and perform insertion Create clerk AS Select empno,ename,job,deptno,hiredate from emp; Insert into clerk(empno,ename,job) Values (3099,anshu,clerk); Join view Create or replace view emp_dept_veiw as select e.empno,e.ename,e.deptno,d.name ,d.loc from EMP e,DEPT d, where e.deptno=d.deptno And d.loc IN(DALLIS, NEW YORK, BOSTON); Q create SEQUENCE Create SEQUENCE emp_id Start with 100 Increment by 1 Maxvalue 500;

36

Insertion in sequences Insert into emp(empno,ename,sal) values (emp_id.nextval, anshu,21000)

37

PL/SQL PROGRAMS Write PL/SQL program to display message Welcome to PL/SQL. Ans. BEGIN Dbms_output.put_line(Welcome to PL/SQL); END; Output:Welcome to PL/SQL

38

Write a PL/SQL program to calculate the product of two numbers. Declare Val1 number; Val2 number; Result number; BEGIN Val1 := :Val1; Val2:= :Val2; Result := Val1 * Val2; Dbms_output.put_line(product of || Val1 || and || Val2 || is = ||Result); END; Output:Enter value for Val1=10 Enter value for Val2=2 Product of 10 and 2 is 20

39

Write PL/SQL program to calculate the area of a circle Declare r number; area number; pi constant number:= 3.1415; BEGIN r:= :r; area:= pi * r ** 2; dbms_output.put_line(area of circle= || area); END; Output:Enter value for r=2 Area of circle=12.56637 PL/SQL procedure successfully completed

40

Write PL/SQL program to find area of rectangle DECLARE l number; b number; area number; BEGIN l:= :l; b:= :b; area:= l *b; dbms_output.put_line(area of rectangle is || area); END; Output:Enter value of l: 4 Enter value of b: 2 Area of rectangle : 8

41

Write PL/SQL program to find area of square DECLARE s number; area number; BEGIN s:= :s; area:= s ** 2; Dbms_output.put_line(area of square || area); END; Output:Enter value for s: 4 Area of rectangle=16

42

Write PL/SQL program to evaluate different arithemetic expressions DECLARE a number := :a; b number := :b; c number; n number:= :n; BEGIN IF (n=1) THEN c:=a+b; dbms_output.put_line(c); elsif (n=2) THEN c:=a-b; dbms_output.put_line(c); elsif (n=3) THEN c:=a*b; dbms_output.put_line(c); ELSIF (n=4) THEN c:=a/b; dbms_output.put_line(c); ELSE dbms_output.put_line('sorry'); END IF; END; Output:Enter the value of a: 5 Enter the value of b: 1 Enter the value of n: 1 6 Statement processed.

43

Write PL/SQL program to check given number is positive or negative DECLARE n number; BEGIN n := :n; if n>0 then dbms_output.put_line(number is negative); ELSE Dbms_output.put_line(number is positive); END IF; END; Output:Enter value for n: -2 Number is negative

44

Write PL/SQL program to display days of week DECLARE n number:= :n; BEGIN IF (n=1) THEN dbms_output.put_line('MONDAY'); elsif (n=2) THEN dbms_output.put_line('TUESDAY'); elsif (n=3) THEN dbms_output.put_line('WEDNESDAY'); ELSIF (n=4) THEN dbms_output.put_line('THURSDAY'); ELSIF (n=5) THEN dbms_output.put_line('FRIDAY'); ELSIF (n=6) THEN dbms_output.put_line('SATURDAY'); ELSIF (n=7) THEN dbms_output.put_line('SUNDAY'); ELSE dbms_output.put_line('sorry'); END IF; END; Output:Enter the value of n: 3 WEDNESDAY Statement processed.

45

46

Write PL/SQL program to find greatest among three numbers DECLARE a number; b number; c number; BEGIN a:= :a; b:= :b; c:= :c; IF (a>b AND a>c) THEN dbms_output.put_line('a is the greatest'); ELSIF (b>a and b>c) THEN dbms_output.put_line('b is the greatest'); ELSIF (c>a and c>b) THEN dbms_output.put_line('c is the greatest'); ELSE dbms_output.put_line('sorry'); END IF; END; Output:Enter the value of a: 2 Enter the value of b: 5 Enter the value of c: 1 b is the greatest Statement processed.

47

Write PL/SQL program to print 1 to 10 number using while loop DECLARE n number; BEGIN n:=:n; WHILE n<=10 LOOP Dbms_output.put_line(n); n:= n+1; END LOOP END; Output:Enter value for n : 1 1 2 3 4 5 6 7 8 9 10

48

Write PL/SQL program to print 1 to 10 numbers using for loop DECLARE n number; BEGIN n := :n FOR n IN 1 ..10 LOOP Dbms_output.put_line(n); END LOOP; END; Output:Enter value for n: 1 1 2 3 4 5 6 7 8 9 10

49

Write PL/SQL program to print 1 to 10 numbers in reverse order using for loop DECLARE n number; BEGIN n:= :n; FOR I IN REVERSE 1 ..n LOOP Dbms_output.put_line(i); END LOOP; Dbms_output.new_line; END; Output:Enter value for n: 10 10 9 8 7 6 5 4 3 2 1

50

Write PL/SQL program to find factorial of a number DECLARE n number:= :n; f number := 1; BEGIN while n>1 LOOP f:= f*n; n:= n-1; END LOOP; dbms_output.put_line('factorial is ' || f ); END; Output:factorial is 24 Statement processed.

Write PL/SQL program to print table of a number

51

DECLARE N number; BEGIN FOR i IN 1..10 LOOP Dbms_output.put_line(n || * || i || n * i); END LOOP; END; Output:Enter value for n: 2 2 * 1=2 2 * 2=4 2 * 3=6 2 * 4=8 2 * 5=10 2 * 6=12 2 * 7=14 2 * 8=16 2 * 9=18 2 * 10=20

Write PL/SQL program to display salary of an employee of specific empno from emp table

52

DECLARE Sal emp.salary%TYPE; Empno emp.eno%TYPE; BEGIN Empno:= :empno; Select salary into sal from emp where eno=empno; Dbms_output.put_line(salary of || empno || is= || sal); END; Output:Enter value for empno: 11 Salary of 11 is= 10000

Write PL/SQL program to update salary of an employee on the basis of eno

53

DECLARE sal employee.salary%type; ecode employee.eno%type; BEGIN ecode:= :ecode; update employee set salary=salary+1000 where eno=ecode; dbms_output.put_line('salary updated'); END; Output:salary updated Statement processed.

Write PL/SQL program to delete a row on the basis of empno Declare ecode employee.eno%type;
54

BEGIN ecode:= :ecode; delete from employee where eno=ecode; dbms_output.put_line('data deleted'); END; data deleted Statement processed.

Write PL/SQL program to perfoem various DML operations on emp table DECLARE ecode employee.eno%type; choice number; BEGIN
55

dbms_output.put_line('case1 : to selection'); dbms_output.put_line('case1 : to insertion'); dbms_output.put_line('case1 : to deletion'); dbms_output.put_line('case1 : to updation'); choice:= :choice; ecode:= :ecode; if (choice=1) THEN select name,salary from employee where eno=ecode; dbms_output.put_line('data selected'); elseif(choice=2) THEN insert into emloyee(eno,name,salary,dept_no) values(2,'ram',30000,20); dbms_output.put_line('data inserted'); elseif(choice=3) THEN delete from employee where eno=ecode; dbms_output.put_line('data deleted'); elseif(choice=4) THEN update employee set salary=salary+500 where eno=ecode; dbms_output.put_line('data updated'); else dbms_output.put_line('invalid choice'); END IF; END;

Write PL/SQL program to print information of a particular employee from emp table using %ROWTYPE
DECLARE Employee emp%ROWTYPE; BEGIN Select * into employee from emp where empno=11;
56

Dbms_output.put_line(employee.ename); Dbms_output.put_line(employee.salary); Dbms_output.put_line(employee.desi); Dbms_output.put_line(employee.deptno); END; Output:Statement processed

Write PL/SQL program to insert a row into emp table

BEGIN Insert into emp(eno,ename,salary,desi,deptno) Values (16, mandeep,50000, manager,20); Dbms_output.put_line(Data entered);
57

END; Output:Data entered

Write PL/SQLprogram to check whether a given number is even or not


DECLARE n number; BEGIN n := :n;

58

If n MOD 2 =0 then Dbms_output.put_line( n || is even); END IF; END; Output:Enter value for n: 4 4 is even

Write PL/SQL program to check whether given number is odd or even


DECLARE n number; BEGIN n := :n;

59

If n MOD 2=0 then Dbms_output.put_line(n || is even); ELSE Dbms_output.put_line(n || is odd); END IF; END; Output:Enter value for n : 7 7 is odd

Write PL/SQL program to check whether a number is even or odd if it is equal to 0 otherwise display the message number is zero.
DECLARE n number; BEGIN n := :n;
60

If n<> 0 THEN IF n mod 2 = 0 THEN Dbms_output.put_line( n || is even); ELSE Dbms_output.put_line( n || is odd); END IF; ELSE Dbms_output.put_line(number is zero); END IF; END; Output:Enter value for n: 5 5 is odd

Write PL/SQL program to insert 5 records into emp table using while loop
DECLARE Ecode number := 1; Salary number := 1000;
61

n number := 1; BEGIN WHILE n<=5 LOOP Insert into emp(empno,sal) values(ecode,salary); Ecode := ecode+1; Salary := salary + 500; n:= n+1; END LOOP; END;

Output:PL/SQL procedure successfully completed

Write PL/SQL program which executes a loop 3 times using EXIT WHEN statement
DECLARE N number :=0; BEGIN
62

LOOP N := n+1; EXIT WHEN n>3; Dbms_output.put_line(loop executes || n || times); END LOOP; END; Output:Loop executes 1 times Loop executes 2 times Loop executes 3 times PL/SQL procedure successfully completed

Write PL/SQL program to handleTOO_MANY_ROWS exception


DECLARE Name emp.ename%type; BEGIN Select ename into name from emp where deptno=10; Dbms_output.put_line(employee name:= || name); EXCEPTION
63

WHEN TOO_MANY_ROWS THEN Dbms_output.put_line(more than one rows returned); END;

Write PL/SQL program which handles more than one exception

DECLARE Name emp.ename%type; BEGIN Select ename into name from emp where deptno=:deptno; dbms_output.put_line(employee name:= || name);

64

EXCEPTION WHEN TOO_MANY_ROWS THEN Dbms_output.put_line(more than one rows returned); WHEN ZERO_DIVIDE THEN Dbms_output(divide by zero); WHEN OTHERS THEN Dbms_output.put_line(no rows exit); END;

Write PL/SQL program to create user-defined exceptions which checks whether the name of the employee is blank or not during insertion
DECLARE Ecode employee.empno%type; Name employee.ename%type; Ename_err exception; BEGIN
65

Ecode := :ecode; Name := :name; If name is null then Raise ename_err; End if; Insert into employee(empno,ename) values (ecode,name); Dbms_output.put_line(data entered); EXCEPTION When ename_err then Dbms_output.pu_line(ename should not be blank); End;

A PL/SQL program to check whether the record exist for a given employee number .If so,then retrieve his salary?
Declare Salary number(5); Begin Select sal INTO Salary FROM Emp where empno=&empno;
66

IF SQL%FOUND THEN dbms_output.put_line('Record is found'); dbms_output.put_line('Salary='||salary); END IF; EXCEPTION WHEN NO_DATA_FOUND then dbms_output.put_line('Employee record is not present'); END;

Output:Enter the value of empno: 10 Record is found Salary is 20000

67

Create a PL/SQL program that fetch the Department name and location of the given department number,and if department number doesn't exist then program will raise the user-defined exception?
Declare Location Dept.Loc%Type; Name Dept.Dname%Type; Dno Dept.DeptNo%Type; Deptno_eRR EXCEPTION; Begin Dno := :Dno; if Dno not IN (10,20,30,40) THEN RAISE deptno_err; END IF; Select Dname,Loc INTO Name, Location FROM DEPT where Deptno=Dno; dbms_output.putline('Location= ' || Location); EXCEPTOIN When Deptno_ERR THEN dbms_output.put_line ('Deptno doesnot exist'); End;

68

Write a PL/SQL program to update the salary of a given employee.Use SQL%NOTFOUND attribute to check whether the record is updated or not? Begin update emp Set sal= sal+100 where empno=&empno; IF SQL%NOTFOUND then dbms_output.put_line('record not found'); ELSE dbms_output.put_line('record is updated'); END IF; END;

69

Write a PL/SQL program,count the number of records affected increasing the salaries of employees by 100 in EMP table?
Begin update EMP set sal=sal+100; dbms_output.put_line(SQL%ROWCOUNT||'Records Updated'); END;

70

Write a PL/SQL program that increases the salaries of the employees of the EMP table such that Manager Salary is increased by 10%,Clerk's Salary is increased by 8% and 'salesman' salary by 5% ?
Declare Cursor SAL_CURSOR IS Select Empno,Job from Emp; Post Emp.Job%TYPE; Ecode Emp.Empno%TYPE; Begin OPEN sal_cursor; LOOP FETCH sal_cursor INTO Ecode,Post; Exit when sal_cursor%NOTFOUND: IF POST='MANAGER' THEN UPDATE Emp SET sal=sal*1.10 where Empno=Ecode; ELSIF POST='CLERK' THEN UPDATE Emp SET sal=sal*1.08 where Empno=Ecode; ELSIF POST=' SALESMAN' THEN UPDATE Emp SET sal=sal*1.05 where Empno=Ecode; END IF; END LOOP;
71

CLOSE sal_cursor; END;

72

Write a PL/SQL program that determines the top 4 employees with respect to salaries ?
Declare Cursor TOP_CURSOR IS Select Ename,sal FROM emp order By sal desc; Salary Emp.sal%TYPE; Name Emp.Ename%TYPE; N NUMBER; Begin OPEN TOP_CURSOR; IF TOP_CURSOR%ISOPEN THEN LOOP Fetch Top_Cursor INTO Name,Salary; N:=Top_Cursor% ROWCOUNT;

EXIT WHEN N>4 OR top_cursor%NOTFOUND; dbms_output.put_line(N || ' ' || Name|| ' END LOOP; END IF; CLOSE Top_Cursor; END; ' ||salary);

73

Write a PL/SQL program to calculate maximum,minimum and average salary department wise and display the results ?
Declare Cursor INFO_CURSOR IS Select Deptno,max(sal),Min(sal),Avg(sal) FROM EMP GROUP BY DEPTNO; Dcode Emp.Deptno%TYPE; Maxsal Emp.sal%TYPE; Minsal EMP.sal%TYPE; Avgsal Emp.sal%TYPE; BEGIN OPEN INFO_cursor; LOOP Fetch INFO_CURSOR INTO Dcode,Maxsal,Minsal,Avgsal; Exit when INFO_CURSOR%NOTFOUND; dbms_output.put_line (Dcode|| ' '||Maxsal || ' '||Minsal||' '||Avgsal); END LOOP; CLOSE INFO_CURSOR; END;

74

Write a PL/SQL program to display the department name and location using the single variable of % ROWTYPE ?
Declare Cursor Dept_Cursor IS Select * from Dept; D_Record Dept % ROWTYPE; BEGIN OPEN DEPT_CURSOR; LOOP Fetch Dept_Cursor INTO D_Record; Exit when Dept_Cursor % NOTFOUND; dbms_output.put_line(D_Record.Dname || ' END LOOP: CLOSE Dept_Cursor; END; '|| D_Record.LOC);

75

Consider you are provided with a table containing employee basic information as follows ENO ,ENAME and GENDER.Suppose the gender of all employees are recorded in such a way that for female 'M' is written and for male 'F' is written.Write a program in PL/SQL to correct the gender code of all the employees.
Declare CURSOR G_CURSOR IS SELECT ENO, GENDER FROM EMP; GENDER12 EMP.GENDER%TYPE; EC EMP.ENO%TYPE; BEGIN OPEN G_CURSOR; LOOP FETCH G_CURSOR INTO EC,GENDER12; EXIT WHEN G_CURSOR%NOTFOUND; IF GENDER12 = 'M' then UPDATE EMP SET GENDER = 'F' WHERE ENO=EC; ELSIF GENDER12 = 'F' then UPDATE EMP SET GENDER = 'M' WHERE ENO= EC; END IF;
76

END LOOP; CLOSE G_CURSOR; END;

77

Write a PL/SQL program to print the department number and name of DEPT Table using cursor FOR loop ?
Declare Cursor Dept_Cursor IS Select Deptno,Dname from Dept; BEGIN FOR V IN DEPT_CURSOR LOOP dbms_output.put_line(V.Deptno || ' END LOOP; END: '||V.Dname);

78

Write a PL/SQL program to print the department name and their corresponding employee information .Ensure that department name is not displayed with each record.
Declare Cursor Dep_Cur IS Select Deptno,Dname from Dept; Cursor Emp_Cur (Dno Number) IS Select * from Emp where Deptno=Dno; Dcode Dept.Deptno%TYPE; Name Dept.Dname%TYPE; BEGIN OPEN Dep_Cur; LOOP fetch Dep_Cur INTO dcode, Name; Exit when Dep_Cur %NOTFOUND; dbms_output.put_line (NAME); dbms_output.put_line ('............'); FOR E IN EMP_Cur (Dcode) LOOP dbms_output.put_line (RPAD(E.ENAME, 10) ||' '|| RPAD (E.JOB, 10) || ' ' || E.sal); END LOOP;
79

CLOSE Dep_Cur ; END ;

80

Write a PL/SQL program to display the information of a given department number


Declare Cursor EMP_DATA IS Select EMPNO,ENAME,SAL From EMP where Deptno=&Deptno; ECODE Emp.Empno%TYPE; Name Emp.Ename%TYPE; Salary Emp.sal%TYPE; Begin OPEN EMP_DATA; LOOP FETCH Emp_data INTO Ecode,Name,Salary; EXIT WHEN Emp_data%NOTFOUND; dbms_output.put_line(Ecode||' END LOOP; CLOSE Emp_data; END; '||Name||' '||salary);

81

Write a PL/SQL program to list the top n salaries and the employee names to which they corresponds. Consider the case where several employees have the same salary. IF one person is listed,then all people who have the same salary should also be listed.
Declare Cursor sal_Cursor IS Select Distinct sal from Emp order by sal desc; Cursor Emp_Cursor (s NUMBER) IS Select Ename from Emp where sal=S; NAME EMP.ENAME%TYPE; Salary Emp.sal%TYPE; N NUMBER; Begin N:= :N; Open Sal_Cursor ; LOOP Fetch Sal_Cursor INTO salary; EXIT WHEN SAL_CURSOR%ROWCOUNT>N OR SAL_CURSOR% NOTFOUND; OPEN EMP_CURSOR(SALARY); LOOP
82

FETCH EMP_CURSOR INTO NAME; Exit when Emp_cursor%NOTFOUND; dbms_output.put_line (RPAD (Name,10) || ' END LOOP; Close Emp_Cursor; END LOOP; CLOSE Sal_Cursor; END: '|| Salary);

83

Write a program in PL/SQL to list the records of emplyees from EMP table within a given range of salaries ?
Declare Cursor Emp_Cursor(N1 Number,N2 number) IS Select ename,sal from EMP where sal>=N1 and sal<=N2; Salary Emp.sal%TYPE; NAME EMP.ENAME%TYPE; M number; N number; Begin M:= : M; N:= :N; Open Emp_cursor(M,N); LOOP Fetch Emp_Cursor INTO Name,Salary; Exit when Emp_Cursor%NOTFOUND; dbms_output.put_line(RPAD (Name, 10)|| ' '||salary); END LOOP; CLOSE EMP_CURSOR; END;

84

Procedures to perform selection on emp table DECLARE ecode employee.eno%type; ename employee.name%type; procedure selection(ecode number) as BEGIN select name into ename from employee where eno=ecode; END selection; BEGIN ecode:= :ecode; selection(ecode); END; Output:select name from employee where eno=6; data selected Statement processed

85

WritePL/SQL procedure to perform updation on emp table DECLARE ecode employee.eno%type; sal employee.salary%type; procedure updation(ecode number) as BEGIN update employee set salary=salary+500 where eno=ecode; END updation; BEGIN ecode:= :ecode; updation(ecode); END; Output:Statement processed. select * from employee; update employee set salary=salary+500 where eno=7; salary updated

86

Write PL/SQL procedure to perform deletion on emp table DECLARE ecode employee.eno%type; procedure deletion(ecode number) as BEGIN delete from employee where eno=ecode; END deletion; BEGIN ecode:= :ecode; deletion(ecode); END; Statement processed select * from employee;

87

Write a local procedure that accepts two numbers using parameters. Declare first_num number; second_num number; result number; PROCEDURE product ( a number,b IN number,c out number) Begin c := a * b; end product; Begin first_num := : first_num; second_num:= : second_num; product(first_num,second_num,result); dbms_output.put_line( 'The Product is '|| result); END; Output:Enter value for first_num: 4 Enter value for second_num: 2 The product is 8
88

Write a procedure to increase the salary of an employee who employee number is given by a user entered amount.
Declare ecode emp.empno%Type; inc_amount emp.sal%Type; procedure salary_in(ecode number,amount number) AS sal_null exception; current_sal number; Begin Select sal INTO current_sal From Emp where empno=ecode; IF current_sal is not NULL then Update emp set sal =sal+amount where empno=ecode; dbms_output.put_line ('data updated'); ELSE raise sal_null; END IF; EXCEPTION when no_data_found then dbms_output.put_line ('empid doesnot exist'); when sal_null then dbms_output.put_line( 'salary should not be null');
89

END salary_in; Begin ecode := :code; inc_amount := :inc_amount; SALARY_IN(ecode, inc_amount); END;

90

A stored procedure that accepts two numbers and displays the product of two number ?
CREATE OR REPLACE PROCEDURE product (a number,b number) AS C number; BEGIN C := a * b; dbms_output.put_line( ' The product is ' || c); END product;

Output:Enter value for a: 4 Enter value for b: 2 The product is 8

91

A PL/SQL program to call a stored procedure is created below:


Declare A number; B number; BEGIN A := : A; B := : B; Product (A,B); END;

92

Create a stored procedure that displays senior most member of each department. The seniority is judged on the basis of hire date.
Create or Replace Procedure Senoir AS Cursor Sen_cur IS Select Deptno,min(Hiredate) Sen_date FROM EMP GROUP BY deptno; Name emp.ename%TYPE; Begin dbms_output.put_line('Dept '|| ' '||'Name '||' '||'Seniority Date'); For i IN sen_cur LOOP Select Ename INTO name FROM emp where hiredate=I.sen_date; dbms_output.put_line(I.deptno || ' (I.sen_date, 20); END LOOP; END Senior; ' || LPAD(Name, 10) ||LPAD

93

Create a stored procedure to debit a bank account. The user must enter the account number and amount to be debited.The minimum balance in the account should be 500. Suppose that a table BANK contains the account number and balance fields and has 10 records into it.
Create or Replace Procedure chk_balance(ACC number,Amount number)AS LESS_balance EXCEPTION; curr_amount Number (8,2); Begin Select balance INTO curr_amount FROM Bank where Accno = Acc; IF curr_amount>500 THEN UPDATE Bank set balance = balance-amount Where accno = acc; dbms_output.put_line ('updation successful'); ELSE dbms_output.put_line(' Minimum balance should be 500'); END IF; EXCEPTION When No_data_found Then dbms_output.put_line('Acc number '|| Acc||'not exists'); END chk_balance;

94

Create a stored procedure that deletes a record of a given employee number from EMP table. It should display the records before deletion and after deletion.
CREATE OR REPLACE PROCEDURE GETINFO AS CURSOR EMP_CUR IS SELECT * FROM EMP; BEGIN FOR I IN EMP_CUR LOOP DBMS_OUTPUT.PUT_LINE( I.EMPNO ||' I.ENAME); END LOOP; END GETINFO; OUTPUT Procedure created. Now we shall create another procedure CREATE OR REPLACE PROCEDURE DEL_EMP(ECODE NUMBER) AS ENO NUMBER; BEGIN SELECT EMPNO INTO ENO FROM EMP WHERE EMPNO=ECODE;
95

'||

DBMS_OUTPUT.PUT_LINE(BEFORE DELETION'); GETINFO; DELETE FROM EMP WHERE EMPNO=ENO; IF (SQL%FOUND) THEN DBMS_OUTPUT.PUT_LINE('AFTER DELETION')' GETINFO; END IF; EXCEPTION WHEN NO_DATA_FOUND THEN DOES END; DBMS_OUTPUT.PUT_LINE('EMPNO '|| ECODE|| ' NOT EXIST');

96

Create a function to calculate the product of two numbers and then return these values.
Declare A number; B number; RESULT number; Function product (A number,B number) Return number AS C number; Begin C := A * B; Return(C); End product; Begin A := :A; B := :B; RESULT := product(A,B); dbms_output.put_line (' Product = '|| RESULT); END;

97

Output:Enter value for a: 4 Enter value for b: 3 Product 12

98

Create a function to display the salary of an employee from EMP table whose employee number is given .
Declare Ecode emp.empno%TYPE; Salary emp.sal%TYPE; Function Calc_sal(E number) Return number AS S Emp.sal %TYPE; Begin Select sal INTO S FROM Emp where Empno =Ecode; Return S; EXCEPTION when NO_DATA_FOUND then return 0; END calc_sal; Begin Ecode := :Ecode; Salary := calc_sal (Ecode); IF salary <> 0 THEN dbms_output.put_line('salary = || salary); ELSE dbms_output.put_line(' Employee does not exit');

99

END IF; END;

100

Create a stored function that computes the greatest of three numbers.


Create or Replace Function Greate (A number, B number,C number) Return number AS Begin IF (A>B AND A>C) THEN Return A; ELSIF(A<B AND B>C) THEN Return b; ELSE Return C; END IF; END Greatest;

Output:-

Enter value for a: 3 Enter value for b: 5 Enter value for c:1 b

101

Write a stored function that return the information for an employee whose 'empno' is begin entered by the user from EMP table. Make use of % ROWTYPE as a return data type ?
Create or Replace function Emp_info (Ecode number) Return EMP%ROWTYPE AS S EMP%ROWTYPE; Begin Select * INTO S from EMP where Empno = Ecode; Return S; END emp_info;

OUTPUT function created.

Thus a stored function ,'Emp_info' is created which is then called in subsequent program.
Declare A emp%ROWTYPE; Ecode emp.empno%type; Begin Ecode := : Ecode;

102

A := Emp_info (Ecode); dbms_output.put_line('Name ='|| A. Ename); dbms_output.put_line('Post ='|| A.Job); dbms_output.put_line('Sal= '|| A.Sal); EXCEPTION WHEN NO_DATA_FOUND then dbms_output.put_line ('No empno found'); END;

103

Create a stored function TAX that returns the tax information of an employee from EMP table where each employee has a salary. Salary Less than or equal to 1000 Greater than 1000 but less than or equal to 2000 Greater than 2000 TAX No tax 10% of salary above 1000 Above tax plus 20% of salary above 2000

CREATE OR REPLACE FUNCTION TAX (S IN NUMBER) RETURN NUMBER IS BEGIN IF (S<=1000) THEN RETURN 0; ELSIF (S>1000 AND S>=2000) THEN RETURN (( S-1000)* 0.10); ELSE RETURN(100 + (s-2000)*0.20); END IF; END TAX;

104

Create a function that concatenates row values into a single column values .
CREATE OR REPLACE FUNCTION rowcount (q IN VARCHAR2) RETURN VARCHAR2 IS ret VARCHAR2 (2000); hold VARCHAR2(2000); cur sys_refcursor; BEGIN OPEN cur FOR q; LOOP FETCH CUR INTO HOLD; EXIT WHEN cur%NOTFOUND; IF ret ISNULL THEN ret := hold; ELSE ret:= ret ||' , ' || hold; END IF; END LOOP; Return ret; END rowcount;

105

Create a PL/SQL program that fetch the Department name and location of the given department number,and if department number doesn't exist then program will raise the user-defined exception?
Declare Location Dept.Loc%Type; Name Dept.Dname%Type; Dno Dept.DeptNo%Type; Deptno_eRR EXCEPTION; Begin Dno := :Dno; if Dno not IN (10,20,30,40) THEN RAISE deptno_err; END IF; Select Dname,Loc INTO Name, Location FROM DEPT where Deptno=Dno; dbms_output.putline('Location= ' || Location); EXCEPTOIN When Deptno_ERR THEN dbms_output.put_line ('Deptno doesnot exist'); End;

106

Write PL/SQL package which contains function to return salary of a given employee code,a procedure which displays employees of given department number abd another procedure that increment the salary of a given employee Package Specification Create or replace package emp_pack AS Function sal_check(ecode number) return; Procedure emp_info(dno number); Procedure sal_inc (ecode number); END emp_pack; Package Body Create or replace package body emp_pack AS Function sal_check (ecode number) return number AS Salary emp.sal%TYPE; BEGIN Select sal into salary from emp where empno=ecode; Return salary; Exception When no_data_found then Return 0; END sal_check;

107

Procedure emp_info(dno number) as Cursor emp_cur is Select * from emp where deptno=dno; Begin For I in emp_cur LOOP Dbms_output.put_line(I.ename || || i.sal); END LOOP; END emp_info; Procedure sal_inc(ecode number) as BEGIN Update emp set sal=sal+100 where empno=ecode; If(SQL%FOUND) THEN Dbms_output.put_line(data updated); Else Dbms_output.put_line(empno does not exists); END IF; END sal_inc; END emp_pack;

108

Write PL/SQL packages which consist of procedure that updates the marks of the students and a function that returns the percentage of marks of a given student create or replace package emp_pack AS PROCEDURE update_marks ( rno number); FUNCTION percentage ( math number, dbms number, eng number, marks number)return number; END emp_pack; alter package emp_pack COMPILE body; create or replace package body emp_pack AS procedure update_marks (rno number ) AS BEGIN update std56 set marks=500 where rollno:= :rno; END update_marks; function percentage (math number, dbms number , eng number, total_marks number ) return number AS per number; begin total_marks=math+dbms+eng; per:= total_marks/300*100; return(per); END per; BEGIN math:= :math; dbms:= :dbms; eng:= :eng; per:= percentage(math,dbms,eng); dbms_output.put_line('per of student=' || per); END emp_pack;

109

Write PL/SQL package to create calculator create or replace package cal_pack AS procedure add (a number ,b number ); FUNCTION subtract (d number , e number ); FUNCTION division (p number , q number); FUNCTION multiply (x number , y number); END cal_pack; create or replace package body AS FUNCTION add (a number, b number )return number AS c number; BEGIN a:= :a; b:= :b; c:= a+b; dbms_output.put_line(' add of two numbers' || c); END add; create or replace package body AS FUNCTIONsubtract(d number, e number )return number AS r number; BEGIN d:= :d; e:= :e; r:= d-e; dbms_output.put_line(' subtract of two numbers' || r); END subtract; create or replace package body AS FUNCTION division(p number, q number )return number AS r number;
110

BEGIN p:= :p; r:= :r; r:= p/q; dbms_output.put_line(' division of two numbers' || r); END division; create or replace package body AS FUNCTION multiply(x number, y number )return number AS z number; BEGIN x:= :x; y:= :y; z:= x/y; dbms_output.put_line(' multiply of two numbers' || z); END multiply; END cal_pack;

111

Write PL/SQL trigger whish will ensure that the salary entered is valid(i.e less than 10000) create or replace trigger check_sal before update on employee DECLARE sal number(8); BEGIN if(sal>10000) then dbms_output.put_line('salary entered is not valid'); END IF; END;

Output:update employee set salary=20000 where dept_no=20; salary entered is not valid statement processed

112

Write PL/SQL trigger which is fired when any deletion or updation is performed on emp table and the data is stoted to log table create or replace trigger emo_log before update or delete on employee for each row begin insert into log_table(eno,name,salary,dept_no,comm,desi,phone_no) values (:old.eno,:old.name,:old.salary,:old.dept_no,:old.comm,:old.desi,:o ld.phone_no); END; Output:delete from employee where salary=9000; statement processed

113

Write PL/SQL trigger whish when fired displays the difference between updated salary and the old salary of an employee create or replace trigger sal_diff after update on employee for each row DECLARE curr_sal number(7); new_salary number; BEGIN New_salary:= :new_salary; curr_sal=:old.salary-:new.salary; END; Output:Enter value for new_salary: 5000 Suppose old sal is 15000 Curr_sal:= 10000 Statement processed ;

114

S-ar putea să vă placă și