You are on page 1of 19

PL/SQL: It is a programming language which is developed by oracle company.

It is a procedural language it is used to process only a row at a time where as non procedural laguage process a set of rows at a time. It support to execute a bloc of stmts at once. Block: collection of executable statements. struture of block: Declare [variable Declaration]; Begin <executable statements>; [exception executable statements]; End; There are two types of blocks I) Anonoums block II) named block Anonmous Blcok: The Block which is having no name called as anonmous Block This block cannot call any other programs. used in D2K forms. Named Block: The Block which is having a named called as named block. This block can call in other PL/SQL programs. eg: procedure function Trigger package PL/SQL supports the variables&constraints SQL will supports the Bind variables only. eg\; var a number exec a:=1000 print :a PL/SQL will support bind variables &list variables. It support the Error handlings. In SQL we can see the errors on the program Or select stmt, But we cannot handle&provide the solution. Where as in PL/SQL we can handle that errors and provides the Appropriate actions. It supports conditional constructs. It supports the Iteration controls i)simple loop ii)while loop iii)for loop It supports the sub programs There are Two types of sub programs: i)function ii)proedure

EG: declare Begin null; end; Data types in PL/SQL: Scalar Composite Eg: Table Record varray Reference: Ref cursor Ref object_type LOB Variable: variables are used to store datavalues that are used by pl/sql variables are represents memory locations used to store user or database data. variables supports the simple data types and composite data types. Host variables are supports the Boolean Datatypes where as Bind variables are not supports the Boolean Datatypes. Syntax: <variable name> datatype(size); declaration part only u declare the variables. eg: declare v_empno number(4):=7902; v_name varchar2(20) not null; note: we should not assign the null values. Assignment operators: Into: This operator for internal values := This operator any external values. Executable sub languages are: DQL DML TCL We cannot use DDL,DCL directely in PL/SQL by using dynamic SQL. Syntax of Select statement: Select <column list>into <variable list> from <table name> where <condition>; Comments in PL/SQL: There are Two types of comments: i)- -single line comment ii) /* multi line comment */ DBMS_OUT.PUT_LINE('Message' Variable);

it is used to print the msg and variable value on the screen. Set serveroutput on It is environment command used to activates DBMS Statemens. SQL> 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7* declare v_sal number(7,2); v_comm number(7,2); net number(7,2); begin v_sal:=&salary; v_comm:=&comm; net:=v_sal+nvl(v_comm,0); dbms_output.put_line('the net sal is:' net); end; declare v_sal number(7,2); v_comm number(7,2); net number(7,2); begin dbms_output.put_line('the net sal is:' (&sal+nvl(&comm,0))); end;

1 declare 2 vempno number(4):=&empno; 3 vename varchar2(20); 4 vsal number(7,2); 5 vcomm number(7,2); 6 netsal number(7,2); 7 begin 8 select ename,sal,comm into vename,vsal,vcomm from emp 9 where empno=vempno; 10 netsal:=vsal+nvl(vcomm,0); 11 dbms_output.put_line('ename' ' ' 'sal' ' ' 'comm' ' ' 'netsal'); 12 dbms_output.put_line(rpad(vename,7) ' ' rpad(vsal,7) ' ' rpad(vcomm,7) ' ' n 13* end;

Nested Block: PL/SQL block can be nested the block which is declarew in another Block called as nested block or inner block or child block. Declare Begin Declare Begin end; end; note: variable forward Reference is possible the backword reference may not pos sible.

1 declare 2 m number:=100; 3 begin 4 m:=500; 5 declare 6 n number:=400; 7 total number; 8 begin 9 m:=600; 10 total:=m+n; 11 dbms_output.put_line('the sum of m,n is:' total); 12 end; --end the inner block 13 dbms_output.put_line('the m value is:' m); 14* end;

Variable Attributes: There are Two types of variable attributes. By using this variable attributes we can Make the Datatype,size independentely for a variable.. Column Type Attribute: Syntax: <variable name> <table name>.<column name>%type; Percentile type(%):- used to declare column type variables. eg: vename emp.ename%type; declare 2 vname emp.ename%type; 3 begin 4 select ename into vname from emp 5 where empno=&eno; 6 dbms_output.put_line('the ename:' vname); 7 end;

declare 2 vname emp.ename%type; 3 vdeptno emp.deptno%type; 4 begin 5 select ename,deptno into vname,vdeptno from emp 6 where empno=&eno; 7 dbms_output.put_line('the ename,deptno:' vname vdeptno); 8* end; Row Type variable attribute: It is used to declare a record type variable Syntax: <variable name> <table name>%row type; eg: i emp%row type; note:in emp table how many columns are there all are represent or available in i variable. 1 declare 2 i emp%rowtype;

3 4 5 6 7 comm 8*

begin i.empno:=&eno; select ename,sal,comm,deptno into i.ename,i.sal,i.comm,i.deptno from emp where empno=i.empno; dbms_output.put_line('the emp details are:' i.ename ' ' i.sal ' ' i. i.deptno); end;

create or replace procedure display(s varchar2) is begin dbms_output.put_line(s); end;

Flow control statements: By using flow control statements we can manipulates and process oracle data. The categery of flow control statements are: conditional control iterative control conditional controls: sequences of statements can be executed based on certain conditions using the if stmt. There are three form of if statements. i)IF_THEN_ENDIF II)IF_THEN-ELSE-ENDIF III)IF-THEN-ELSIF-ENDIF Syntax: IF condition then seuence of statements; end if; declare begin if ascii('Allen')=65 then Display('it is true'); end if; end;

syntax: If condition then sequence of statements; else sequence of statements; end if; declare v_num number(2):=&eno; begin if mod(v_num,2)=0 then display(v_num 'is an even number');

else display(v_num 'is an odd number'); end if; end; syntax: if <condition>then <executable stmts> elsif<condition>then <executstmts> elsif<condition>then <exstmts> else <exstmts> end if; declare avg_marks number:=&avgmark; grade varchar2(10); begin if avg_marks between 80 and 100 then grade:='A'; elsif avg_marks between 60 and 79 then grade:='B'; elsif avg_marks between 40 and 59 then grade:='C'; elsif avg_marks between 0 and 39 then grade:='D'; else grade:='unknown'; end if; Iterative controls: iterative statements enable you to execute a group of statements many times. Three Types; simple loop for loop while loop loop <executable stmts>; end loop; declare n number:=1; begin loop display(n); n:=n+1; end loop; end; declare

n number:=1; begin loop display(n); exit when (n>=10); n:=n+1; end loop; end; while<conditio> loop <executable stmts>; end loop;

declare n number(3):=1; begin while(n<=10) loop display(n); n:=n+1; end loop; end;

FOR loop_counter IN[Reverse] lower_bound...higer_bound loop <excut stmts>; end loop; declare begin for i in 1..10 loop display(i); end loop; end; Cursors: cursors are variables that we can define and declare section of pl/sql Block. A cursor is apl/sql construct and allows you to name of the work area access their stored information process the multiple Records note: manipulate the more than one record that time used cursor stmts. Types of cursors: two types: 1)Static cursor a)Explicit cursor b)Implicit cursor

2)Dynamic cursor (Ref cursor) Explicit cursor: It is declared by the user and manipulated by theuser and valide only in pl/sql. the life cycle of Explicit cursor goes through four stages i) declare ii)open iii)fetch iv)close i)Declare: The cursor stmt is declared explicitely in declarative section syntax: Declare cursor<cursor name> is select<list of columns> from <table name> [where condition]; Begin ------End; SQL> 2 3 4 5 6 7 8 declare cursor c1 is select empno,ename,sal,deptno from emp where deptno=20; begin null; end;

ii) open: Here the query execution done now we can fetch the data. syntax: open<cursor name> iii) fetch: The retrieves of data into the pl/sql variables or host variable is done through the fetch stmt. The fetch stmt is a simple loop to fetch the all the cursor stmt. syntax: fetch<cursor name> into <variables>; iv) close: Explicitely closes the cursor syntax: close <cursor name> Cursor Attributes: i) % found: it rerurns true if fetch is success ii) % not found: it rerurns true if fetch is not success iii) % is open: it returns true if cursor is open successfully iv) % row count: it returns no.of rows fetched Eg: 1 declare cursor c1 is 2 select empno,ename,sal 3 from emp 4 where deptno=30; 5 vempno emp.empno%type; 6 vename emp.ename%type; 7 vsal emp.sal%type; 8 begin

9 10 11 12 13 14 15 16*

open c1; loop fetch c1 into vempno,vename,vsal; exit when c1%notfound; dbms_output.put_line(vempno ' ' vename ' ' vsal); end loop; close c1; end;

1 declare 2 cursor c_sal is 3 select empno,ename,sal,job,deptno 4 from emp; 5 i emp%rowtype; 6 begin 7 open c_sal; 8 loop 9 fetch c_sal into i.empno,i.ename,i.sal,i.job,i.deptno; 10 exit when c_sal%notfound; 11 if i.job='clerk'then 12 i.sal:=i.sal+i.sal*0.25; 13 elsif i.job='manager'then 14 i.sal:=i.sal+i.sal*0.35; 15 else 16 i.sal:=i.sal+i.sal*0.15; 17 end if; 18 update emp set sal=i.sal 19 where empno=i.empno; 20 dbms_output.put_line(rpad(i.ename,8) '' rpad(i.sal,6) '' rpad(i.deptno, 10)); Types of explicit cursor: Explicit cursor with simple loop Explicit cursor with for loop Advantages: no need to declare variables no need to open the cursor explicitely no need to fetch the data no need to explicitely stop the loop no need to close the cursor syntax: for <variable> in <cursor name> loop stmts; end loop;

1 2 3 4 5 6 7 8 9 10 11 12

declare cursor comm_cur is select empno,ename,sal,comm,deptno from emp; begin for k in comm_cur loop if k.comm is null then k.comm:=300; elsif k.comm=0 then k.comm:=250;

13 14 15 16 17 18 19 20 21* 1 2 3 4 5 6 7 8 9 10 11 '' 12 13*

else k.comm:=k.comm+k.sal*0.15; end if; update emp set comm=k.comm where empno=k.empno; dbms_output.put_line(rpad(k.empno,8) '' k.comm '' k.deptno); end loop; end; declare cursor dnoc is select deptno,min(sal) low_pay, max(sal) high_pay,sum(sal) tot_pay, count(empno)noe from emp group by deptno; begin for i in dnoc loop dbms_output.put_line(i.deptno '' i.low_pay '' i.high_pay '' i.tot_pay i.noe); end loop; end;

Implicit cursor: Define by the oracle when everDml is performed in pl/sql program. Implicit cursor: An implicit cursor craete and erased by automatically. ---> During the process of an implicit cursor oracle automatically perform the o perations like open , fetch and close. ---> Attributes are i) Sql % found ii) Sql % not found iii) Sql % is open iv) Sql % row count 1 begin 2 for i in(select empno, ename,sal,deptno from emp) 3 loop 4 if i.deptno=10 then 5 i.sal:=i.sal+500; 6 elsif 7 i.deptno=20 then 8 i.sal:=i.sal+600; 9 else 10 i.sal:=i.sal+700; 11 end if; 12 update emp set sal=i.sal 13 where empno=i.empno; 14 dbms_output.put_line(rpad(i.empno,8) '' i.ename '' i.sal '' i.deptno) ; 15 end loop; 16* end;

Ref cursor: Dynamic cursor is ref cursor it refers different work area in memory. It is used to declare a cursor w/o select stmt. A Ref cursor can be reused if it is declared in package. A Ref cursor can support to return more than one row from subprogram. Two types of dynamic cursors: I) Weak Ref cursor: The cursor variable w/o return type called as Weak Ref curso r. syntax: >type<typename> is Ref cursor; II) Strong Ref cursor: The cursor variable with return type called as Strong Ref cursor. syntax: >type<typename> is Ref cursor [return <tablename>% rowtype] note: Explicit cursor is a static cursor Explicit cursor refers always one work area associated with the cursor .

features of cursors: cursor with parameter for update as { of column name now wait } ---> where current of <cursor> ---> row id ---> sub queries parametric cursor: A cursor define with parameter is called parametric cursor. the default mode of parameter is " in ". syntax: cursor <cursor name> (parameter name dtype,---) is select stmt; where current of clause to refuse the current record and fetched from the explic it cursor. for update clause explicitely focus the records stored in the private work area. Composite data types (collections) : These are two types which cannot hold any data physically i) PL/SQL Record ii) PL/SQL Table i) PL/SQL Record: A PL/SQL Record is allows you to treat sevara l variables as a unit. PL/SQL Records are similar to strutures in C syntax: Type <Type name> is record (field name1, [field name2]---); ii) PL/SQL Table: It holds the elements of the similar datatypes. it is similar like a array concept in C

syntax: type <table name> is table of <data type> index by binary-integer; here table name is collection name data type---> what type of data can plce in a index index by---> perform the no.of indexes which can hold the data temporarly binary-integer---> it is a system datatype

Exception: An exception in pl/sql block is raised during exception of blo ck. ---> it terminates the main body of the action means a block always terminates w hen pl/sql raised an exception. ---> if the exception is handled then the pl/sql block terminates successfully. Types of Exceptions: Raised implicity: (predefined exceptions) The exceptions which are declared by the oracle and ra ised implicity these exceptions are called Raised implicity. Raised explicity: Defined by the user handle by the user according to th e requirement. Predefined exception list: Exception Name i) Dup_Val_On_Index ii) Invalid cursor tion iii) Login_Denied and password iv) No_Data_Found v) To_Many_Rows ore vi) Invalid_Number ed syntax: Exception When <exception_name> Then Sql stmt When <exception_name> Then Sql stmt When Others Then Sql stmt Raise Application Error: It is built in function It is used in pl/sql This enable due to specified user defined error message and suspend the task. syntax: Raise_Application_Error <error_num> <error_msg>; Error num limit is(-20,000 and -20,999) User Defined Exception: The exception which is defined by user calle Exception Ora_0001 Ora_1001 Ora_01017 Ora_01403 Ora_1422 than one row ora_1722 Description Unique constraint violated Illigal cursor opera Incase of invalid username Data is not exist in the table A select ---into stmt matches m Conversion to a number fail

d as a User Defined Exception. This exception can invoked by the user by raised stmt. steps: i) declare the exception (in declare function) ii) raise in executable section (explicitly using raise stmt) iii) handled the raised exception Sql Code: It holds the currently raised error numbers Sql Error: It holds the currently raised error msgs syntax: display (Sql Code Prgama Exception-init: I need to display my our message, ---> it is used to handle the error just like a exception ---> to associate exception in the error code the pragma exception init is defec ted. ---> it contains two parameters i) exception name ii) error number(or)code Sub Prgrams A set of PL/SQL stmts with a name stored permentely in database Called Two types: Procedures Functions Procedure: A Procedure is a Named PL/SQL Block performing one or more actions associated to business logic. It is also called Stored procedure It accept the parameters It is Explicitely called by using Executives. It may or may not Return values. Procedurre cannot use With Select Statement. Advantages of Procedure: Using Procedure a programmer to shift the code from the Application side to the database side. Business Rules and Application logic to be stored As Procedures with in the database side. The procedural code stored within the database can be Reused Anywhere with in the Application. They nednot be rewritten in each code module of the aplication so saves the creation time of the application. Reduce the maintaince effort. Types of Procedures: Stand alone Procedure: The procedure which is created outside of the package called as This procedure will stored in user_procedures. Part of the package: This Procedure is define in a package This procedure is not stored Anywhere. Sql Error);

Parts of the Procedure: Specification: nothing but declaration section here we can give the procedure name parameters and local variables. Body: it contains pl/sql code based on this PL/SQL only the Action of procedure depend. Syntax: Create or replace Procedure<procname> [parameter[mode]datatype,-----)] is/as [local variable] Begin <executable stmts>; Exception <executable stmts>; End[procedure name]; Programs: Write a pl/sql procedure to display the SI AND CI >set serveroutput on create or replace procedure simintr (p in number,n in numbr,r in number) is si number; ci number; begin si:=(p*n*r)/100; ci:=p*power(1+r/100),n); dbms_output.put_line('The si is ' si); ('The ci is' ci); End simintr; syntax:execute<proceduree name><required argments>; Eg;execute simintr(100,10,12); PL/SQL: Begin procedure name<arg1,arg2,.......>; End; Ex: Begin simintr(100,10,12); end; o/p:si is= ci is= Parameter modes: Three types of modes i)IN ii) OUT iii) INOUT IN: It accepts a default type Always Accept values into subpgms It cannot be assigne with values in subpgms

Out: It returns a value from subpgm initilizes in subpgm it cannot carries a value into a subpgm Inout: carries a value into a subpgm Return a value from The subpgm Max 32 Argments into subpgm Syntax: <parameter name> [parameter mode]<datatype> note: Procedure maynot Return a value but through the outmode parameter procedure may Returned Remove the procedure: Drop procedure<proc name>; Eg: create or replace procedure sp (m in number, n out number) is begin n:=m*m; end sp; using Bind variable var r number exec sp(10,:r); procedure created print :r create or replace procedure proc_cal (m in number,sr out number,cr out number) is begin sr:=m*m cr:=m*m*m; end proc_cal; var sr number var cr number exec proc_cal(10,:sr,:cr) print :sr Print :cr Call this procedure in another PL/SQL Block Declare sr number; cr number; begin proc_cal(10,sr,cr); dbms_output.put_line('the sr is:' sr); ('the cr is:'cr); end;

o/p: sr is: cr is: Remove the procedure: Drop procedure <procedure name>; Pragma _autonomous transaction: It is used write the TCL commonds in trigger. it is used also in nested procedure to make each procedure independently for TCL .

Function: The function is a PL/SQL Block that Returns a Single value. Function can accept one or more parameters or no parameters. function must hava a Return clause in the executable section of a function. it is called part of expression. it is used for calculation of a value. function can user with the select stmt. function cannot use with select stme when it has a outmode,inout mode parameters . Syntax: create or replace function <fname> (parameter name[mode] datatype,------) Return <datatype> is/as [local variable] Begin <executable stmts>; Return <variable/value>; Exception <executable stmts>; end <function name>; Execution: select <function name>(argments) from dual; pl/sql: begin <sql stmts>; end; Packages: It's group of logically Related PL/SQL Types Objects and Subprograms. Package can not be invoked,parameter and nested. It has usually Two parts i)specification II)Body It allowa the oracle server to read multiple objects into memory at once.

means when we call packaged PL/SQL construct for the first time,the whole package is loaded into memory. later calls to construct in the same package Require no disk I/O Syntax for specification: create or replace packbody<packname> is/as [public variable declaration]; <subprogram bodies> End <pack name>; Syntax for The Body: create or Replace packBody <Pack name> is/as [private Variable declaration]; <subprogram bodies> End [pack name]; Execution: Execute<Packname>.<subProgname>(parameter values); Triggers: A set of PL/SQL stmts automatically executed whenever an DML stmts is performed on table. Or A Database Trigger is a named PL/SQL Block stored in a database and Executed Imp licitely when Triggering Event occurs. A Triggering Event is a Dml stmt Associated with "insert","update" or "delete" stmt executed againest a database Table. Advantages of Triggers: It is used to implement user defined Restriction on table. used to impose business Rules on data. Provides high security. Trigger can fire before or after a Triggering Events. Before: By using Before we can make the Trigger action Before performing Transa ction. After: By using After we can execute the Trigger after perform a Transaction. Defined Trigger : Row Trigger: This Trigger will be fired for every row manipulated. Generaly used for data auditing applications. By using FOR EACHROW u can make the trigger as Row level. Statement Triggers: (table level)

The Trigger will be fired only once for Dml stmt. Types of Triggers: i) Application level II) Database Triggers. Application level Triggers: The validation or rules different from each and every application we should use the application trigger. Eg: D2K forms and Reports: Database Triggers: The validation or Rules are common for Every Applicant who are Applicant who are accessing the Database we can use the Database Triggers. Trigger Qulifiers: :New.<colmn name> :Old.<column name> Triggers Qulifiers can use only in Row level. Syntax: Create or Replace Trigger <Trigger name> After/Before <insert/update/delete> (of <column name>) on <table name> [for eachrow] (when <condition>) [declare local variable]; Begin Sql stmts--------------------Exception Executable stmts End [Trigger name]; Difference between Procedure and Triggers. Procedure i)call explicitely ely against the events II) accept the parameters t parameters iii)Procedure can nested ted iv)procedure can used for storing the images V) in procedure u can use the Trigger i)call implicit ii) triggers not accep iii)trigger cannot nes iv) triggers cannot used V)Trigger may not give the comp

ilation error but gives the Run time erro the TCL command w/o compile and Runtime errors Fragma autonoums is optional tory Difference Beteen Triggers and Constraints. Triggers We can create the user define ams Triggers and we can change the of the constraints. behavior of this trigger. Trigger can check only data and future data. we can disable the all able at once. the triggers on a table at a time. Constraints constraints are the building progr and we cannot change the behavior Fragma autonomous is manda

it will check the existing feture data. if may not disable all the constraints in a t

You might also like