Oracle 9 | Control Flow | Pl/Sql

Oracle

Create Command Create command is used to create a Table or a relation. Syntax: Create table tablename (Field1 datatype, Field1 datatype,……., Field n datatype) SQL> create table emp (eno number (8), ename varchar2 (20), esal number (10)); Table created. Describe Command Describe command is used to see the description of a table. Syntax: Desc tablename SQL> desc emp; Name Null? Type ------------------------------- -------- ---ENO NUMBER(8) ENAME VARCHAR2(20) ESAL NUMBER(10) Insert command Insert command is used to insert the values in a table. Syntax: insert into tablename values (value1, value2,….., value n) insert into emp values(1,”shyam”,5000); SQL> insert into emp values (&eno,'&ename',&esal); Enter value for eno: 1 Enter value for ename: suresh Enter value for esal: 20000 old 1: insert into emp values(&eno,'&ename',&esal) new 1: insert into emp values(1,'suresh',20000) 1 row created. SQL> / Enter value for eno: 2 Enter value for ename: ajay Enter value for esal: 15000 old 1: insert into emp values(&eno,'&ename',&esal) new 1: insert into emp values(2,'ajay',15000) 1 row created. SQL> / Enter value for eno: 3 Enter value for ename: vijay Enter value for esal: 18000 old 1: insert into emp values(&eno,'&ename',&esal) new 1: insert into emp values(3,'vijay',18000) 1 row created. SQL> /

Enter value for eno: 4 Enter value for ename: arun Enter value for esal: 17 old 1: insert into emp values(&eno,'&ename',&esal) new 1: insert into emp values(4,'arun',17) 1 row created. Select Command Select command is used to view the table. Syntax: Select columnname from emp Select columnname1, columnname2, columnname3 from emp Select * from emp SQL> select * from emp; ENO ENAME ESAL --------- -------------------- --------1 suresh 20000 2 ajay 15000 3 vijay 18000 4 arun 17 Update Command Update command is used to update the values of a table. Syntax: update tablename set columnname=value where columnname=value SQL> update emp set esal=17000 where eno=4; 1 row updated. SQL> select * from emp; ENO ENAME ESAL --------- -------------------- --------1 suresh 20000 2 ajay 15000 3 vijay 18000 4 arun 17000 Alter Command : Alter command is used to alter the structure of a table. Alter command has three attributes namely add, modify and drop. Add: Adding a column in a table. Modify: Modify the size of a column. Drop: Dropping a column of a table. Syntax: Add Column Alter table tablename add (column datatype) SQL> alter table emp add (city varchar2 (15)); Table altered. SQL> select * from emp;

ENO ENAME ESAL CITY --------- -------------------- --------- ---------1 suresh 20000 2 ajay 15000 3 vijay 18000 4 arun 17000 SQL> update emp set city='CHD 'where eno=1; 1 row updated. SQL> update emp set city='CHD 'where eno=2; 1 row updated. SQL> update emp set city='AMBALA' where eno=3; 1 row updated. SQL> update emp set city='banur' where eno=4; 1 row updated. SQL> select * from emp; ENO ENAME ESAL CITY --------- -------------------- --------- ----------1 suresh 20000 CHD 2 ajay 15000 CHD 3 vijay 18000 AMBALA 4 arun 17000 banur SQL> desc emp; Name Null? Type ------------------------------- -------- ---ENO NUMBER(8) ENAME VARCHAR2(20) ESAL NUMBER(10) CITY VARCHAR2(15) Syntax: Modify Column Alter table tablename modify (column datatype) SQL> alter table emp modify(city varchar2(20)); Table altered. SQL> desc emp; Name Null? Type ------------------------------- -------- ---ENO NUMBER(8) ENAME VARCHAR2(20) ESAL NUMBER(10) CITY VARCHAR2(20)

Syntax: Drop Column Alter table tablename drop column columnname SQL> alter table emp drop column city ; Table altered. SQL> desc emp; Name Null? Type ------------------------------- -------- ---ENO NUMBER(8) ENAME VARCHAR2(20) ESAL NUMBER(10) Delete Command Delete command is used to delete a row from a table. Syntax: Delete from tablename where cloumnname=value SQL> delete from emp where eno=3; 1 row deleted. SQL> select * from emp; ENO ENAME ESAL CITY --------- -------------------- --------- -------------------1 suresh 20000 CHD 2 ajay 15000 CHD 4 arun 17000 banur Truncate command: Truncate command is used to truncate or empty or delete all rows of a table. Syntax:Truncate table tablename SQL> truncate table emp; Table truncated. SQL> select * from emp; no rows selected SQL> desc emp; Name Null? Type ------------------------------- -------- ---ENO NUMBER(8) ENAME VARCHAR2(20) ESAL NUMBER(10) CITY VARCHAR2(20) Drop Command: Drop command is used to drop the structure of a table permanently. Syntax: Drop table tablename

SQL> drop table emp; Table dropped. SQL> desc emp; ERROR: ORA-04043: object emp does not exist Slash Command(/) : Slash command is used to rerun the previous command. SQL> create table employee(eno number(8),ename varchar2(20),esal number(10)); Table created. SQL> insert into employee values(&eno,'&ename',&esal); Enter value for eno: 1 Enter value for ename: arun Enter value for esal: 12000 old 1: insert into employee values(&eno,'&ename',&esal) new 1: insert into employee values(1,'arun',12000) 1 row created. SQL> / Enter value for eno: 2 Enter value for ename: raani Enter value for esal: 14000 old 1: insert into employee values(&eno,'&ename',&esal) new 1: insert into employee values(2,'raani',14000) 1 row created. SQL> / Enter value for eno: 3 Enter value for ename: raaj Enter value for esal: 15000 old 1: insert into employee values(&eno,'&ename',&esal) new 1: insert into employee values(3,'raaj',15000) 1 row created. SQL> / Enter value for eno: 4 Enter value for ename: harpreet Enter value for esal: 17000 old 1: insert into employee values(&eno,'&ename',&esal) new 1: insert into employee values(4,'harpreet',17000) 1 row created. SQL> select * from employee ENO ENAME ESAL --------- -------------------- ---------

-----------.sec-12b chd 20 Sumit Mkt 12000 #897/a amb 30 Harish Finance 23000 #986 Mohali 40 Avneet sales 15000 #908 Pkl 50 Neha Admin 16000 #765. COMPARISON/RELATIONAL OPERATOR:SQL> select * from emp1 where empno!=20.-------------.esalary*12 "Annual Salary" from emp1.---------. EMPNO ENAME EDEP ESALARY EADD ELOC -------------. OPERATORS:1.-------------.-----------------------. employee no employee name employee department -----------------.---------------------------------10 Amit HR 20 Sumit Mkt 30 Harish Finance 40 Avneet sales 50 Neha Admin 60 Rajat Prod 6 rows selected.d Pat 60 Rajat Prod 24000 #127. EMPNO ENAME EDEP ESALARY EADD ELOC ----------. 2.-------------.-------------.edep "employee department" from emp1. SQL> select * from emp1. EMPNO ENAME Annual Salary ------------.----------------- .b Banur 6 rows selected. ARITHMETIC OPERATOR:SQL> select empno.---------------------10 Amit 120000 20 Sumit 144000 30 Harish 276000 40 Avneet 180000 50 Neha 192000 60 Rajat 288000 6 rows selected.ename.----------------.----------.1 arun 12000 2 raani 14000 3 raaj 15000 4 harpreet 17000 COLUMN ALIASES:SQL> select empno "employee no".--------------10 Amit HR 10000 #1276.ename "employee name".----------.

10 30 40 50 60 Amit Harish Avneet Neha Rajat HR Finance sales Admin Prod 10000 23000 15000 16000 24000 #1276.-------------.d Pat #127.sec-12b chd C) LIKE:SQL> select * from emp1 where ename like 'A%' EMPNO ENAME EDEP ESALARY EADD ELOC ---------.-------------10 Amit HR 10000 #1276. EMPNO ENAME EDEP ESALARY EADD ELOC ------------.-------.sec-12b chd 20 Sumit Mkt 12000 #897/a amb 40 Avneet sales 15000 #908 Pkl 50 Neha Admin 16000 #765.sec-12b chd 40 Avneet sales 15000 #908 Pkl 3. EMPNO ENAME EDEP ESALARY EADD ELOC ----------. EMPNO ENAME EDEP ESALARY EADD ELOC ------------.-----------.---------.-----------. EMPNO ENAME EDEP ESALARY EADD ELOC ------------.-----------------10 Amit HR 10000 #1276.------------.----------.sec-12b chd #986 Mohali #908 Pkl #765.----------------.-------------------.------------.d Pat B) IN:SQL> select * from emp1 where edep in('HR'.---------.'Sales').--------.---------.------------.--------------10 Amit HR 10000 #1276.-------------------.-------------.--------------30 Harish Finance 23000 #986 Mohali B) OR OPERATOR:SQL> select * from emp1 where esalary=15000 or edep='HR'.---------.------------------------. LOGICAL OPERATOR:A) AND OPERATOR:SQL> select * from emp1 where esalary=23000 and edep='Finance'.--------------10 Amit HR 10000 #1276.------------.sec-12b chd 40 Avneet sales 15000 #908 Pkl .b Banur A) BETWEEN:SQL> select * from emp1 where esalary between 10000 and 20000.

B) UNION ALL:SQL> select empno from emp1 union all select empno from emp2. A) UNION:SQL> select empno from emp1 union select empno from emp2. EMPNO -------------10 20 30 40 50 60 70 80 .-----------. EMPNO ENAME ESALARY ----------. SET OPERATORS:We created two tables emp1 and emp2 with the following enteries:SQL> select * from emp2.4.sec-12b chd 20 Sumit Mkt 12000 #897/a amb 30 Harish Finance 23000 #986 Mohali 40 Avneet sales 15000 #908 Pkl 50 Neha Admin 16000 #765.-------------.d Pat 60 Rajat Prod 24000 #127. EMPNO ENAME EDEP ESALARY EADD ELOC -------------.---------.-------------. EMPNO --------10 20 30 40 50 60 70 80 90 9 rows selected.-----------70 Mohit 90000 80 Roshan 25000 90 Ajay 17000 30 Harish 23000 SQL> select * from emp1.b Banur 6 rows selected.----------.--------------10 Amit HR 10000 #1276.

. Table Created. Referential Integrity Constraint: FOREIGN KEY 1) DOMAIN LEVEL CONSTRAINT:We are inserting a null value in ename field of emp2 table.They are used to maintain the consistency of the database. CHECK 2. Entity Integrity Constraint: PRIMARY KEY. So by dropping the table emp2 and creating it again implementing a NOT NULL constraint: NOT NULL:Create table emp2(empno number(3). 1 row created.We have three categories of constraints: 1.ename varchar2(30) constraint emp_en_nn not null. EMPNO --------30 D) MINUS:SQL> select empno from emp1 minus select empno from emp2. EMPNO --------10 20 40 50 60 CONSTRAINTS:Constraints are the rules and regulations which we impose on our table fields.8000).esalary number(10)). Domain Level Constraint : NOT NULL . C) INTERSECT:SQL> select empno from emp1 intersect select empno from emp2.90 30 10 rows selected.Constraint can be applied at the time of table creation. SQL> select * from emp2 EMPNO ENAME ESALARY -----------.----------70 Mohit 90000 80 Roshan 25000 90 Ajay 17000 30 Harish 23000 100 8000 Now we implement a NOT NULL constraint on emp2 table. UNIQUE 3.-----------. SQL> insert into emp2 values(100.''.

Table altered. Table altered. Conversion Functions Let us discuss them SINGLE ROW FUNCTIONS:A) Character Functions:i) INITCAP:It makes the first Charcter of the string as capital. Date Functions 4. SQL FUNCTIONS:We have Single row functions and Group functions in SQL. alter table emp add constraint emp_eno_pk primary key(eno) * ERROR at line 1: ORA-02437: cannot enable (SCOTT. B) ENTITY INTEGRITY CONSTRAINTS:Entity Integrity constraints can also be created at both times at the time of creation and at the time of alteration of a table. EMPNO INITCAP(ENAME) ESALARY --------. At the time of alteration: SQL> alter table emp2 add constraint emp_sal_chk check(esalary>5000). UNIQUE:SQL> alter table emp add constraint emp_dn_uq unique(dname). Single row functions are further divided into following categories: 1.EMP_ENO_PK) .CHECK:Check constraint can be applied at the time of table creation and at the time of alteration as well. PRIMARY KEY:SQL> alter table emp add constraint emp_eno_pk primary key(eno).ename varchar2(30). Table altered. Miscellaneous Functions 5. Numeric Functions 3. At the time of creation: Create table emp2(empno number(3).---------------------------10 Amit 10000 .initcap(ename). Character Functions 2.esalary from emp1. SQL> select empno.esalary number(10) constraint emp_sal_chk check(esalary>5000)).primary key violated C) REFERENTIAL INTEGRITY CONSTRAINTS:FOREIGN KEY:SQL> alter table emp add constraint emp_dno_fk foreign key(dno) references dep(dno). Table Created.

esalary from emp1.---------------------------10 amit 10000 20 sumit 12000 30 harish 23000 40 avneet 15000 50 neha 16000 60 rajat 24000 6 rows selected.'it') from emp1 where empno=10. EMPNO LOWER(ENAME) ESALARY --------.esalary from emp1. SQL> select empno. EMPNO UPPER(ENAME) ESALARY --------. RT -am .---------------------------10 AMIT 10000 20 SUMIT 12000 30 HARISH 23000 40 AVNEET 15000 50 NEHA 16000 60 RAJAT 24000 6 rows selected. SQL> select ltrim ('amit'.upper(ename).lower(ename). iv) LTRIM:It trims the given set of characters from a string from left. SQL> select empno.'am') from emp1 where empno=10.20 30 40 50 60 Sumit Harish Avneet Neha Rajat 12000 23000 15000 16000 24000 6 rows selected. LT -it 1 rows selected. Ii) LOWER:It converts the field into lowercase. v)RTRIM:It trims the given set of characters from a string from right. SQL> select rtrim ('amit'. iii) UPPER:It converts the field into uppercase.

4. EMPNO LENGTH(ENAME) --------. EMPNO REPLAC --------. vii)REPLACE:It replaces a character by multiple characters.5) from dual. vi)TRANSLATE:It replaces a character by a single character. SQL> select empno. SQL> select empno.'i'.'ee') from emp1 where empno=20. viii)LENGTH:It counts the number of characters in a string.length(ename) from emp1.translate('neha'. EMPNO TRAN --------.'u') from emp1 where empno=50.10.1 rows selected. SUBST ----LOWOR x) LPAD:SQL> select lpad('amit'. ix) SUBSTR:It fetches the given substring from a string.'a'.---50 nehu 1 rows selected.------------10 4 20 5 30 6 40 6 50 4 60 5 6 rows selected.-----20 sumeet 1 rows selected. xi) RPAD:- .'*') from dual. SQL> select substr('HELLOWORLD'. LPAD('AMIT ---------******amit 1 rows selected. replace('sumit'. SQL> select empno.

'world') from dual.'*')from dual. .3) from dual. ABS(-31) ------------31 ii) CEIL():SQL> select ceil(100.'E') -----------------2 B) NUMERIC FUNCTIONS:i) ABS():SQL> select abs(-31) from dual.10. CONCAT('HE ---------Helloworld xiii) INSTR:SQL> select instr('hello'.23) ------------100 iv) POWER():SQL> select power(2.23) from dual.23) -----------101 iii) FLOOR():SQL> select floor(100. CEIL(100. FLOOR(100.'e') from dual.23) from dual. RPAD('AMIT ---------------amit****** 1 rows selected.SQL> select rpad('amit'. INSTR('HELLO'. xii) CONCAT:SQL> select concat('hello'.

3) ---------8 v) MOD():SQL> select mod(10.47 vii) TRUNCATE():SQL> select trunc(23.6) from dual.3) --------1 vi) ROUND():SQL> select round(23. TRUNC(23.'15-oct-09') from dual. ADD_MONTH --------29-MAY-10 ii. MOD(10.467235. SYSDATE --------29-NOV-09 iii.2) from dual.461235. ADD_MONTHS:SQL> select add_months(sysdate.467235. ROUND(23.46 viii) SQRT():SQL> select sqrt(4) from dual.461235.2) from dual. SQRT(4) --------2 C) DATE FUNCTIONS:i.2) -----------------23.3) from dual.'15-OCT-09') ----------------------------------- . MONTHS_BETWEEN:SQL> select months_between(sysdate. SYSDATE:SQL> select sysdate from dual.2) -----------------23.POWER(2. MONTHS_BETWEEN(SYSDATE.

UID:SQL> select uid from dual. TO_CHAR():SQL> select to_char(sysdate) from dual.4819736 iv. TO_NUMBER('123') ---------------123 iii. TO_CHAR(S --------29-NOV-09 ii.1. NEXT_DAY( --------06-DEC-09 D) MISCELLANEOUS FUNCTIONS:i. USER -----------------------------SCOTT E) CONVERSION FUNCTIONS:i. TO_DATE():SQL> select to_date('29-NOV-09') from dual. UID --------20 ii. NEXT_DAY:SQL> select next_day(sysdate. TO_NUMBER():SQL> select to_number('123') from dual. TO_DATE(S --------29-NOV-09 . LAST_DAY:SQL> select last_day('14-jul-09') from dual. USER:SQL> select user from dual.'Sunday') from dual. LAST_DAY( --------31-JUL-09 v.

COUNT(*) --------5 JOINS SQL joins are used to query data from two or more tables. MAX(ESALARY) -----------24000 3) SUM:SQL> select sum(esalary) from emp1. Equii join 2.--------------. EQUII JOIN Return rows when there is at least one match in both tables. SUM(ESALARY) -----------85000 4) AVG:SQL> select avg(esalary) from emp1. Full Outer Join 4. Non Equii join 3. Self Join 1. based on a relationship between certain columns in these tables. SQL> select * from emp.e. Left Outer Join ii. MIN(ESALARY) -----------10000 2) MAX:SQL> select max(esalary) from emp1.GROUP FUNCTIONS 1) MIN:SQL> select min(esalary) from emp1. AVG(ESALARY) -----------17000 5) COUNT:SQL> select count(*) from emp1. Lets have a look at both the tables i. ENO ENMAE DNO --------. Right Outer Join iii.--------- . emp and dep table. Outer Join i. We have following type of joins:1.

e.-----------------.salgrade s where e.--------------. ENO ENAME ESAL --------.grade from emp2 e.losal and s. ENO ENAME ESAL GRADE --------.dno.eno.dep where emp.--------. .--------------.esal.e.-----------------1 A 5500 2 B 6500 3 C 14000 4 D 2200 5 E 25000 SQL> select * from salgrade.dep.--------1 A 10 4 D 10 2 B 20 5 E 20 3 C 30 DNAME --------------HR HR MKT MKT SALES 2. emp2 and salgrade table. SQL> select * from emp2.e. DNO DNAME DLOC --------. ENO ENMAE DNO --------.dno=dep.dname from emp.hisal.1 2 3 4 5 A B C D E 10 20 30 10 20 SQL> select * from dep.--------1 700 1200 2 1201 1400 3 1401 2000 4 2001 3000 5 3001 9999 Implementing non equii join on both tables: SQL> select e.ename.emp.eno.esal between s. GRADE LOSAL HISAL --------. NON-EQUII JOIN Lets have a look at both the tables i.dno.emp.enmae.s.--------4 D 2200 4 1 A 5500 5 2 B 6500 5 3.---------10 HR Chd 20 MKT Moh 30 SALES Banur Implementing equii join on both tables: SQL> select emp. OUTER JOIN SQL> select * from emp.

enmae. ii. ii.--------. SQL> select * from dep.dep where emp.--------.emp.dno=dep.'Pkl').emp. ENO ENMAE DNO DNAME --------.dno(+).dno.dno(+)=dep.--------------1 A 10 HR 4 D 10 HR 2 B 20 MKT 5 E 20 MKT 3 C 30 SALES ADMIN 6 rows selected.dno(+) Return rows when there is a match in one of the tables.---------10 HR Chd 20 MKT Moh 30 SALES Banur 40 ADMIN Pkl i.dno.dno.--------1 A 10 2 B 20 3 C 30 4 D 10 5 E 20 6 F 70 SQL> insert into dep values (40.--------. even if there are no matches in the right table.--------------.enmae.--------------1 A 10 HR 4 D 10 HR 2 B 20 MKT 5 E 20 MKT 3 C 30 SALES 6 F 70 6 rows selected. even if there are no matches in the left table.dname from emp.--------------- . ENO ENMAE DNO DNAME --------.dno=dep.dno.dname from emp.dep where emp. FULL OUTER JOIN:SQL> select eno.emp.dname from emp.'ADMIN'.--------------.dno(+)=dep. ENO ENMAE DNO DNAME --------. RIGHT OUTER JOIN:SQL> select eno.--------------.enmae. DNO DNAME DLOC --------.dep where emp.--------------.--------------.ENO ENMAE DNO --------. 1 row created. LEFT OUTER JOIN Return all rows from the left table. Return all rows from the right table.dno and emp. SQL> select eno.

4.---------1 A 2 B 4 D 3 C 5 E 6 F 6 rows selected.--------------------------------1 A Peon C 4 D Peon C 6 F Clerk C 2 B Clerk E DESIGNATION MGR --------------------Peon 3 Clerk 5 Peon 3 Manager Manager Clerk 3 SUB QUERIES Nested queries are known as sub queries.e1.mgr=e2. ENO ENAME DESIGNATION ENAME --------.1 4 2 5 3 6 A D B E C F 10 10 20 20 30 70 HR HR MKT MKT SALES ADMIN 7 rows selected.eno. ENAME ---------C . SQL> select * from emp2.e1.ename. ENO ENAME --------.designation. ENO ENAME ESAL --------. SELF JOIN:Joins the table with itself. SQL> select e1.--------1 A 5500 2 B 6500 3 C 14000 4 D 2200 5 E 25000 QUERY1 : SELECT THE ENAMES FROM THE EMP TABLE WHOSE SALARY ARE GREATER THAN THE SALARY OF EMP WHOSE ENO IS 2. SQL> select ename from emp2 where esal>(select esal from emp2 where eno=2).emp3 e2 where e1.---------. SQL> select * from emp3.ename from emp3 e1.eno.e2.

SQL> select max(esal) from emp2 where esal<(select max(esal) from emp2).b SQL> create or replace view emp10(empno.---------.--------------10 Amit #1276. a virtual table. SQL> select eno.ename. MAX(ESAL) --------14000 VIEWS A view is.-------------------------10 Amit HR 10000 #1276.---------.empname. Rather.esalary from emp1. Syntax: CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition SQL> select * from emp1.-------------. .d 60 Rajat #127.sec-12b chd 20 Sumit Mkt 12000 #897/a amb 30 Harish Finance 23000 #986 Mohali 40 Avneet sales 15000 #908 Pkl 50 Neha Admin 16000 #765.b Banur 1. SQL> select * from emp10.ename. ENO ENAME ESAL --------.sec-12b 20 Sumit #897/a 30 Harish #986 40 Avneet #908 50 Neha #765. It does not physically exist.ename.-------------.-------------.empsal) as select empno.-------------.--------4 D 2200 QUERY3 : SELECT THE 2ND MAXIMUM SALARY OF THE EMP TABLE.d Pat 60 Rajat Prod 24000 #127.esal from emp2 where esal=(select min(esal)from emp2). in essence.eadd from emp1. it is created by a query joining one or more tables. View created. SIMPLE VIEW:SQL> create or replace view emp10 as select empno. EMPNO ENAME EADD -------------. EMPNO ENAME EDEP ESALARY EADD ELOC -------------.---------.E QUERY2 : SELECT THE DETAILS OF EMP WHOSE SALARY IS EQUAL TO THE MINIMUM SALARY.-----------.

e.--------------.dno. COMPLEX VIEW SQL> select * from emp. ENO ENMAE DNO --------.dno.dname from emp e.e.dno=d. SQL> select * from dep.--------1 A 10 2 B 20 3 C 30 4 D 10 5 E 20 6 F 70 6 rows selected.--------1 A 10 4 D 10 2 B 20 5 E 20 3 C 30 DROP VIEW SQL> drop view emp10.---------10 HR Chd 20 MKT Moh 30 SALES Banur 40 ADMIN Pkl SQL> create or replace view emp10 as select e. ENO ENMAE DNO --------. SQL> select * from emp10.View created. View created. select * from em0p10 * DNAME --------------HR HR MKT MKT SALES .d.--------------. DNO DNAME DLOC --------. View dropped.eno.dep d where e. SQL> select * from emp10. EMPNO --------10 20 30 50 60 EMPNAME -------------------Amit Sumit Harish Neha Rajat EMPSAL --------10000 12000 23000 16000 24000 2.enmae.--------------. SQL> select * from emp10.

DNO DNAME DLOC --------. insert into dep values(50.---------10 HR Chd 20 MKT Moh 30 SALES Banur 40 ADMIN Pkl SQL> create unique index i4 on dep(dname). SQL> insert into dep values(50. Index created.--------------. 1 row created.'HR'. Index created.'CHD').'HR'. SQL> select * from dep. DNO DNAME DLOC --------.---------10 HR Chd 20 MKT Moh 30 SALES Banur 40 ADMIN Pkl 50 HR1 Pat DROP INDEX .'Pat'). SQL> select * from dep.'HR1'.I4) violated SQL> insert into dep values(50. DNO DNAME DLOC --------.--------------.--------------.ERROR at line 1: ORA-00942: table or view does not exist INDEX SQL> select * from dep.---------10 HR Chd 20 MKT Moh 30 SALES Banur 40 ADMIN Pkl 50 HR1 Pat COMPOSITE INDEX SQL> create unique index d1 on dep (dno.dloc).'CHD') * ERROR at line 1: ORA-00001: unique constraint (SCOTT.

1) We can directly assign values to variables. one of which is a not null. you can use a variable. dept varchar2(10) NOT NULL := “HR Dept”. The General Syntax is: variable_name:= value. if you want to store the current salary of an employee. INTO statement. The General Syntax is: SELECT column_name INTO variable_name FROM table_name . 2) We can assign values to variables directly from the database columns by using a SELECT. * “salary” is a variable of datatype number and of length 6. where you can initialize a variable. Each variable declaration is a separate statement and must be terminated by a semicolon. Index dropped. We can assign values to variables in the two ways given below. • • • • • variable_name is the name of the variable. The value of a variable can change in the execution or exception section of the PL/SQL Block. DECLARE salary number(4). When a variable is specified as NOT NULL. For example. NOT NULL is an optional specification on the variable. datatype is a valid PL/SQL datatype.. value or DEFAULT valueis also an optional specification. The General Syntax to declare a variable is: variable_name datatype [NOT NULL := value ]. For example: The below example declares two variables.SQL> drop index d1. DECLARE salary number (6). you must initialize the variable when it is declared. IMPLEMENTING PL/SQL PL/SQL Variables These are placeholders that store the values that can change through the PL/SQL Block.

These are declared in a inner block and cannot be referenced by outside Blocks. 7> DECLARE 8> var_mult number. 4> BEGIN 5> var_num1 := 100.put_line('The employee ' || var_emp_id || ' has salary END. The variables declared in the inner blocks are not accessible to outer blocks.e. the Execution section of an outer block can contain inner blocks. Example: The below program will get the salary of an employee with id '1116' and display it on the screen. • • Local variables . it cannot be accessed after line 11. For Example: In the below example we are creating two variables in the outer block and assigning thier product to the third variable created in the inner block. Therefore. The variable 'var_mult' is declared in the inner block. 12> END. var_emp_id number(6) = 1116.put_line(var_salary).[WHERE condition]. dbms_output. Scope of Variables PL/SQL allows the nesting of Blocks within Blocks i.e. dbms_output. BEGIN SELECT salary INTO var_salary FROM employee WHERE emp_id = var_emp_id. Based on their declaration we can classify variables into two types. 3> var_num2 number. The variables 'var_num1' and 'var_num2' can be accessed anywhere in the block. 13> / . 11> END.These are declared in a outer block and can be referenced by its itself and by its inner blocks. DECLARE var_salary number(6). / ' || var_salary). 1> DECLARE 2> var_num1 number. 6> var_num2 := 200. so cannot be accessed in the outer block i. a variable which is accessible to an outer Block is also accessible to all nested inner Blocks. Global variables . 9> BEGIN 10> var_mult := var_num1 * var_num2.

PL/SQL supports programming language features like conditional statements. You can declare a constant and use it instead of actual value. • • • constant_name is the name of the constant i. If you do not assign a value to a constant while declaring it and try to assign a value in the execution section. VALUE . iterative statements. END. You cannot assign a value later. Next time when you want to increase the salary again you can change the value of the constant which will be easier than changing the actual value throughout the program. For example. You must assign a value to a constant at the time you declare it. . dbms_output. The General Syntax to declare a constant is: constant_name CONSTANT datatype := VALUE. The programming constructs are similar to how you use in programming languages like Java and C++.PL/SQL Constants As the name implies a constant is a value used in a PL/SQL Block that remains unchanged throughout the program. The word CONSTANT is a reserved word and ensures that the value does not change. you will get a error. to declare salary_increase.put_line (salary_increase).e. DECLARE salary_increase CONSTANT number(3). In this section I will provide you syntax of how to use conditional statements in PL/SQL programming. If you execute the below Pl/SQL block you will get error.It is a value which must be assigned to a constant when it is declared. A constant is a user-defined literal value. similar to a variable name. Conditional Statements in PL/SQL As the name implies. For example: If you want to write a program which will increase the salary of the employees by 25%. you can write code as follows: DECLARE salary_increase CONSTANT number (3) := 10. you can declare a constant and use it throughout the program. BEGIN salary_increase := 100.

ELSIF condtion2 THEN statement 3. END IF. else dbms_output. END IF 3) IF condition 1 THEN statement 1. end. END IF.put_line(‘No God’). ELSIF condition3 THEN statement2.IF THEN ELSE STATEMENT 1) IF condition THEN statement 1. statement 2. 4) IF condition1 THEN ELSE IF condition2 THEN statement1.g declare num number(3). if num>4 then dbms_output. ELSIF condtion2 THEN statement 3. ELSE statement 4. END IF. statement 2. ELSE statement 2. / Switch case: e.put_line(‘God’). begin num:=5. END IF. 2) IF condition 1 THEN statement 1.g accept num prompt ‘Enter a single no’. prompt . ELSE statement 4. e.

/ Or Declare Num:=2. End case. An EXIT condition must be specified in the loop.} END LOOP. End. {or EXIT WHEN condition.put_line(‘One’). / Iterative Statements in PL/SQL An iterative control Statements are used when we want to repeat the execution of one or more statements for specified number of times. These are similar to those in There are three types of loops in PL/SQL: • Simple Loop • While Loop • For Loop 1) Simple Loop A Simple Loop is used when a set of statements is to be executed at least once before the loop terminates.put_line(‘Sunday’). end case. when 2 then dbms_output. . The General Syntax to write a Simple Loop is: LOOP statements. When the EXIT condition is satisfied the process exits from the loop. begin case num1 when 1 then dbms_output. 1) Initialise a variable before the loop body. These are the important steps to be followed while using Simple Loop. otherwise the loop will get into an infinite number of iterations.put_line(‘Wrong’). 2) Increment the variable in the loop. Else Dbms_output. EXIT. Begin Case num When 1 then Dbms_output.declare num1 number:=&num.put_line(‘two’). end.

g . / 2) While Loop A WHILE LOOP is used when a set of statements has to be executed as long as a condition is true. 2) Increment the variable in the loop. The condition is evaluated at the beginning of each iteration. begin dbms_output. end. 3) EXIT WHEN statement and EXIT statements can be used in while loops but it's not done oftenly. e. e. end loop. Important steps to follow when executing a while loop: 1) Initialise a variable before the loop body. loop ctr:=ctrl+1. The General Syntax to write a WHILE LOOP is: WHILE <condition> LOOP statements.3) Use a EXIT WHEN statement to exit from the Loop.g declare ctr number(2):=0. dbms_output. The iteration continues until the condition becomes false. the statements in the loop is executed only once.put_line(‘Loop number:’||ctr). exit when ctr>10. END LOOP.put_line(‘the loop begins’). If you use a EXIT statement without WHEN condition.

’999’). The General Syntax to write a FOR LOOP is: FOR counter IN val1. begin dbms_output..put_line(‘Loop number’||to_char(ctr.End integer value. so it's not necessary to declare it explicity. while ctr<=10 loop dbms_output. The counter is always incremented by 1.Start integer value. / 3) FOR Loop A FOR LOOP is used to execute a set of statements for a predetermined number of times. Important steps to follow when executing a while loop: 1) The counter variable is implicitly declared in the declaration section. val2 . Iteration occurs between the start and end integer values given.put_line(‘The while loop begin’). ctr:=ctr+1. Simple for loop e. The loop exits when the counter reachs the value of the end integer. 2) The counter variable is incremented by 1 and does not need to be incremented explicitly.g . • • val1 . end.declare ctr number(2):=1. 3) EXIT WHEN statement and EXIT statements can be used in FOR loops but it's not done oftenly. END LOOP. end loop.val2 LOOP statements.

The following syntax illustrates the use of conditional logic: IF condition1 THEN statements1 ELSIF condition2 THEN statements2 ELSE statements3 END IF. 2. This conditional logic flows as follows: 1. end loop. and END IF keywords in PL/SQL for performing conditional logic. then statements2 is executed. End loop. statements2. THEN. End loop.put_line(‘Loop number’||ctr).put_line(‘hello’)..2)= 0 then Dbms_output. / Reverse for loop Begin For ctr in reverse 1.6 loop If MOD(I. ELSIF. statements1.begin for I in 1. If condition1 is false but condition2 is true. condition1 and condition2 are Boolean expressions that evaluate to true or false. 2. .5 loop dbms_output. / Find the mod of number using for Begin For I in 1. End. and statements3 are PL/SQL statements.10 loop Dbms_output. where 1.. end. ELSE. End if. / Table 1 You may use the IF..put_line(‘Loop counters is:’||i). If condition1 is true. End. then statements1 is executed.

SQL> set echo on SQL> SQL> DECLARE 2 v_a Number := 50 . 9 ELSIF v_Score >= 70 THEN 10 v_LetterGrade := 'C'. 11 END. --Percentage 3 v_LetterGrade Char(1). 7 ELSIF v_Score >= 80 THEN 8 v_LetterGrade := 'B'. 18 / Your Letter Grade is: B PL/SQL procedure successfully completed.40. 15 END IF. 13 ELSE 14 v_LetterGrade := 'E'. 16 DBMS_OUTPUT.----------------OSTATUS ---------- . If neither condition1 nor condition2 are true. We have created a table order_master with the following fields: SQL> select * from order_master. 3 v_b Number. 8 ELSE 9 v_b := 0. 11 ELSIF v_Score >= 60 THEN 12 v_LetterGrade := 'D'. then statements3 is executed. Use IF THEN ELSE IF set serveroutput on SQL> set echo on SQL> SQL> DECLARE 2 v_Score Number := 85. 10 END IF.--------. 7 DBMS_OUTPUT. 4 BEGIN 5 IF v_Score >= 90 THEN 6 v_LetterGrade := 'A'.PUT_LINE('Your Letter Grade is: ' || v_LetterGrade ). 12 / Hours b worked = 10 PL/SQL procedure successfully completed. ONO ITEM QUANTITY DDATE -------. 17 END.PUT_LINE('Hours b worked = ' || v_b). 4 BEGIN 5 IF v_a > 40 THEN 6 v_b := v_a .3.

3 begin 4 select ostatus into os from order_master where ono=1. 3 begin 4 loop 5 a:=a+1.----1 pancil 2 pen 3 ink 4 eraser QUANTITY ----. 5 if(os='p') then 6 update order_master set ddate=sysdate+15 where ono=1. 3 begin 4 while(a>5) 5 loop . 6 dbms_output.1 2 3 4 pancil pen ink eraser 100 500 400 900 15-NOV-09 29-OCT-09 25-OCT-09 12-NOV-09 p d d p Write a PL/SQL Block to implement IF statement SQL> declare 2 os varchar2(10).put_line(a). 8 end loop. 11 / PL/SQL procedure successfully completed. 9 end if. Write a PL/SQL Block to implement while Loop SQL> declare 2 a number:=1. SQL> select * from order_master. ONO ITEM --------. 10 / PL/SQL procedure successfully completed. 7 exit when(a>5). 7 else 8 update order_master set ddate=sysdate where ono=1. 10end. 9 end.--------100 500 400 900 DDATE --------06-DEC-09 29-OCT-09 25-OCT-09 12-NOV-09 OSTATUS ---------p d d p Write a PL/SQL Block to implement Simple Loop SQL> declare 2 a number:=1.

dbms_output. 7 dbms_output. end.--. vloc varchar2(10).6 a:=a+1. end. 9end. begin select esal into vsal from emp6 where ename='&ename'. 10/ PL/SQL procedure successfully completed. dbms_output.sal%type.put_line(vdname||' '||vloc).put_line(a). begin select dname. dbms_output. end. Exception Handling in PL/SQL SQL> select * from emp. / To display the name and location of dept declare vdname varchar2(10). begin select sal into vsal from emp where empno='&empno'.%type and %rowtype attribute are used to avoid the erro which might occure due to some mistake while declaring a variable. Suppose you want to display the total sal of emp declare vsal emp.put_line(vsal).loc into vdname.put_line('The total sal is'||to_char(vsal)).---------1 navneet 2 navjot 3 permod 4 harish ESAL --------12000 14000 15000 18000 DATABASE WITH PL/SQL declare vsal number. / To display the record in row wise declare drec dept%rowtype. / Working with attribute:. . ENO ENAME -----.vloc from dept where deptno='&deptno'. 8 end loop.

dbms_output. begin select sal into vsal from emp where empno='&empno'. elsif erec. Pre defined exception 2. dbms_output. / Too_many_rows declare vsal emp.put_line('No such emp exists in the table:').job='SALESMAN' then vraise:=1000. vraise number. end.begin select * into drec from dept where deptno='&deptno'. end.It help to us about take care of any error that may have occurred in the executable part of the block. end. Some common exception are: 1. / Exceptions:.put_line('The total sal is'||to_char(vsal)).empno.loc).sal%type.G declare vsal emp. update emp set sal=sal+vraise where empno=erec. begin select * into erec from emp where ename='&ename'. exception when no_data_found then dbms_output.sal%type.dname||' '||drec.job='CLERK' then vraise:=500.g of pre defined exc.Exceptions are nothing but error handlers. if erec. / To increase the salary based on their jobs declare erec emp%rowtype. User defined exc E.put_line(drec. end if. .     NO_DATA_FOUND TOO_MANY_ROWS ZERO_DIVIDE VALUE_ERROR E.

9 dbms_output. 4 salary emp.put_line('employee salary is:' || salary).:'). 3 o_pending Exception.--------1 pancil 100 2 pen 500 3 ink 400 4 eraser 900 SQL> declare 2 d1 order_master. ONO ITEM QUANTITY --------.ename %type. exception TOO_MANY_ROWS then dbms_output.. 16 / Enter value for eno: 4 old 6: empno:=&eno. / Write a PL/SQL Block to implement Inbuilt exception-No data found and too many rows SQL>declare 2 name emp. DDATE OSTATUS ----------------06-DEC-09 p 29-OCT-09 d 25-OCT-09 d 12-NOV-09 p .---------.put_line('too many rows are there for this end'). 13 when too_many_rows then 14 dbms_output. 10 EXCEPTION 11 when no_data_found then 12 dbms_output. end. 7 select ename. dbms_output.'). 5 begin 6 empno:=&eno.esal %type.put_line('The total sal is'||to_char(vsal)).put_line('employee name is:' ||name). 8 dbms_output. new 6: empno:=12. there is no data for this employee no.. employee name is:harish employee salary is:18000 PL/SQL procedure successfully completed.salary from emp where eno=empno.esal into name.put_line('too many rows . 3 empno emp. 15 end.begin select sal into vsal from emp where empno='&empno'. new 6: empno:=4. Write a PL/SQL Block to implement a user defined exception SQL> select * from order_master.eno %type.put_line('there is no data for this employee no. SQL> / Enter value for eno: 12 old 6: empno:=&eno.ddate %type.

9 end if. 7 else 8 dbms_output.---------1 navneet 3 permod 4 harish ESAL --------12000 15000 18000 Write a PL/SQL Block to implement the attribute: %rowcount . ENO ENAME --------. 5 if SQL %found then 6 dbms_output. Cursor Management in PL/SQL Implicit Cursor: Write a PL/SQL Block to implement the attribute: %found SQL> select * from emp.---------1 navneet 2 navjot 3 permod 4 harish ESAL --------12000 14000 15000 18000 SQL> declare 2 no emp. ENO ENAME --------.eno %type. new 4: delete from emp where eno=2. 11 / Enter value for no: 2 old 4: delete from emp where eno=&no.put_line('your order is still pending'). 12 end. 13 / your order is still pending PL/SQL procedure successfully completed.put_line('record found'). 6 if(d1<sysdate)then 7 raise o_pending. record found PL/SQL procedure successfully completed. 9 exception 10 when o_pending then 11 dbms_output. 8 end if.put_line('record is not found').4 begin 5 select ddate into d1 from order_master where ono=4. 10 end. 3 begin 4 delete from emp where eno=&no. SQL> select * from emp.

--------. 12 end if.SQL> declare 2 no emp. 9 / Enter value for no: 1 old 4: update emp set esal=24000 where eno=&no.------------------1 rahul 12000 CHD 110 ADMIN 2 manpreet 4500 patiala 120 MKT 3 reena 23000 panchkula 130 HR 4 sabiha kour 41000 CHD 130 HR 5 gopal 14500 CHD 120 MKT 7 jaspreet 42000 patiala 150 FIn 6 rows selected. 13 exit when emp_crsr %notfound.--------------.esal %type. new 4: update emp set esal=24000 where eno=1. ENO ENAME ESAL ECITY DNO DNAME --------. SQL> select * from emp.salary.put_line(SQL %rowcount). 14 end loop.name. 3 name employee. 3 begin 4 update emp set esal=24000 where eno=&no. 16 end. 8 end. 15 close emp_crsr. 5 if SQL %found then 6 dbms_output. 10 if(salary>15000)then 11 update employee set esal=10000 where esal<=4500.eno %type.--------.esal from employee. SQL> declare 2 no employee. 6 begin 7 open emp_crsr.ename. 8 loop 9 fetch emp_crsr into no. 17 / . 4 salary employee. 1 PL/SQL procedure successfully completed. 5 cursor emp_crsr is select eno. 7 end if.eno %type.ename %type.-------------------. ENO ENAME --------.---------1 navneet 3 permod 4 harish ESAL --------24000 15000 18000 Explicit Cursor: SQL> select * from employee.

12 / PL/SQL procedure successfully completed.p_job varchar2) 3 is 4 select eno. 5 begin 6 for e1 IN emp_crsr 7 loop 8 if(e1. 9 end if. 7 if(emp_cursor %found)then 8 dbms_output. 10 close emp_cursor.put_line('record fetch'). 13 end loop. 5 begin 6 open emp_cursor (10. Cursor For loop SQL> select * from emp.esal<15000) then 9 dbms_output. 10 else 11 dbms_output. 14 end.PL/SQL procedure successfully completed.esal from employi where dno=p_depno and job=p_job.put_line('salary is average').put_line('salary is less'). . Parameterized cursor: SQL> declare 2 cursor emp_cursor(p_depno number. 12 end if. 11 end.ename.'clerk'). 15 / PL/SQL procedure successfully completed. ENO ENAME -----------------1 arpeta 2 arun 3 harish 4 rahul 5 ranjeet ESAL --------12000 15000 20000 14000 45000 SQL> declare 2 cursor emp_crsr 3 is 4 select * from emp.

INTO statement is executed in a PL/SQL Block. When you execute INSERT. Explicit cursors: They must be created when you are executing a SELECT statement that returns more than one row. For example. Implicit Cursors: When you execute DML statements like DELETE. The cursor attributes available are %FOUND.What are Cursors? A cursor is a temporary work area created in the system memory when a SQL statement is executed. The status of the cursor for each of these attributes are defined in the below table. and %ISOPEN. They are also created when a SELECT statement that returns just one row is executed. UPDATE. but they differ in the way they are accessed. implicit statements are created to process these statements. The set of rows the cursor holds is called the active set. When a SELECT. implicit cursor attributes can be used to find out whether any row has been returned by the SELECT statement. INSERT. but can process only one row at a time. This temporary work area is used to store the data retrieved from the database. UPDATE and SELECT statements. A cursor can hold more than one row. INSERT.. When you fetch a row the current row position moves to next row.. and DELETE statements are executed. %NOTFOUND. PL/SQL returns an error when no data is selected. which is called as current row. There are two types of cursors in PL/SQL: Implicit cursors: These are created by default when DML statements like. only one record can be processed at a time. Oracle provides few attributes called as implicit cursor attributes to check the status of DML operations. Even though the cursor stores multiple records. Both implicit and explicit cursors have the same functionality. and manipulate this data. or DELETE statements the cursor attributes tell us whether any rows are affected and how many have been affected. A cursor contains information on a select statement and the rows of data accessed by it. UPDATE. %ROWCOUNT. .

. if a DML statement like INSERT. ELSIF SQL%FOUND THEN var_rows := SQL%ROWCOUNT. if the DML SQL%FOUND statements like INSERT. DELETE and UPDATE do not affect even one row and if SELECT …. DELETE and UPDATE do not affect row and if SELECT…. %ROWCOUNT Return the number of rows affected by the SQL%ROWCOUNT DML operations INSERT.put_line('Salaries for ' || var_rows || 'employees are updated'). DELETE and UPDATE at least one row and if SELECT …. the salaries of all the employees in the ‘employee’ table are updated.INTO statement does not return a row. END. The return value is FALSE. Else we get a message like for example. DELETE. IF SQL%NOTFOUND THEN dbms_output. BEGIN UPDATE employee SET salary = salary + 1000. END IF. %NOTFOUND The return value is FALSE. dbms_output. If none of the employee’s salary are updated we get a message 'None of the salaries where updated'. DELETE and UPDATE affect at least one row and if SELECT ….INTO statement do not return a row. The return value is TRUE.put_line('None of the salaries where updated'). if DML statements like INSERT. In the above PL/SQL Block. 'Salaries for 1000 employees are updated' if there are 1000 rows in ‘employee’ table. if DML SQL%NOTFOUND statements like INSERT.INTO statement return at least one row. SELECT For Example: Consider the PL/SQL Block that uses implicit cursor attributes as shown below: DECLARE var_rows number(5).Attributes %FOUND Return Value Example The return value is TRUE. UPDATE.INTO statement return at least one row.

select_statement – A select query which returns multiple rows.Explicit Cursors An explicit cursor is defined in the declaration section of the PL/SQL Block. CLOSE the cursor in the Execution Section before you end the PL/SQL Block. How to access an Explicit Cursor? . 1) Declaring a Cursor in the Declaration Section: DECLARE CURSOR emp_cur IS SELECT * FROM emp_tbl WHERE salary > 5000. How to use Explicit Cursor? There are four steps in using an Explicit Cursor. In the above example we are creating a cursor ‘emp_cur’ on a query which returns the records of all the employees with salary greater than 5000. • • • • DECLARE the cursor in the declaration section. We can provide a suitable name for the cursor. FETCH the data from cursor into PL/SQL variables or records in the Execution Section. OPEN the cursor in the Execution Section. The General Syntax for creating a cursor is as given below: CURSOR cursor_name IS select_statement. Here ‘emp_tbl’ in the table which contains records of all the employees. • • cursor_name – A suitable name for the cursor. 2) Accessing the records in the cursor: Once the cursor is created in the declaration section we can access the cursor in the execution section of the PL/SQL program. It is created on a SELECT Statement which returns more than one row.

FETCH cursor. Points to remember while fetching a row: · We can fetch the rows in a cursor to a PL/SQL Record or a list of variables created in the PL/SQL Block. General Syntax to fetch records from a cursor is: FETCH cursor_name INTO record_name. When the data is fetched it is copied to the record or variables and the logical pointer moves to the next row and it becomes the current row. create a cursor. OR FETCH cursor_name INTO variable_list. . General Syntax to close a cursor is: CLOSE cursor_name. END. BEGIN OPEN cursor. the program will throw an error. process the records. · If you are fetching a cursor to a list of variables. General Form of using an explicit cursor is: DECLARE variables. · If you are fetching a cursor to a PL/SQL Record. General Syntax to open a cursor is: OPEN cursor_name. If you want to fetch after the last row. the pointer moves to the next row. 2) Fetch the records in the cursor one at a time. records. CLOSE cursor.These are the three steps in accessing the cursor. 3) Close the cursor. the first row becomes the current row. When there is more than one row in a cursor we can use loops along with explicit cursor attributes to fetch all the records. the record should have the same structure as the cursor. When a cursor is opened. On every fetch statement. the variables should be listed in the same order in the fetch statement as the columns are present in the cursor. 1) Open the cursor.

we are fetching the cursor to the record in line no 9. We use these attributes to avoid errors while accessing cursors through OPEN.put_line (emp_rec. We can also create a record with a cursor by replacing the table name with the cursor name. if fetch statement doesn’t Cursor_name%NOTFOUND return a row. 10> dbms_output. When does an error occur while accessing an explicit cursor? a) When we try to open a cursor which is not closed in the previous operation. we are displaying the first_name and last_name of the employee in the record emp_rec in line no 10. Sixth. Fifth. These are the attributes available to check the status of an explicit cursor. 12> END. we are opening the cursor in the execution section in line no 8. we are closing the cursor in line no 11.6. 11> CLOSE emp_cur.first_name || ' emp_rec. 3> CURSOR emp_cur IS 4> SELECT * 5> FROM 6> WHERE salary > 10. . Fourth. we are declaring a cursor ‘emp_cur’ from a select query in line no 3 . FALSE. FALSE. if fetch statement doesn’t return a row. What are Explicit Cursor Attributes? Oracle provides some attributes known as Explicit Cursor Attributes to control the data processing while using cursors. Attributes %FOUND Return values Example TRUE. if fetch statement returns at %NOTFOUND . Third. Second.last_name).Lets Look at the example below Example 1: 1> DECLARE 2> emp_rec emp_tbl%rowtype. if fetch statement returns at Cursor_name%FOUND least one row. 9> FETCH emp_cur INTO emp_rec. FETCH and CLOSE Statements. 7> BEGIN 8> OPEN emp_cur. TRUE. b) When we try to fetch a cursor after the last operation. first we are creating a record ‘emp_rec’ of the same structure as of table ‘emp_tbl’ in line no 2. ' || In the above example.

WHILE LOOP and FOR LOOP. 15> END. These loops can be used to process multiple rows in the cursor. if there is a row found the program continues. The number of rows fetched by the Cursor_name%ROWCOUNT fetch statement If no row is returned. 12> dbms_output. .salary). TRUE. it directly moves to line no 9.first_name || ' ' || emp_cur. 16> / In the above example we are using two cursor attributes %ISOPEN and %NOTFOUND. if the cursor is not opened in the program.put_line(emp_cur. if the cursor is already open in Cursor_name%ISNAME the program FALSE. salary FROM emp_tbl. 14> END LOOP. So use these attributes in appropriate instances. the PL/SQL statement returns an error.%ROWCOUNT %ISOPEN least one row. We can use %FOUND in place of %NOTFOUND and vice versa. a condition which exists when you fetch the cursor after the last row. Using Loops with Explicit Cursors: Oracle provides three types of cursors namely SIMPLE LOOP. If there is no rows found the program would exit. In line no 6. we are using the cursor attribute %NOTFOUND to check whether the fetch returned any row. In line no 11. Here I will modify the same example for each loops to explain how to use loops with cursors.last_name 13> || ' ' ||emp_cur. we are using the cursor attribute %ISOPEN to check if the cursor is open. 8> END IF. if the condition is true the program does not open the cursor again. we need to reverse the logic of the program. If we do so. 11> EXIT WHEN emp_cur%NOTFOUND. last_name. 4> emp_rec emp_cur%rowtype. Cursor with a Simple Loop: 1> DECLARE 2> CURSOR emp_cur IS 3> SELECT first_name. 9> LOOP 10> FETCH emp_cur INTO emp_rec. 5> BEGIN 6> IF NOT sales_cur%ISOPEN THEN 7> OPEN sales_cur.

In the loop.last_name 13> || ' ' ||emp_cur. END LOOP.first_name || ' ' || emp_cur. salary FROM emp_tbl. 10> WHILE sales_cur%FOUND THEN 11> LOOP 12> dbms_output. salary FROM emp_tbl. fetch and close the cursor. need not open. 1> DECLARE 2> CURSOR emp_cur IS 3> SELECT first_name.Cursor with a While Loop: Lets modify the above program to use while loop.. General Syntax for using FOR LOOP: FOR record_name IN cusror_name LOOP process the row. 18> / In the above example. If the fetch statement is not executed once before the while loop the while condition will return false in the first instance and the while loop is skipped. 5> BEGIN 6> IF NOT sales_cur%ISOPEN THEN 7> OPEN sales_cur. 15> FETCH sales_cur INTO sales_rec. last_name. 4> emp_rec emp_cur%rowtype. Cursor with a FOR Loop: When using FOR LOOP you need not declare a record or variables to store the cursor values. before fetching the record again. 9> FETCH sales_cur INTO sales_rec. In the loop we use fetch statement again (line no 15) to process the next row. 4> emp_rec emp_cur%rowtype. 17> END.. in line no 10 we are using %FOUND to evaluate if the first fetch statement in line no 9 returned a row. 1> DECLARE 2> CURSOR emp_cur IS 3> SELECT first_name. 5> BEGIN . always process the record retrieved by the first fetch statement. These functions are accomplished by the FOR LOOP automatically.put_line(emp_cur. 16> END LOOP. 8> END IF.salary). else you will skip the first row. if true the program moves into the while loop. Let’s use the above example to learn how to use for loops in cursors. last_name.

10> END LOOP.97) 10 11 12 END. execution section and exception section similar to a general PL/SQL Block. The body consists or declaration section. This is similar to a procedure in other programming languages. 12> / In the above example. We can pass parameters to procedures in three ways. NUMBER(4.salary).last_name 9> || ' ' ||emp_cur. The header consists of the name of the procedure and the parameters or variables passed to the procedure. 11>END.first_name || ' ' ||emp_cur. DATE CURSOR product_cur IS SELECT * FROM product FOR UPDATE OF product_price. By using FOR Loop in your program. 13 / VARCHAR2(25) PRIMARY KEY. the cursor is opened.product_price * 0 WHERE CURRENT OF product_cur. Create a cursor for update Create a following table: CREATE TABLE product ( 2 product_name 3 product_price 4 quantity_on_hand 5 last_stock_date 6 ). you can reduce the number of lines in the program.0). 1) IN-parameters 2) OUT-parameters 3) IN OUT-parameters . A procedure is similar to an anonymous PL/SQL Block but it is named for repeated usage.put_line(emp_cur. NUMBER(5.6> FOR emp_rec in sales_cur 7> LOOP 8> dbms_output. A procedure has a header and a body. the rows are fetched to the record ‘emp_rec’ and the cursor is closed after the last row is processed. when the FOR loop is processed a record ‘emp_rec’of structure ‘emp_cur’ gets created. DECLARE 2 3 4 5 BEGIN 6 7 8 9 . What is a Stored Procedure? A stored procedure or in simple a proc is a named PL/SQL block which performs one or more specific task. END LOOP. FOR product_rec IN product_cur LOOP UPDATE product SET product_price = (product_rec.2).

12>END. General Syntax to create a procedure is: CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters] IS Declaration section BEGIN Execution section EXCEPTION Exception section END.put_line(emp_cur. 5> emp_rec emp_cur%rowtype. 1> CREATE OR REPLACE PROCEDURE employer_details 2> IS 3> CURSOR emp_cur IS 4> SELECT first_name.last_name 10> || ' ' ||emp_cur.first_name || ' ' ||emp_cur. salary FROM emp_tbl. The syntax within the brackets [ ] indicate they are optional. 13> / How to execute a Stored Procedure? There are two ways to execute a procedure. IS .salary). By using CREATE OR REPLACE together the procedure is created if no other procedure with the same name exists or the existing procedure is replaced with the current code. . EXECUTE [or EXEC] procedure_name.marks the beginning of the body of the procedure and is similar to DECLARE in anonymous PL/SQL Blocks. 11> END LOOP. 6> BEGIN 7> FOR emp_rec in sales_cur 8> LOOP 9> dbms_output. The code between IS and BEGIN forms the Declaration section. 2) Within another procedure – simply use the procedure name.A procedure may or may not return any value. The below example creates a procedure ‘employer_details’ which gives the details of the employee. 1) From the SQL prompt. procedure_name. last_name.

salary OUT emp.esal %type) 2 is 3 begin 4 select ename. 4 end raise_salary. 5 end emp_detail. . OUT mode. we are using backward slash ‘/’ at the end of the program.ename %type. 6 / Procedure created. This indicates the oracle engine that the PL/SQL program has ended and it can begin processing the statements. 5 / Procedure created.esal into name. SQL> select * from emp. ENO --------1 2 3 4 5 ENAME ---------arpeta arun harish rahul ranjeet ESAL --------12000 16000 20000 14000 45000 Write a procedure to implement OUT Mode: SQL> create or replace procedure emp_detail(no IN emp.eno % type) 2 is begin 3 update emp set esal=esal+1000 where eno=no.esal %type) T emp. ENO ENAME -----------------1 arpeta 2 arun 3 harish 4 rahul 5 ranjeet ESAL --------12000 15000 20000 14000 45000 SQL> create or replace procedure raise_salary(no IN emp. PL/SQL procedure successfully completed.eno %type. SQL> execute raise_salary(2). Stored Procedures in PL/SQL A stored procedure has three categories of parameter modes: IN mode. name OUT emp. IN OUT mode Write a procedure to implement IN Mode: SQL> select * from emp.salary from emp where eno=no.NOTE: In the examples given above.

8 end.SQL> declare 2 no emp. SQL> / Enter value for eno: 3 old 6: no:=&eno. Fetch the area code from a phone number given using a format procedure code. 3 name emp.putline("Phoneno Is: "||p).salary). 4 salary emp. Write a procedure to implement IN OUT Mode: Format a phone number using a procedure. 6 format_phone(p). 7 emp_detail(no. 7 dbms_output.esal%type. 6 / Procedure created. 10* end. SQL> create or replace procedure format_phone(p in out varchar2(10)).eno %type. 5 end format_phone.The first three digit/ characters are of area code. 8 dbms_output. SQL> declare 2 p varchar2(10). Phone number is having a format like 022-2567890.name. . 5 begin 6 no:=&eno. employee name is: harish employee salary is: 20000 PL/SQL procedure successfully completed. 2 is 3 begin 4 p:=substr(p.3).putline("Area Code Is: "||p). new 6: no:=3.1.ename %type.put_line('employee salary is: '||salary). 5 dbms_output. 9 dbms_output. 3 begin 4 p:=&p.put_line('employee name is: '||name).

ENO ENAME ESAL --------. 9 / PL/SQL procedure successfully completed. Phoneno Area Code Is: 172 PL/SQL procedure successfully completed.--------1 arpeta 14000 2 arun 16000 3 harish 20000 4 rahul 18000 5 ranjeet 45000 SQL> create or replace function getsal(no emp. SQL> select * from emp. 5 begin 6 select esal into sal from emp where eno=no. 8 end getsal. The simplified syntax for the CREATE FUNCTION statement is as follows: The simplified syntax for the CREATE FUNCTION statement is as follows: CREATE [OR REPLACE] FUNCTION function_name [(parameter_name [IN | OUT | IN OUT] type [. . Is: 1722665626 Function: A function is similar to a procedure except that a function must return a value. 3 is 4 sal number..eno %type) 2 return number.---------.9 / Enter value for p: 1722665626 old 4: p=&p.])] RETURN type {IS | AS} BEGIN function_body END function_name. Functions in PL/SQL Write a function to get the salary of employee. 7 return sal. new 4: p=1722665626. . You create a function using the CREATE FUNCTION statement..

where 1. 8 .deptno = p_deptno. 6 RETURN x. OR REPLACE specifies the function that is to replace an existing function if present. 4 / ss_thresh 65400 Calling a Function . type specifies the PL/SQL type of the parameter. 9 end. 10 . 2. 10 / CREATE OR REPLACE a function CREATE OR REPLACE FUNCTION ss_thresh 2 RETURN NUMBER AS 3 x NUMBER(9. table employees( empno NUMBER(4) ename VARCHAR2(8) init VARCHAR2(5) job VARCHAR2(8) mgr NUMBER(4) bdate DATE msal NUMBER(6. 9 . 8 / Function created. 4 BEGIN 5 x := 65400.2).2) deptno NUMBER(2) ) . 3.PUT_LINE('ss_thresh ' || ss_thresh()). 3 END. SQL> BEGIN 2 DBMS_OUTPUT. 4 .2) comm NUMBER(6. create or replace function emp_count(p_deptno in number) 2 return number is 3 cnt number(2) := 0. 7 . The body of a function must return a value of the PL/SQL type specified in the RETURN clau Describe a user-defined function create 2 3 . 5 . 8 return (cnt). 6 . 4 begin 5 select count(*) into cnt 6 from employees e 7 where e. 7 END ss_thresh.

CREATE OR REPLACE FUNCTION circle_area (p_radius IN NUMBER) RETURN NUMB ER AS 2 v_pi NUMBER := 3." You can debug. 7 RETURN v_average_salary. or replace a package body without changing the package spec. It declares the types. variables. 2). The specification (spec for short) is the interface to the package. and subprograms that can be referenced from outside the package. CIRCLE_AREA(12) Calling a Function to a table. exceptions. 3 BEGIN 4 SELECT AVG(salary) 5 INTO v_average_salary 6 FROM employee. AVERAGE_SALARY -------------4071. CREATE OR REPLACE FUNCTION average_salary RETURN NUMBER AS 2 v_average_salary NUMBER. 8 / Function created.14. You can think of the spec as an interface and of the body as a "black box. variables. 4 BEGIN 5 v_area := v_pi * POWER(p_radius.7525 Packaage:. a specification and a body. 7 END circle_area. SQL> SQL> select average_salary from dual. 3 v_area NUMBER. 6 RETURN v_area. SQL> SQL> select circle_area(12) from dual. .A package is a schema object that groups logically related PL/SQL types. 9 / Function created. constants. cursors. The body defines the queries for the cursors and the code for the subprograms. sometimes the body is unnecessary. 8 END average_salary. enhance. and subprograms. Packages usually have two parts.

use the SQL statement CREATE PACKAGE. mgr NUMBER. salary REAL). a cursor. CURSOR desc_salary RETURN EmpRecTyp. 4. PROCEDURE hire_employee ( ename VARCHAR2. The procedure hire_employee uses the sequence empno_seq and the function SYSDATE to insert a new employee number and hire date. The spec holds public declarations. a CREATE PACKAGE BODY statement defines the package body. The package specification generally doesn't contain the code. 5. sal NUMBER. which are hidden from code outside the package. . 1. / CREATE OR REPLACE PACKAGE BODY emp_actions AS -. The package specification contains information about the package. Following the declarative part of the package body is the optional initialization part. 6. The body holds implementation details and private declarations. comm NUMBER. END emp_actions. and two employment procedures. Packages are typically made up of two components: a specification and a body. You must declare subprograms at the end of the spec after all other items (except pragmas that name a specific function. PROCEDURE hire_employee ( ename VARCHAR2. deptno NUMBER). These are potentially available to all database users. such pragmas must follow the function spec). sal FROM emp ORDER BY sal DESC.body CURSOR desc_salary RETURN EmpRecTyp IS SELECT empno. 3. which holds statements that initialize package variables and do any other one-time setup steps. The package specification lists the available procedures and functions. 7. The package body contains the actual code. 2.To create package specs. If necessary. CREATE OR REPLACE PACKAGE emp_actions AS -. Packages encapsulate related functionality into one self-contained unit. CREATE OR REPLACE PACKAGE command: Example of a PL/SQL Package The example below packages a record type.spec TYPE EmpRecTyp IS RECORD (emp_id INT. PROCEDURE fire_employee (emp_id NUMBER). job VARCHAR2. which are visible to stored procedures and other code outside the package.

END fire_employee.create demo table create table Employee( ID VARCHAR2(4 BYTE) First_Name VARCHAR2(10 BYTE). you must use dot notation. deptno NUMBER) IS BEGIN INSERT INTO emp VALUES (empno_seq. you create the body of the package. PROCEDURE fire_employee (emp_id NUMBER) IS BEGIN DELETE FROM emp WHERE empno = emp_id. End_Date DATE. City VARCHAR2(10 BYTE). sal NUMBER. ename.2).NEXTVAL.subprogram_name SQL> SQL> 2 3 4 5 6 7 8 9 10 11 -. To reference the package's subprograms and objects. The body of a package is a collection of schema objects that was declared in the specification.type_name package_name.object_name package_name. job. / Creating Packages and call its functions After the specification is created. Salary Number(8. SQL> . Start_Date DATE. END emp_actions. SYSDATE. Last_Name VARCHAR2(10 BYTE). END hire_employee. mgr NUMBER. comm NUMBER. The Syntax for Dot Notation package_name. Description VARCHAR2(15 BYTE) ) / NOT NULL. If you perform any initialization in the package body. sal. comm. it is executed once when the package is initially referenced. Table created. mgr.job VARCHAR2. deptno).

Last_Name.SQL> -. SQL> insert into Employee(ID. First_Name.'YYYYMMDD'). 'Smith'.'David'.prepare data SQL> insert into Employee(ID. t 3 / 1 row created. First_Name. E 2 values('02'. Last_Name. E 2 values('07'. SQL> insert into Employee(ID. First_Name. Start_Date.'James'. Last_Name. E 2 values('05'.'YYYYMMDD'). to_date('19821024'. 'Black'. SQL> insert into Employee(ID. First_Name. to_date('19901231'. 'Larry'. to_date('19960917'. to_date('19840115'. t 3 / 1 row created.display data in the table SQL> select * from Employee 2 / . 'Green'. 'Rice'.'Celia'.'Linda'. t 3 / 1 row created. E 2 values('03'. Last_Name. Start_Date. Start_Date. t 3 / 1 row created. to_date('19960725'. E 2 values('06'.'Alison'. Start_Date. SQL> insert into Employee(ID.'YYYYMMDD'). 'Martin'. First_Name.'YYYYMMDD'). Last_Name.'YYYYMMDD'). Start_Date. t 3 / 1 row created. Start_Date.'YYYYMMDD'). E 2 values ('01'. to_date('19760321'. SQL> insert into Employee(ID. to_date('19870730'. t 3 / 1 row created.'James'.'Jason'. E 2 values('08'. SQL> insert into Employee(ID. First_Name. 'Mathews'. Last_Name. First_Name. to_date('19781212'. 'Cat'.'YYYYMMDD'). SQL> SQL> SQL> SQL> -. Start_Date.'Robert'. First_Name. SQL> insert into Employee(ID. t 3 / 1 row created. Last_Name. Last_Name. Start_Date. t 3 / 1 row created.'YYYYMMDD'). E 2 values('04'.

78 New York 12-FEB-98 7897. 13 END. . SQL> SQL> SQL> SQL> SQL> CREATE OR REPLACE PACKAGE inv_pck_spec as 2 FUNCTION inv_count(qty integer) RETURN integer. 16 17 END inv_pck_spec.78 Vancouver 08-AUG-98 2334.78 New York 15-APR-02 1232.78 Vancouver 21-APR-99 2344.56 Toronto 21-FEB-86 6661. SQL> SQL> CREATE OR REPLACE PACKAGE BODY inv_pck_spec is 2 FUNCTION inv_count(qty integer)RETURN integer is 3 new_qty integer. SQL> SQL> call inv_pck_spec. SQL> SQL> select * from employee.78 Vancouver DESCRIPTION --------------Programmer Tester Tester Manager Tester Tester Manager Tester 8 rows selected. 5 / Package created.inv_adjust(2000). Call completed. 14 BEGIN -. 7 RETURN(new_qty). 4 END inv_pck_spec. first_name)values('01'.package initialization begins here 15 INSERT into employee (id. 18 / Package body created.---------. 'new'). SQL> SQL> --call inv_pck_spec. 9 10 PROCEDURE inv_adjust(qty integer) is 11 BEGIN 12 DELETE from employee WHERE salary<qty.salary) values ('01'.inv_count(2). 6 INSERT into employee (id.ID ---01 02 03 04 05 06 07 08 FIRST_NAME ---------Jason Alison James Celia Robert Linda David James LAST_NAME ---------Martin Mathews Smith Rice Black Green Larry Cat START_DAT --------25-JUL-96 21-MAR-76 12-DEC-78 24-OCT-82 15-JAN-84 30-JUL-87 31-DEC-90 17-SEP-96 END_DATE SALARY CITY --------. 4 BEGIN 5 new_qty:= qty*6.---------25-JUL-06 1234. 3 PROCEDURE inv_adjust(qty integer).new_qty). 8 END inv_count.78 Vancouver 15-MAR-90 6544.78 Vancouver 04-JAN-96 4322.

ID ---02 03 04 05 06 07 01 FIRST_NAME ---------Alison James Celia Robert Linda David new LAST_NAME ---------Mathews Smith Rice Black Green Larry START_DAT --------21-MAR-76 12-DEC-78 24-OCT-82 15-JAN-84 30-JUL-87 31-DEC-90 END_DATE SALARY CITY --------. SQL> SQL> SQL> SQL> -.78 Vancouver 04-JAN-96 4322.clean the table SQL> drop table Employee 2 / Table dropped.78 New York 12-FEB-98 7897.---------21-FEB-86 6661.78 Vancouver 21-APR-99 2344. .78 Vancouver 15-MAR-90 6544.78 Vancouver 08-AUG-98 2334.---------.78 New York DESCRIPTION --------------Tester Tester Manager Tester Tester Manager 7 rows selected.

Sign up to vote on this title
UsefulNot useful