You are on page 1of 55

PL/SQL Material 2014

#################### # PL/SQL # #################### Before going to start PL/SQL first we will discuss what is sql and pl/sql SQL: It is a structured query language AND non-procedural language PL/SQL: It is a procedural language. we can communicate with the database directly using SQL. In sql we have some sublanguages DDL -> Data Definition language |-> Create |-> Alter |-> Rename |-> Drop |-> Truncate DML -> Data Manipulation Language |-> Insert |-> Update |-> Delete DCL -> Data Control Language |-> Grant |-> Revoke TCL -> Transaction Control Language |-> Commit |-> Rollback |-> Savepoint DQL/DRL -> Data Query/Retrieval Language |-> Select Differences between Delete and Truncate _________________________________________________________________ | DELETE | |---------|1. It is a DDL Statement | |3. Whole records of table will be | deleted perminantly TRUNCATE | | | | | | | |--------------------------| 1. It is a DML statement | | commit or rollback completeset of records

| 2. Explicitly user has to Perform |2. It is Auto-commited statement | 3. Deletion may be partial or`

Faculty: Mr. Basha Wilshire Software Technologies

Page 1

PL/SQL Material 2014


| 4. Can be rolledback | 5. It may fail |4. Rollback is not possible |5. It will not fail data it is handling HWM will come down | | | | | | |

| 6. Estimated time is proportional |6. Estimated time is independent of| | to the amount of data is handling | | 7. Space will not be released as | | Mark there is no change in High Water | | |_____________________ ______ |7. space will be released as the

|____________________________

[3]. In Delete Command Partial is nothing but where deptno=10 only 3 records will be deleted In Truncate command all the records of the table will be removed Perminantly [5]. For ex: if i am delete 10000 records from the table, the before image data has to store in undo tablespace if the undo tablespace doesnt have enough space to handle the before image the txn will not complete, it will be rolled back. And i am trying to delete the records which are not present in my Actual table then instead of getting error i will get a message "No rows selected" In this two cases we can say that the txn is fail But in truncate there is no use of undo tablespace because the records will deleted perminantly and no where the before image will store. [6]. Estimated time is dependent because the before image has to write to undo tablespace in delete statement But in truncate with in fraction of secons the records will removed How to check Defragmentation? Basha>>select avg_row_len,num_rows from dba_tables where table_name='EMP'; Basha>>alter table emp move to <othertsname>; ##########Real time Scenarios where we have to use PL/SQL only############ 1. Log in and logout time of a user

Faculty: Mr. Basha Wilshire Software Technologies

Page 2

PL/SQL Material 2014


2. Always we have to ensure that bal not less than 1k 3. Keep Track, who has modified the sal of emp 4. Sending mail 5. Reading from files and writing to files 6. Hiding some rows or some imp col info[VPD] (virtual private database) 7. Executing shell scripts from oracle 8. Scheduling the jobs -> PL/SQL (Procedural language /sql) is a procedural language extension to a non-procedural sql -> it is a block structured language what is a block: A collection of executable statements is called as block -> in procedural language we need to mention what to do and how to do -> in non procedural language we mention only what to do not how to do. -> PL/SQL was first released in 1992 as an optional extension to oracle 6(to enhance the capabilities of sql) -> pl/sql allows the DML and DRL statements of sql to be included in block structures and procedural units of code. making a pl/sql a powerful transaction processing language. ADVANTAGES OF PL/SQL: 1> Tight integration with sql -> pl/sql is tightly integrated with sql. the most widely used database manipulation language -> pl/sql lets us use all sql DML,TCL statements and all sql functions, operators, pseudo columns... -> pl/sql fully supports sql datatypes 2> High Performance -> in sql only one statement can be executed at at time -> in pl/sql multiple statements can be executed at a time -> each time an sql statement is executed, a call is made to the server resources. this leads to network traffic due to this decreasing the data processing speed especially in multiuser environment. -> pl/sql allows us to group of sql statements together with in a single block and to send the entire block to the server in a single call, there by network traffic is reduced and increased the performance 3> High productivity

Faculty: Mr. Basha Wilshire Software Technologies

Page 3

PL/SQL Material 2014


-> pl/sql trats the entire block as a single continuous statement & within a short span all the statements will executed and then automaticall the production is high

4> Exception handling -> Note: in pl/sql an error is called as an exception, pl/sql permits dealing with errors as required and facilitates displaying user friendly messages when errors are encountered. 5> Portability( platform independent) -> applications written in pl/sql are portable to any computer hardware and operating system where ever oracle server can run, without any modifications at all 6> Supports Subprograms: -> pl/sql supports to share & reuse the code through subprograms using named pl/sql blocks here procedures and functions are known as subprograms. PL/SQL BLOCK / \ NAMED BLOCK UN-NAMED OR ANONYMOUS Named: These blocks are possible to store in the db by giving a name to block. --> calling the named pl/sql block is possible. Unamed or anonymous: Storing un-named or anonymous blocks is not possible --> calling un-named pl/sql block is not possible Pl/sql block contains 3 Sections: 1) Declaration Section 2) Executable Section 3) Execptional handling section Declaration Section: its an optional section in this section we declare variables, cursors, exceptions, constants,..etc Executable Section: it is a manadatory section

Faculty: Mr. Basha Wilshire Software Technologies

Page 4

PL/SQL Material 2014


IN this section we specify the(sql,plsql) statements to be executed. Exception Handling: is used to control the pl/sql errors. it is an option section we can specify executable statements in exception handling section,but those will be executed only when error occurs. Syntax for PL/SQL block: declare variable declaration; begin exception end; / Note: A pl/sql block ends with Executing a pl/sql block: after entering all code close the pl/sql block with 'end;' and execute using '/' Terminating Pl/sql Block: place a period '.' to terminate a pl/sql block Example Of a pl/sql block: decalre begin; null; exception when others then null; end; / VARIABLES AND DATATYPES Variable: a variable is a object which can hold a value the value may change at the time of execution of a pl/sql block 'end;' -->Mandatory -->Optional executable statements; exception handlers; -->optional

Faculty: Mr. Basha Wilshire Software Technologies

Page 5

PL/SQL Material 2014


Syntax to declare a variable: variable datatype(size); Types of variables: we have two types of variables 1. pl/sql variables 2. Non pl/sql variables Pl/sql variables: The variables which are declared with in a pl/sql block are called pl/sql variables. Non-pl/sql[host/bind]variables: the varaibles which are declared outside of the pl/sql block called non pl/sql or host or bind variables. Datatypes: -- data types are of four types 1. scalar 'Scalar': the datatype which can hold only one value is called scalar datatype ex: char,varchar,date,number,...etc. in scalar datatypes again we have boolean, %type datatypes. 'Composite': its a collection of more than one datatype here we have %rowtype ex1: adding two number using pl/sql declare a number:=10; b number:=20; c number; begin c:=a+b; dbms_output.put_line(c); end; / ex2: printing user defined message in output. declare 2.composite 3.lob 4.ref-cursor

Faculty: Mr. Basha Wilshire Software Technologies

Page 6

PL/SQL Material 2014


a number:=10; b number:=20; c number; begin c:=a+b; dbms_output.put_line('sum of two numbers is'c); end; / ex3: Printing variable values in output. declare a number:=10; b number:=20; c number; begin c:=a+b; dbms_output.put_line('Sum of'||a||'and'||b||'is'||c); end; / ex4: Using predefined function in pl/sql block declare v_ename varchar2(10):='SMITH'; v_num number; begin v_num:=length(v_ename); dbms_output.put_line(v_num); end; / In the above example we had given the values manually. to provide the values dynamically we can use '&' operator. declare v_ename varchar2(10):='&v_ename'; v_num number; begin v_num:=length(v_ename); dbms_output.put_line(v_num); end; /

Faculty: Mr. Basha Wilshire Software Technologies

Page 7

PL/SQL Material 2014

Commenting In pl/sql: -> To Comment a single line '--' is used -> To comment list of lines '/*....*/'

Using Select Statement in Pl/sql Block: Select col1,col2,col3... into var1,var2,var3 from <table_name> where <cond>; ex1: declare v_ename varchar2(10); begin select ename into v_ename from emp where empno=7788; dbms_output.put_line(v_ename); end; / |-----------------------------------------------------------| |l or L or ; -> to view recently executed code. | |-----------------------------------------------------------| ex2: declare ename varchar2(10); sal number; job varchar2(10); hiredate date; begin select ename,sal,job,hiredate into ename,sal,job,hiredate from emp where empno=7788; dbms_output.put_line(ename||' '||sal||' '||job||' '||hiredate); end; /

Faculty: Mr. Basha Wilshire Software Technologies

Page 8

PL/SQL Material 2014


ex3: declare a varchar2(3); b number; begin select ename,sal into a,b from emp where empno=7566; dbms_output.put_line(a||' '||b); end; / %type: syntax: <tablename>.<colname>%type; Ex1: declare v_ename emp.ename%type; begin select ename into v_ename from emp where empno=7902; dbms_output.put_line(v_ename); end; / Ex2: declare v_ename emp.ename%type; v_job emp.job%type; v_sal emp.sal%type; v_hiredate emp.hiredate%type; v_deptno emp.deptno%type; begin select ename,job,sal,hiredate,deptno into v_ename,v_job,v_sal,v_hiredate,v_deptno from emp where empno=7566; dbms_output.put_line(v_ename||' '||v_job||' '||v_sal||' '|| v_hiredate||' '||v_deptno); end; / Composite Datatype: %rowtype: Is used to hold more than one datatype.

Faculty: Mr. Basha Wilshire Software Technologies

Page 9

PL/SQL Material 2014


Syntax: <variablename> <tablename>%rowtype; ex: declare i emp%rowtype; begin select ename,job,sal into i.ename,i.job,i.sal from emp where empno=7566; dbms_output.put_line(i.ename||' '||i.job||' '||i.sal); end; / NOTE: %type and %rowtype are the variable attributes. Bind variables: The variables declared outside the pl/sql block. syntax to Declare a bind variable: sql>>variable <variablename> datatype(size); ex: sql>>variable a number; Loading a value to a bind variable: sql>>exec :<bindvariable_name>:=<value>; ex: sql>>exec :a:=10; printing value of a bind variable: sql>>print <bind_variable_name>; To list all bind variables: sql>> var To list multiple bind variable values: sql>>print var1 var2 var3 .....

Faculty: Mr. Basha Wilshire Software Technologies

Page 10

PL/SQL Material 2014


ex: sql>>variable v_ename varchar2(10); sql>>variable v_sal number; sql>>variable v_job varchar2(10); sql>>begin select ename,sal,job into :v_ename,:v_sal,:v_job from emp where empno=7566; dbms_output.put_line(:v_ename||:v_sal||:v_job); end; / Note: without using dbms_output we print the bind variable values directly sql>>print v_ename v_sal v_job Using DML statements in pl/sql block: sql>>begin insert into emp select *From emp; end; / sql>>begin insert into dept select *from dept; delete from dept where deptno=20; update dept set deptno=50 where deptno=10; end; / Using DDL and DCL in pl/sql block: Using DDL and DDL in pl/sql block is not possible directly. we should use 'execute immediate' option to have DDL or DCL in a block ex: begin execute immediate 'create table sample(sno number)'; execute immediate 'grant select on emp to ora002'; end; /

Faculty: Mr. Basha Wilshire Software Technologies

Page 11

PL/SQL Material 2014


CONTROL STRUCTURES Devided into two types 1. Conditional 2. Iterative Control Structures or loops

Conditional Control Structures: Using a particular condition controling the number of executions is possible using conditional control structures.

1). Simple If: syntax: if<condition> then sequence of statements; end if; ex: declare n number:=&n; begin if n>=1 then dbms_output.put_line('positive'); end if; end; / 2). If-Else. Syntax: if <condition> then sequence of stmts1; else sequence of stmts2; end if; / ex: declare n number:=&n; begin

Faculty: Mr. Basha Wilshire Software Technologies

Page 12

PL/SQL Material 2014


if n>=1 then dbms_output.put_line('positive'); else dbms_output.put_line('negative'); end if; end; / 3). If-Else-If syntax: if <condition> then stmt1; elsif <condition> then stmt2; else stmt3; end if; ex: declare n number:=&n; begin if n>=1 then dbms_output.put_line('positive'); elsif n=0 then dbms_output.put_line('zero'); else dbms_output.put_line('negative'); end if; end; / ex2: declare a number:=&a; begin if (a is null) then dbms_output.put_line('value is null'); else if(a=0) then dbms_output.put_line('value is zero'); else

Faculty: Mr. Basha Wilshire Software Technologies

Page 13

PL/SQL Material 2014


if(a>0) then dbms_output.put_line('value is positive'); else if(a<0) then dbms_output.put_line('value is negative'); end if; end if; end if; end if; end; /

Question: Increase the employees salary who sal is less than 3000 declare v_empno number:=&v_empno; v_sal number; begin select sal into v_sal from emp where empno=v_empno; dbms_output.put_line('old salary is'||v_sal); if v_sal<3000 then update emp set sal=sal+200 where empno=v_empno; commit; select sal into v_sal from emp where empno=v_empno; dbms_output.put_line('new salary is'||v_sal); else dbms_output.put_line('no updations'); end if; end; / Local Variables & Global Variables: declare a number:=10; begin dbms_output.put_line(a);

Faculty: Mr. Basha Wilshire Software Technologies

Page 14

PL/SQL Material 2014


declare b number:=20; begin dbms_output.put_line(b); dbms_output.put_line(a); end; end; / Labled Blocks: <<b1>> declare a number:=10; begin dbms_output.put_line(a); <<b2>> declare a number:=20; begin dbms_output.put_line(a); dbms_output.put_line(b1.a); end b2; end; / Nested Block: declare a number:=10; begin dbms_output.put_line(a); declare b number:=20; begin dbms_output.put_line(b); dbms_output.put_line(a); end; dbms_output.put_line(a); end; /

Faculty: Mr. Basha Wilshire Software Technologies

Page 15

PL/SQL Material 2014


ITERATIVE CONTROL STRUCTURES iterative control structures are also called as loops. Loops are used to execute a single statement for 'N' number of times. There are 3 types of loops: 1. Simple/ Basic loop 2. While loop 3. For loop or Numeric loop. Simple Loop: Syntax: loop exit when <condition> sequence of stmts; end loop;

Ex: Print 1 to 5 numbers using simple loop declare n number:=1; begin loop exit when n>5 dbms_output.put_line(n); n:=n+1; end loop; end; / While Loop: Syntax: while <condition> loop sequence of stmts; end loop;

Faculty: Mr. Basha Wilshire Software Technologies

Page 16

PL/SQL Material 2014


ex: Generate Odd numbers upto a given number. declare a number:=1; begin while a<10 loop dbms_output.put_line(a); a:=a+2; end loop; end; / For Loop: For loop also called as numeric loop.

Syntax: for loopcounter in lowerbound..upperbound loop sequence of stmt; end loop; ex: Print numbers from 1 to 7 begin for i in 1..7 loop dbms_output.put_line(i); end loop; end; / Print number from 1 to 7 in reverse begin for i in reverse 1..7 loop dbms_output.put_line(i);

Faculty: Mr. Basha Wilshire Software Technologies

Page 17

PL/SQL Material 2014


end loop; end; / Using Function in for Loop: declare name varchar2(20):='helloeveryone'; v number:=length(name); begin for j in 1..v loop dbms_output.put_line(substr(name,1,j)); end loop; end;

Ex: Print as below given * * * * * * * * * * * * * * * * * * * * * * * * * declare n varchar2(20); begin for i in 1..5 loop for j in 1..i loop n:=n||'*'; end loop; dbms_output.put_line(n);

Faculty: Mr. Basha Wilshire Software Technologies

Page 18

PL/SQL Material 2014


n:=null; end loop; for i in reverse 1..5 loop for j in 2..i loop n:=n||'*'; end loop; dbms_output.put_line(n); n:=null; end loop; end; /

Ex: Print the output as ---* --*** -***** ******* declare v varchar2(100):='*'; n number:=1; j number:=3; a char(200); spac varchar2(100); spac_1 number; begin loop exit when n>5; for k in 1..j loop spac:=spac||'-'; end loop;

Faculty: Mr. Basha Wilshire Software Technologies

Page 19

PL/SQL Material 2014


dbms_output.put_line(a); a:=spac||v; v:=v||'*'||'*'; n:=n+1; j:=j-1; spac:=null; end loop; end; / CURSORS Cursor->: A cursor is a memory where oracle opens automatically to parse and execute the sql statements. Cursor Types: 1. implicit cursors -> Managed by oracle 2. Explicit Cursors -> Managed by user

1. Implicit cursors: Declared for all pl/sql DML, pl/sql select statements. ex:(for dml) begin update emp set sal=sal+200; delete from emp where deptno=10; end; ex: (for select) declare n number; begin select ename into n from emp where empno=7900; end; / ex1: begin delete from emp;

Faculty: Mr. Basha Wilshire Software Technologies

Page 20

PL/SQL Material 2014


end; / ex2: begin delete from emp; if sql%rowcount>0 then dbms_output.put_line('The no of rows deleted are -->'||sql%rowcount); else dbms_output.put_line('Zero rows deleted'); end if; end; / ********SQL CURSOR ATTRIBUTES*************** Using sql cursor attributes we can test the outcome of sqlstatement. Types of cursor Attributes: sql%rowcount :- Number of rows affected by the most recent sql statement (numeric only) sql%found :- Boolean attribute that evaluates to true if the most sql statement affects one or more rows. sql%notfound :- Boolean attribute that evaluates to true if the most recent sql statement does not effect any rows. sql%isopen:- Always evaluates to false because pl/sql closes the implicit cursor immediately after execution. Note: implicit cursors always stores the attributes of the recently executed Ex1: begin delete from emp; sql statement.

Faculty: Mr. Basha Wilshire Software Technologies

Page 21

PL/SQL Material 2014


if sql%rowcount>0 then dbms_output.put_line('the no.of rows selected are '||sql%rowcount); else dbms_output.put_line('Zero rows deleted'); end if; if sql%found then dbms_output.put_line('sql found is true'); else dbms_output.put_line('sql found not true'); end if; end; / Ex2: begin delete from emp; if sql%rowcount>0 then dbms_output.put_line(sql%rowcount); else dbms_output.put_line('no data'); end if; if sql%found then dbms_output.put_line('found'); else dbms_output.put_line('not found'); end if; if sql%notfound then dbms_output.put_line('not found1'); else dbms_output.put_line('found1'); end if; if sql%isopen then dbms_output.put_line('open'); else dbms_output.put_line('not open'); end if; end; /

Faculty: Mr. Basha Wilshire Software Technologies

Page 22

PL/SQL Material 2014


Explicit Cursors Declared and named by the programmer and used for select statements. Explicit cursors are always defined only on 'select' queries and the select query may refere any no.of tables. _________ | |101 abc |102 bcd | | | | |-- ->|--- ---| | | | | | |--> Actual table |_______| |_______|--> Active Set |_______| |_______|

|___________| Note: The explicit Cursor always points to first record of the o/p.

******* DECLARING THE CURSOR ********* Declaration: cursor <cursor_name> is <select stmt>; opening Cursor: open <cursor_name>; Fetching: Fetch <cursor_name> into [(var1,var2,....)/record name]; Closing: close <cursor_name>; ******** Cursor States *******

Faculty: Mr. Basha Wilshire Software Technologies

Page 23

PL/SQL Material 2014


|-------------------------| |Implicit | | | | Open Fetch Close | | | Explicit | Declare Open | | | Close | |-----------|-------------| |-----------|-------------| |-----------|-------------| | Fetch | |-----------|-------------| |-------------------------|

*********** Explicit Cursor Attributes ***** cur_name%isopen: Evaluates to true if the cursor is open cur_name%notfound: Evaluates to true if the most recent fetch doesnt return a row cur_name%found: Evaluates to true if the most recent fetch returns a row. cur_name%rocount: Returns the Numeric value of fetched Records

Ex1: declare n number; cursor c1 is select sal from emp where empno=7788; begin open c1; fetch c1 into n; dbms_output.put_line(n); close c1; end; / Ex2: declare v_ename varchar2(10); v_sal number;

Faculty: Mr. Basha Wilshire Software Technologies

Page 24

PL/SQL Material 2014


cursor c1 is select ename,sal from emp where empno=7900; begin open c1; fetch c1 into v_ename,v_sal; dbms_output.put_line('name is-->'||v_ename||' close c1; open c1; fetch c1 into v_ename,v_sal; dbms_output.put_line('name is-->'||v_ename||' close c1; end; / Ex3a: declare n number; begin select sal into n from emp where deptno=10; dbms_output.put_line(n); end; / Ex3b: declare v_sal varchar2(10); cursor c1 is select sal from emp where deptno=10; begin open c1; fetch c1 into v_sal; dbms_output.put_line(v_sal); fetch c1 into v_sal; dbms_output.put_line(v_sal); fetch c1 into v_sal; dbms_output.put_line(v_sal); close c1; end; / Ex4: Cursor With Variables declare cursor c1 is select empno,ename from emp; sal is-->'||v_sal); sal is-->'||v_sal);

Faculty: Mr. Basha Wilshire Software Technologies

Page 25

PL/SQL Material 2014


a emp.empno%type; b emp.ename%type; begin open c1; loop fetch c1 into a,b; dbms_output.put_line(a||b); exit when c1%notfound; end loop; close c1; end; / Ex5: declare cursor c1 is select *from emp; rec c1%rowtype; begin open c1; loop fetch c1 into rec; dbms_output.put_line(rec.empno||'-'||rec.ename||'-'||rec.job||''||rec.sal); exit when c1%notfound; end loop; close c1; end; / Ex6: declare cursor c1 is select *from emp; rec c1%rowtype; begin if c1%isopen then dbms_output.put_line('cursor is opne'); else dbms_output.put_line('cursor is not open'); open c1; end if; loop

Faculty: Mr. Basha Wilshire Software Technologies

Page 26

PL/SQL Material 2014


fetch c1 into rec; exit when c1%notfound; dbms_output.put_line(c1%rowcount); end loop; close c1; end; / CURSOR SIMPLE LOOP declare cursor c1 is select ename,sal from emp where deptno=10; v_ename varchar2(10); v_sal number; begin open c1; loop fetch c1 into v_ename,v_sal; exit when c1%notfound; dbms_output.put_line(v_ename||' '||v_sal); end loop; end; / CURSOR FOR LOOP declare cursor c1 is select *from emp; begin for rec in c1 loop dbms_output.put_line(rec.empno||' '||rec.ename); end loop; end; / CURSOR WHILE LOOP declare cursor c1 is select ename,sal from emp; v_ename varchar2(10);

Faculty: Mr. Basha Wilshire Software Technologies

Page 27

PL/SQL Material 2014


v_sal number; begin open c1; fetch c1 into v_ename,v_sal; while c1%found loop dbms_output.put_line(v_ename||' '||v_sal); fetch c1 into v_ename,v_sal; end loop; close c1; end; / CURSOR WITH PARAMETERS declare cnt number; xyz number; cursor countcur(dno number) is select count(*)from emp where deptno=dno; begin open countcur(10); fetch countcur into xyz; dbms_output.put_line(xyz); close countcur; open countcur(20); fetch countcur into xyz; dbms_output.put_line(xyz); close countcur; open countcur(30); fetch countcur into xyz; dbms_output.put_line(xyz); close countcur; end; / CURSOR FOR LOOP WITH PARAMETERS declare cnt number;

Faculty: Mr. Basha Wilshire Software Technologies

Page 28

PL/SQL Material 2014


cursor deptcur is select distinct deptno from emp; cursor countcur(dno number) is select count(*) cnt from emp where deptno=dno; begin for deptrec in deptcur loop for cntrec in countcur(deptrec.deptno) loop dbms_output.put_line(cntrec.cnt); end loop; end loop; end; / INLINE CURSOR Using select statement in for loop is called as Inline cursor. ex: begin for i in(select *from emp) loop dbms_output.put_line(i.ename||' '||i.job); end loop; end; /

ex2: Print emp records without cursors. begin for i in(select *From emp) loop dbms_output.put_line(i.empno||i.ename||i.sal); end loop; end; /

Faculty: Mr. Basha Wilshire Software Technologies

Page 29

PL/SQL Material 2014


FOR UPDATE CLAUSE: declare cursor c1 is select *From emp for update; begin for rec in c1 loop dbms_output.put_line(rec.empno||rec.ename); end loop; end; / DIFFERENCE BETWEEN IMPLICIT AND EXPLICIT CURSORS |--------------------------| Implicit Cursors |--------------------------|1. controlled by oracle |2. Defined on DML,Select | | | | | | | | |_________________________ EXCEPTIONS -- An exception is an identifier in pl/sql that is raised during execution When ever an exception raised in pl/sql block all the uncommited transactions will be rolled back. queries rows then no_data_found exception is raised. explicit cursors |3. If the query retrieves 0 |-------------------------------------| Explicit Cursors |------------------------------------|1. Controlled by user |2. Only on select queries | |3. Exception is not raised when the | | | implicit cursors processed by the cursor so far ex: 1,2,3,4...... then it is true other wise it will be false. query retrieves 0 rows

|4. Performance is better than|4. Poor Performance compared to |5. %rowcount give the no.of ex: 10 |5. %rowcount give the no.of rows | | |

rows processed by the user|

|6. sql%open always false

|6. If the cursor is opened the

|______________________________________

Faculty: Mr. Basha Wilshire Software Technologies

Page 30

PL/SQL Material 2014


Ex1: declare n number; begin delete from emp; select sal into n from emp where empno=&empno; dbms_output.put_line(n); end; / Ex2: begin update emp set sal=2000; delete from emp where deptno=10; insert into test values(101); insert into test values(101); end; / Exception Syntax: when excp1 [or excp 2 ...] then stmt1; stmt2; when excp3 [or excp4 ..] then stmt3; stmt4; when others then stmt5; stmt6; Ex3: declare n number; begin delete from emp where deptno=10; select sal into n from emp where empno=&empno; dbms_output.put_line(n); exception when others then commit; end; /

Faculty: Mr. Basha Wilshire Software Technologies

Page 31

PL/SQL Material 2014


Types Of exceptions: Predefined: The exception which are already derived by oracle the predefined exceptions will have error message and error number. ******* PREDEFINED EXCEPTIONS ************* Exception ACCESS_INTO_NULL CASE_NOT_FOUND COLLECTION_IS_NULL CURSOR_ALREADY_OPEN DUP_VAL_ON_INDEX INVALID_CURSOR INVALID_NUMBER LOGIN_DENIED NO_DATA_FOUND NOT_LOGGED_ON PROGRAM_ERROR ROWTYPE_MISMATCH SELF_IS_NULL STORAGE_ERROR SUBSCRIPT_BEYOND_COUNT SUBSCRIPT_OUTSIDE_LIMIT SYS_INVALID_ROWID TIMEOUT_ON_RESOURCE TOO_MANY_ROWS VALUE_ERROR ZERO_DIVIDE Oracle Error ORA-06530 ORA-06592 ORA-06531 ORA-06511 ORA-00001 ORA-01001 ORA-01722 ORA-01017 ORA-01403 ORA-01012 ORA-06501 ORA-06504 ORA-30625 ORA-06500 ORA-06533 ORA-06532 ORA-01410 ORA-00051 ORA-01422 ORA-06502 ORA-01476 SQLCODE Value -6530 -6592 -6531 -6511 -1 -1001 -1722 -1017 +100 -1012 -6501 -6504 -30625 -6500 -6533 -6532 -1410 -51 -1422 -6502 -1476

Brief descriptions of the predefined exceptions follow:

Faculty: Mr. Basha Wilshire Software Technologies

Page 32

PL/SQL Material 2014


Exception ACCESS_INTO_NULL Raised when ... Your program attempts to assign values to the attributes of an uninitialized (atomically null) object. CASE_NOT_FOUND None of the choices in the WHEN clauses of a CASE statement is selected, and there is no ELSE clause. COLLECTION_IS_NULL Your program attempts to apply collection methods other than EXISTS to an uninitialized (atomically null) nested table or varray, or the program attempts to assign values to the elements of an uninitialized nested table or varray. CURSOR_ALREADY_OPEN Your program attempts to open an already open cursor. A cursor must be closed before it can be reopened. A cursor FOR loop automatically opens the cursor to which it refers. So, your program cannot open that cursor inside the loop. DUP_VAL_ON_INDEX Your program attempts to store duplicate values in a database column that is constrained by a unique index. INVALID_CURSOR Your program attempts an illegal cursor operation such as closing an unopened cursor. INVALID_NUMBER In a SQL statement, the conversion of a character string into a number fails because the string does not represent a valid number. (In procedural statements, VALUE_ERROR is raised.) This exception is also raised when the LIMIT-clause expression in a bulkFETCH statement does not evaluate to a positive number. LOGIN_DENIED Your program attempts to log on to Oracle with an invalid username and/or password. NO_DATA_FOUND A SELECT INTO statement returns no rows, or your program references a deleted element in a nested table or an uninitialized element in an index-by table. SQL aggregate functions such as AVG and SUM always return a value or a null. So, a SELECT INTO

Faculty: Mr. Basha Wilshire Software Technologies

Page 33

PL/SQL Material 2014


Exception Raised when ... statement that calls an aggregate function never raises NO_DATA_FOUND. The FETCH statement is expected to return no rows eventually, so when that happens, no exception is raised. NOT_LOGGED_ON Your program issues a database call without being connected to Oracle. PROGRAM_ERROR ROWTYPE_MISMATCH PL/SQL has an internal problem. The host cursor variable and PL/SQL cursor variable involved in an assignment have incompatible return types. For example, when an open host cursor variable is passed to a stored subprogram, the return types of the actual and formal parameters must be compatible. SELF_IS_NULL Your program attempts to call a MEMBER method on a null instance. That is, the built-in parameter SELF (which is always the first parameter passed to a MEMBER method) is null. STORAGE_ERROR PL/SQL runs out of memory or memory has been corrupted. SUBSCRIPT_BEYOND_COUNT Your program references a nested table or varray element using an index number larger than the number of elements in the collection. SUBSCRIPT_OUTSIDE_LIMIT Your program references a nested table or varray element using an index number (-1 for example) that is outside the legal range. SYS_INVALID_ROWID The conversion of a character string into a universal rowid fails because the character string does not represent a valid rowid. TIMEOUT_ON_RESOURCE A time-out occurs while Oracle is waiting for a resource. TOO_MANY_ROWS VALUE_ERROR A SELECT INTO statement returns more than one row. An arithmetic, conversion, truncation, or sizeconstraint error occurs. For example, when your program selects a column value into a character

Faculty: Mr. Basha Wilshire Software Technologies

Page 34

PL/SQL Material 2014


Exception Raised when ... variable, if the value is longer than the declared length of the variable, PL/SQL aborts the assignment and raises VALUE_ERROR. In procedural statements, VALUE_ERROR is raised if the conversion of a character string into a number fails. (In SQL statements, INVALID_NUMBER is raised.) ZERO_DIVIDE Your program attempts to divide a number by zero.

Managing Predefined Exceptions: declare n number; begin delete from emp; select sal into n from emp where empno=&empno; dbms_output.put_line(n); exception when no_data_found then dbms_output.put_line('no records found with empno'); commit; end; / Semi Predefined Exceptions: In this semi predefined exceptions oracle will have the error code but error message will not be there. the user has to provide error message for error code. Ex1: declare e_notnull exception; pragma exception_init(e_notnull,-1400); begin insert into emp(empno,ename) values(null,'&ename'); commit; exception when e_notnull then dbms_output.put_line('you can not leave a field blank at empno'); end;

Faculty: Mr. Basha Wilshire Software Technologies

Page 35

PL/SQL Material 2014


/ Ex2: declare unique_ex exception; pragma exception_init(unique_ex,-00001); begin insert into test values(&sno); exception when unique_ex then dbms_output.put_line('Value is presented'); end; / Userdefined Exception: In this user defined exception the user has to define the exception name and the error code also. The error code range is -20000 to -20999 Ex1: declare v_empno emp.empno%type; begin select empno into v_empno from emp where empno=100; exception when no_data_found then raise_application_error(-20112,'no records found with matching empno'); end; / Ex2: declare i emp%rowtype; begin select ename,sal,empno into i.ename,i.sal,i.empno from emp where empno=&empno;

Faculty: Mr. Basha Wilshire Software Technologies

Page 36

PL/SQL Material 2014


if(i.sal>2000) then raise_application_error(-20418,'no updations'); else update emp set sal=sal+200 where empno=i.empno; end if; exception when no_data_found then dbms_output.put_line('no such emp is exist'); when others then dbms_output.put_line('some other exception'); end; / Error Traping: declare msg varchar2(100); code varchar2(100); begin insert into test values(101); insert into test values(101); exception when others then msg:=substr(sqlerrm,1,100); code:=sqlcode; insert into error_msg_log values(code,msg,systimestamp); commit; end; /

*********** SUB PROGRAMS Sub programs are devided in to two types: 1. Procedures 2. Functions

***************

Faculty: Mr. Basha Wilshire Software Technologies

Page 37

PL/SQL Material 2014


PROCEDURES: Storing a pl/sql block in the database is called stored procedure. --> procedures will not occupy any space. Ex: CREATE OR REPLACE PROCEDURE greetings AS BEGIN dbms_output.put_line('Hello World!'); END; / executing the procedure: exec procedure_name exec greetings; Using procedure in pl/sql block: BEGIN greetings; END; / Syntax: create or replace procedure <proc_name> (parameter1 <mode> datatype, parameter2 <mode> datatype, . . . ) is/as procedure body; end procedure_name;

Ex2: create or replace procedure proc_si(p in number,n in number,r in number) is si number;

Faculty: Mr. Basha Wilshire Software Technologies

Page 38

PL/SQL Material 2014


begin si:=(p*n*r)/100; dbms_output.put_line('Simple Interest is:'||si); end proc_si; / sql>> exec proc_si(20,34,23); sql>> declare a number:=&a; b number:=&b; c number:=&c; begin proc_si(a,b,c); end; / --IN: -If the parameter is in mode then a user can pass a value to procedure. --OUT: If the parameter is OUT mode then a user gets a value from the

--- procedure. --IN OUT:if the parameter is in out mode then a user can pass a value to the --value to the user. NOTE: Do not specify any size to datatype. IS/AS: used to start the pl/sql block. Using In mode parameter: create or replace procedure inmode(a number,b number) as s number; begin s:=a+b; dbms_output.put_line(s); procedure and from the same we can use the parameter to send a

Faculty: Mr. Basha Wilshire Software Technologies

Page 39

PL/SQL Material 2014


end; / declare a number:=&a; b number:=&b; begin inmode(a,b); end; / Executing Standalone procedure: exec inmode(23,2); Using Bind Variable in Procedure: sql>> variable a number; sql>> variable b number; sql>> exec :a:=10; sql>> exec :b:=20; sql>> exec inmode(:a,:b); Ex2: create or replace procedure proc4(pdeptno in number) as v_dname varchar2(10); v_loc varchar2(10); begin select dname,loc into v_dname,v_loc from dept where deptno=pdeptno; dbms_output.put_line(v_dname||' '||v_loc); end; / sql>>exec proc4(10); sql>> declare v_num number:=&v_num; begin proc4(v_num); end; / Using OUT mode parameter: create or replace procedure outmode(a number,b number,c out number)

Faculty: Mr. Basha Wilshire Software Technologies

Page 40

PL/SQL Material 2014


as begin c:=a+b; end; / declare abc number; begin outmode(10,3,abc); dbms_output.put_line(abc); end; / ex2: create or replace procedure proc3(vdeptno in number,pdname out varchar2,ploc out varchar2) as begin select dname,loc into pdname,ploc from dept where deptno=vdeptno; end; / declare a varchar2(10); b varchar2(20); begin proc3(10,a,b); dbms_output.put_line(a || b); end; / USING BIND VARIABLES: SQL>> variable x varchar2(10); variable y varchar2(10); sql>> exec proc3(10,:x,:y); sql>> print x y

Faculty: Mr. Basha Wilshire Software Technologies

Page 41

PL/SQL Material 2014


USING IN OUT PARAMETER: Ex: SQL>>create or replace procedure inout(a in number,b in out number) as begin b:=a+b; end; / declare abc number:=&abc; begin inout(200,abc); dbms_output.put_line(abc); end; / Ex2: create or replace procedure square(a in out number) is begin a:=a*a; dbms_output.put_line(a); end square; / declare b number:=&b; begin square(b); end; / Create A procedure to add bonus to the employees: create or replace procedure proc_bonus as cursor b1 is select empno,ename,job,sal+nvl(comm,0) netsal from emp; bonus number; i b1%rowtype;

Faculty: Mr. Basha Wilshire Software Technologies

Page 42

PL/SQL Material 2014


begin open b1; loop fetch b1 into i; exit when b1%notfound; if i.job='CLERK' then bonus:=i.netsal*0.25; elsif i.job='SALESMAN' then bonus:=i.netsal*0.15; else bonus:=i.netsal*0.35; end if; update emp set sal=sal+bonus where empno=i.empno; dbms_output.put_line(i.ename||' '||i.job ||' '||bonus||' '||i.netsal); end loop; close b1; end proc_bonus; / ********* METHODS FOR PARSING ********** ex: create or replace demo_sum(a number, b number,c number) as begin dbms_output.put_line(a+b+c); end; / positional: ex: exec demo_sum(10,20,30); named: ex: exec demo_sum(a=>10,b=>20,c=>30); combined: ex: exec demo_sum(10,20,c=>30); NOTE: while passing the parameters using combined always the named parameters should write at last.

Faculty: Mr. Basha Wilshire Software Technologies

Page 43

PL/SQL Material 2014


********* FUNCTIONS ***********

--> A function is a named pl/sql block that returns a value --> A function will store in the database as a schema object for repeated executions syntax: create or replace function <fun_name> [parameter1 <mode> datatype, parameter2 <mode> datatype, . . . ] return datatype is/as pl/sql block; Note: The pl/sql block should have atleast one return statement. ex: create or replace function sunfun(a number, b number) return number as begin return(a+b); end; / Using the function: sql>> select sumfun(10,40) from dual; Function with bind variables: sql>>variable a number; sql>>exec :a:=sumfun(10,40) sql>>print a o/p: 50 Using function in a block: sql>>declare

Faculty: Mr. Basha Wilshire Software Technologies

Page 44

PL/SQL Material 2014


s number; begin s:=sumfun(20,40); dbms_output.put_line(s); end; / using column names: --select empno,ename,sum(empno,deptno) from emp; --it throughs error

select sumfun(empno,deptno) from emp; Ex: Create function to print day of given date: create or replace function fun1(f_date in date) return varchar2 is v_day varchar2(20); begin select to_char(f_date,'Dy') into v_day from dual; return v_day; end; / Ex: declare a number:=&a; b number:=&b; begin if sumfun(a,b)>100 then dbms_output.put_line('value is >100'); else dbms_output.put_line('value is <100'); end if; end; /

Faculty: Mr. Basha Wilshire Software Technologies

Page 45

PL/SQL Material 2014

Write a function to find tax depending on sal: create or replace function tax_cal(p_value in number) return number is begin return(case when p_value between 2000 and 5000 then p_value*0.1 when p_value between 100 and 1999 then p_value*0.04 else p_value end ); end tax_cal; / Differences b/w procedures and functions: --------------------------------------------------------------------------| PROCEDURE | FUNCTION |------------------------------------------------------------------------|1. Executes as a pl/sql stmt |2. No return clause in the header | |3. can return one or more or none | | values |4. can contain a return stmt |1. Invokes as a part of an expression| |2. Must contain a header clause in | | |3. Must Return a single value |4. Must contain at least one return | stmt. the header | | | | | | |

|______________________________________________________________________

######### PACKAGES

#############

--> A package is a collection of stored procedures and functions --> Inter-related procedures should be given in a package A package contains package specification and package body. Package specification: In package specification specifiy only the procedures and functions along with parameters without any executable sections.

Faculty: Mr. Basha Wilshire Software Technologies

Page 46

PL/SQL Material 2014


Package body: Specify the executable section in the package body for the procedures which are specified in the package specification

Note: With out creating a package specification creating package body is not possible Syntax to create package specification: create or replace package <package_name> is/as procedure 1 <procedure_name>(parameters <mode> datatype,....); procedure 2 <procedure_name>(parameters <mode> datatype,....); . . . function <function_name>(parameter <mode> datatype) return datatype; end package; / Syntax to create package body: create or replace package body <package_name> is/as procedure <procedure_name>(parameter <mode> datatype,...); is/as begin executable section; end <procedure_name>; . . . function <fun_name>(parameter <mode> datatype,....) return datatype; is/as begin

Faculty: Mr. Basha Wilshire Software Technologies

Page 47

PL/SQL Material 2014


executable section; exceptional handling section; end <fun_name>; end <package_name>; / --> The package name at package body should be the same name which provided at the time of package specification. Note: While creating the package body write the executable sections in the same sequence mentioned at the time package specification. if not it throughs error.

Using the package elements: syntax: sql>>exec package_name.element_name; ex1_specification: create or replace package new_pack as procedure p1(a in number,b in number,c out number); end; / ex1_body: create or replace package body new_pack as procedure p1(a in number,b in number,c out number) as begin c:=a+b; dbms_output.put_line(c); end p1; end new_pack; / sql>> declare a number:=&a; b number:=&b;

Faculty: Mr. Basha Wilshire Software Technologies

Page 48

PL/SQL Material 2014


c number; begin new_pack.p1(a,b,c); end; /

ex2_Creating package specification: BASHA>>create or replace package cust_sal as procedure find_sal(c_id customers.id%type); end cust_sal; / ex2_Creating package body: BASHA>>create or replace package body cust_sal as procedure find_sal(c_id customers.id%type) is c_sal customers.salary%type; begin select salary into c_sal from customers where id=c_id; dbms_output.put_line('salary is'||c_sal); end find_sal; end cust_sal; / sql>> declare code customers.id%type:=&id; begin cust_sal.find_sal(code); end; / sql>>exec cust_sal.find_sal(2); sql>>exec cust_sal.find_sal(1); create or replace package e_package as

Faculty: Mr. Basha Wilshire Software Technologies

Page 49

PL/SQL Material 2014


--add a customer procedure addcustomer(c_id customers.id%type, c_name customers.name%type, c_address customers.address%type, c_sal customers.salary%type); --remove customer procedure delcustomer(c_id customers.id%type); end e_package; / ex1_pack_body: create or replace package body c_package as procedure addcustomer(c_id customers.id%type, c_name customers.name%type, c_address customers.address%type, c_sal customers.salary%type) is begin insert into customers(id,name,address,salary) values(c_id,c_name,c_address,c_sal); end addcustomer; procedure delcustomer(c_id customers.id%type) is begin delete from customers where id=c_id; end delcustomer; end e_package; / Adding Customer using package: declare id number:=&id; c_name varchar2(10):='&c_name'; c_address varchar2(10):='&c_address'; c_sal number:=&c_sal; begin e_package.addcustomer(id,c_name,c_address,c_sal); end; / Deleting Customer Using Package:

Faculty: Mr. Basha Wilshire Software Technologies

Page 50

PL/SQL Material 2014


declare a number:=&a; begin e_package.delcustomer(a); end; /

sql>>create or replace package body emp_sal as procedure find_sal(empno emp.empno%type) is e_sal emp.sal%type; begin select sal into e_sal from emp where empno=empno; dbms_output.put_line('sal is '||e_sal); end find_sal; end emp_sal; / *********** AUTONOMOUS TRANSACTIONS ************** --> When we call a procedure with in a procedure The procedure which is calling will be treated as called procedure and the procedure called by the procedure is called as calling procedure. if the calling procedure contains TCL(commit,rollback) those will be affected to the called procedure also. in order to overcome this we have autonomous transaction option PRAGMA autonomous_transaction; is used to have autonomous transactions ex: create or replace procedure add_emp as pragma autonomous_transaction; begin insert into emp(empno,ename) values(101,50);

Faculty: Mr. Basha Wilshire Software Technologies

Page 51

PL/SQL Material 2014


commit; end add_emp; / ************ table or view,schema,or the database. -> Executes implicitly when ever a particular event takes place -> Can be either Uses OF triggers: -> Triggers can be used for security issues -> Used as a backup of a table -> To restrict a user -> To audit the user -> Restrict the user on a particular table Triggers are of two types: Application trigger Database trigger Application Triggers: Application trigger will raise when ever an even occurs with particular application TRIGGER ************** -> A trigger is a pl/sql block or a pl/sql procedure associated with a

Database Triggers: Fires when ever a data event (such as DML) or system event(such as logon or shutdown) occurs on a schema or database. Application trigger will be of oracle forms related. GUIDLINES FOR DESIGNING TRIGGERS --> Design triggers to -> To perform related actions -> Centralized global operation CREATING DML TRIGGERS A triggering statement contains:

Faculty: Mr. Basha Wilshire Software Technologies

Page 52

PL/SQL Material 2014


*. Trigger Timing -> For table (Before, After) -> For view (Instead of) *. Triggering Event -> Insert, Update, Delete *. Object Name: -> On table, view *. Trigger Type: -> Row or statement *. When Clause: -> Restricting condition *. Trigger Body -> Pl/sql Block

Ex:

/row level -> 14 times = 14 rows modified update emp set sal=sal+200; \Statement Level -> only once for stmt

Syntax To create a trigger: create or replace trigger <trigger_name> timing event1[or event2 or event3] on <tablename> trigger_body Ex: create or replace trigger intrig before insert on emp for each row begin dbms_output.put_line('While inserting before'); end intrig; / create or replace trigger deltrig before delete on emp for each row begin dbms_output.put_line('While deleting before'); end deltrig;

Faculty: Mr. Basha Wilshire Software Technologies

Page 53

PL/SQL Material 2014


/ create or replace trigger intrig1 after insert on emp begin dbms_output.put_line('while insert after'); end intrig1; /

Creating a Single Trigger On multiple Events: create or replace trigger trig12 before insert or delete or update on emp begin if deleting then dbms_output.put_line('While Deleting'); elsif inserting then dbms_output.put_line('While Inserting'); elsif updating then dbms_output.put_line('While updating'); end if; end; / Creating DML row trigger: create or replace trigger <trig_name> timing event1 [or event2 or event3] on table [refrencing old as old/new as new for each row when condition] trigger body Column Qualifiers: OLD: It captures the old value of a datafield. NEW: It records the new values of a datafield.

Faculty: Mr. Basha Wilshire Software Technologies

Page 54

PL/SQL Material 2014


Syntax: :new.<colname> _____________________________________ | EVENT |INSERT |UPDATE |DELETE |--------| | | | OLD NO YES YES | | | | NEW YES YES NO | | | | | | |---------- |---------- |----

|---------

|------

Trigger with column qualifiers: ex1: ---create table empbkp(empno number);

>> create or replace trigger trig1 before insert on emp for each row begin insert into empbkp values(:new.empno); end; / >> select *From empbkp;

Faculty: Mr. Basha Wilshire Software Technologies

Page 55

You might also like