PL/SQL

© 2009 Wipro Ltd ² Internal & Restricted

Agenda
1 Introduction to PL/SQL 2 PL/SQL Programming Constructs 3 PL/SQL Language Features 4 SQL in PL/SQL 5 Control Structures

2

© 2009 Wipro Ltd ² Internal & Restricted

Agenda
6 Stored sub programs 7 Cursors and Data Types as in 3GL 8 Cursors 9 Packages 10 Exceptions

3

© 2009 Wipro Ltd ² Internal & Restricted

11 Triggers 12 Dependencies among PL/SQL Constructs 4 © 2009 Wipro Ltd ² Internal & Restricted .).Agenda (Contd.

1. Introduction to PL/SQL 5 © 2009 Wipro Ltd ² Internal & Restricted .

PL/SQL .Introduction ‡ Integrating Programming Features with SQL Programming Language +SQL=PL/SQL ‡ PL/SQL submits the request as a Block 6 © 2009 Wipro Ltd ² Internal & Restricted .

What is PL/SQL Block ‡ PL/SQL Block comprises of ± SQL Statements ± PL features like ‡ Conditional Statements ‡ Looping Constructs ± Additional features like ‡ Stored Procedures ‡ Exceptions ‡ Triggers 7 © 2009 Wipro Ltd ² Internal & Restricted .

Why PL/SQL? ‡ Connectivity exists between consecutive requests in PL/SQL ‡ Logical implementation of user·s requirement is made possible with PL/SQL 8 © 2009 Wipro Ltd ² Internal & Restricted .

PL/SQL Engine ‡ It is a separator. which splits the SQL and PL/SQL statements. ‡ PL/SQL is available ± Client Side ± Server Side 9 © 2009 Wipro Ltd ² Internal & Restricted .

««...SERVER««««.. 10 © 2009 Wipro Ltd ² Internal & Restricted .Where PL/SQL stands? Front end application Program « «. Query PL/SQL SQL Data DATABASE ««««««. «. Invoking PL/SQL PROCEDURE «.

11 © 2009 Wipro Ltd ² Internal & Restricted . End.PL/SQL Block [Declare Variable Declarations (if any) ] Begin SQL / PL-SQL Statements [ Exception] «.

Advantages of PL/SQL ‡ Block structured ± SQL statements are grouped and send as one consolidated request to the server. Improved Performance ± Network traffic can be reduced Security ± Access to the data through PL/SQL ± Limited actions allowed over the table through PL/SQL Portable ± Work wherever Oracle Works ‡ ‡ ‡ 12 © 2009 Wipro Ltd ² Internal & Restricted .

Advantages-Contd. ‡ Stored Procedures ± Additional Features like Stored procedures and Triggers are included ± Stored Procedures are available in the server as database objects and is ready to execute 13 © 2009 Wipro Ltd ² Internal & Restricted . ‡ Compatibility ± Supports all the data types available in Oracle/SQL.

Nesting of Blocks ‡ ‡ ‡ ‡ ‡ Blocks within the other Block Sub Blocks are allowed to enhance the modularity Inner blocks follow the similar syntax The variables declared in the inner block is valid till the end of that block No limitations on number of nested blocks 14 © 2009 Wipro Ltd ² Internal & Restricted .

PL/SQL Program Constructs 15 © 2009 Wipro Ltd ² Internal & Restricted .2.

PL/SQL Program Constructs Anonymous Block Packages PL/SQL BLOCK Stored Procedure/ Programs Triggers Procedures Functions 16 © 2009 Wipro Ltd ² Internal & Restricted .

It can·t be accessed/referred neither by oracle nor by user for execution Has to be compiled every time we need that block of statements Both compilation and execution are done at the server end.Anonymous Block ‡ ‡ ‡ ‡ ‡ PL/SQL block without a name for identification It has to be brought to the server·s memory every time it is required. 17 © 2009 Wipro Ltd ² Internal & Restricted .

Synonyms ‡ Stored in the ready to executable form ‡ Can be referred by other PL/SQL block ‡ One copy is brought to the buffer for sharing by multiple users 18 © 2009 Wipro Ltd ² Internal & Restricted . Indexes.Stored Procedures ‡ Named PL/SQL Block ‡ Stored as Database Objects like Tables.Views. Sequences.

Procedures or Functions ‡ Collectively identified as one Database object 19 © 2009 Wipro Ltd ² Internal & Restricted .Packages ‡ Collection of related objects ‡ The components can be variables.

Triggers ‡ The PL/SQL Block which gets fired automatically whenever some specified event happens ‡ The chain of actions to be performed can be written in the trigger body for continual execution ‡ Will be invoked by oracle automatically 20 © 2009 Wipro Ltd ² Internal & Restricted .

3. PL/SQL Language Features

21

© 2009 Wipro Ltd ² Internal & Restricted

Glimpse of PL/SQL Block
Declare Variable declaration v_designation varchar2(15); Begin select job Data Retrieval from Table into v_designation into Variable from emp where ename='SCOTT'; if (v_designation = 'MANAGER') then update emp set sal=sal*1.5 where ename='SCOTT'; else update emp set sal=sal*1.05 where ename='SCOTT'; End if; End;
22 © 2009 Wipro Ltd ² Internal & Restricted

Lexical Unit
‡ Character Set ± Alphabets (both upper and lower) ± Numerals ± Special Characters like #,%,$,etc., ‡ Commenting ± Two Consecutive hyphens -- for single line comment and /*«..*/ for multi line comments ‡ Delimiter ± Every statement in PL/SQL Block is separated using semicolon(;)

23

© 2009 Wipro Ltd ² Internal & Restricted

Variables ‡ ‡ ‡ ‡ Identifier is the name given for variables Identifiers used to hold values that is to be used in PL/SQL block All the variables must be declared before the begin and end block Scope of this variable is within the block 24 © 2009 Wipro Ltd ² Internal & Restricted .

Rules-Identifier ‡ It is user defined name and should not be oracle defined names (reserved words) ‡ It should start with an alphabet ‡ Can have zero or more additional characters ± 0 to 9 or Alphabets(A-Z or a-z) ± Symbols like # or $ or _ are also allowed ‡ Follow Standards ² Naming Conventions 25 © 2009 Wipro Ltd ² Internal & Restricted .

Varchar.Tables ± Cursors 26 © 2009 Wipro Ltd ² Internal & Restricted .Varchar2. Integer ± Character ²Char.Long ± Date ± Boolean ‡ Composite Data Type ± Record.Data Types ‡ Primitive Data Type ± Numeric ² Number.

HRA Number(7. 27 © 2009 Wipro Ltd ² Internal & Restricted .2). DA Number(7.2):=2000. Example Salary Number(7.Declaration .Example Syntax is Variable Name Data Type [ DEFAULT ] [ NOT NULL ] [ NULL ].2) default 3000.

Declaration ‡ ‡ ‡ ‡ Identifiers are to be declared before their usage Map to relevant data types Memory and initialization will be done every time it is executed Multiple Declaration is not allowed 28 © 2009 Wipro Ltd ² Internal & Restricted .

PUT_LINE(A). END.PUT_LINE(A). -. BEGIN DBMS_OUTPUT..Print A A is 100 or 200? .Inner Block ends DBMS_OUTPUT. 29 © 2009 Wipro Ltd ² Internal & Restricted What would be the value of A? -.Scope & Visibility of Variables In nested Blocks Declare A number: =200. Declare --Inner Block Starts A number:=100. END. BEGIN ««. «.

A). BEGIN ««. BEGIN DBMS_OUTPUT.LABEL << « >> <<outer>> Declare A number: =200.. Print 100 and then 200 «. -. Declare --Inner Block Starts A number:=100. END. END.PUT_LINE(A). 30 © 2009 Wipro Ltd ² Internal & Restricted .Inner Block ends DBMS_OUTPUT.PUT_LINE(A || outer.

‡ Data :=null. ± Assign null to the variable ¶Data· ± By default un-initialized variables are assigned to null irrespective of the data type of the variable 31 © 2009 Wipro Ltd ² Internal & Restricted . ± Assign 10 to the variable A.Operators-Assignment ‡ := is the assignment operator in PL/SQL ‡ Example A:=10.

BETWEEN. . LIKE.Operators ‡ Arithmetic Operators ± * . AND. OR 32 © 2009 Wipro Ltd ² Internal & Restricted . = and != or <> or ~= ± IS NULL. >=.. >. / .IN ‡ Logical Operators ± NOT.mod ‡ Comparison Operators ± Relational Operators ‡ <. + . <=.

Built-in-Functions ‡ ‡ ‡ ‡ ‡ ‡ Number Character Conversion Date Error Reporting Others 33 © 2009 Wipro Ltd ² Internal & Restricted .

34 © 2009 Wipro Ltd ² Internal & Restricted .TAN.Number Functions ‡ ‡ ‡ ‡ ‡ ROUND TRUNC MOD POWER.SQRT COS.SIN.LOG.

Upper.Character Function ‡ ‡ ‡ ‡ ‡ ‡ Lower.Translate 35 © 2009 Wipro Ltd ² Internal & Restricted . Rtrim Substr. Rpad Ltrim. Concat Length Replace. Initcap Lpad.

Date -Function ‡ ‡ ‡ ‡ ‡ ‡ ‡ ‡ Sysdate Last_day Months_between Round Trunc Add_months New_time Next_day 36 © 2009 Wipro Ltd ² Internal & Restricted .

Conversion Function ‡ ‡ ‡ ‡ ‡ ‡ ‡ To_char To_date To_number Chartorowid Rowidtochar Hextoraw rawtohex 37 © 2009 Wipro Ltd ² Internal & Restricted .

Error Reporting Functions ‡ SQLERRM ‡ SQLCODE 38 © 2009 Wipro Ltd ² Internal & Restricted .

Functions ‡ ‡ ‡ ‡ ‡ DECODE GREATEST LEAST NVL USER 39 © 2009 Wipro Ltd ² Internal & Restricted .Others .

4. SQL In PL/SQL

40

© 2009 Wipro Ltd ² Internal & Restricted

Data Retrieval From PL/SQL
‡ SQL Select statement is the only source for data retrieval. ‡ From PL/SQL the data can be retrieved with the help of Select Statement with added INTO clause. ‡ PL/SQL Block can include all DML,TCL commands and not DDL & DCL commands directly

41

© 2009 Wipro Ltd ² Internal & Restricted

INTO Clause
Data From SQL into PL/SQL ‡ Syntax of SELECT statement in PL/SQL is SELECT column [list] INTO variable [list] FROM table [list] [WHERE condition(s) ] ‡ SQL data retrieval ² SELECT list ‡ PL/SQL data mapping - INTO list

42

© 2009 Wipro Ltd ² Internal & Restricted

dbms_output. deptno INTO v_name. 43 © 2009 Wipro Ltd ² Internal & Restricted .Example DECLARE v_name varchar2(10). v_dno FROM emp WHERE empno=7788. BEGIN SELECT ename.INTO Clause . END.put_line(v_name||·is working for ¶||v_dno). v_dno number(2).

Example ² 2 DECLARE v_name varchar2(10). end. ‡ What is wrong with this query? ‡ Will this query work if there are more that 1 employee working for deptno 10 ? ‡ Will this query work if there are no employees working for deptno 10? 44 © 2009 Wipro Ltd ² Internal & Restricted . Begin SELECT ename INTO v_name FROM emp WHERE deptno=10.

Restrictions ‡ Select statement in PL/SQL can retrieve only one record at a time ‡ SELECT & INTO clause should contain ± Equal number of columns list and variable list ± Similar (compatible) data types ± Order of specification of select statement corresponding to its appropriate variable list 45 © 2009 Wipro Ltd ² Internal & Restricted .

end. ‡ DML commands can be executed through PL/SQL without any modification in the syntax. TEXAS ). v_new_mgr:=7788 update emp set mgr=v_new_mgr where mgr=v_eno. insert into dept values(60. FINANCE . ‡ DML Can use compatible data items 46 © 2009 Wipro Ltd ² Internal & Restricted .DML in PL/SQL Begin v_eno:=7782. delete emp where empno=v_eno.

end if.TCL in PL/SQL DECLARE v_sal number(7. 47 © 2009 Wipro Ltd ² Internal & Restricted . BEGIN update emp set sal=sal*1. select sum(sal) into v_sal from emp.50. END. else commit. if v_sal > 1000000 then rollback.2).

& Substitution Variable ‡ Prompt the user for data ‡ Example ± data:=&value1. &dname. ‡ SQL * PLUS specific command ‡ Prompts at compile time with the predefined message ¶enter the value for dno:· 48 © 2009 Wipro Ltd ² Internal & Restricted . ± Insert into dept values (&dno. &loc). ± Select * from emp where deptno=&dno.

Session specific 49 © 2009 Wipro Ltd ² Internal & Restricted .Host variables ‡ Referred as bind variables ‡ Usage ± ± ± SQL:>VAR X NUMBER --declare variable SQL:>EXECUTE :X:=10 --define it SQL:>PRINT X --refer it in SQL ‡ Scope .

PL/SQL Block 2 begin dbms_output. --prints 20 end.Example PL/SQL Block 1 Begin a:=:x.put_line (:x). --assign 20 to variable x end. 50 © 2009 Wipro Ltd ² Internal & Restricted .Bind variables . --acts as global variable :x:=:x + a.

Control Structures 51 © 2009 Wipro Ltd ² Internal & Restricted .5.

Executing the statements one after the other ‡ Control can be transferred as required based on the logic using any one of the control structures ± Conditional Statements ± Looping Constructs 52 © 2009 Wipro Ltd ² Internal & Restricted .Control Structures ‡ By default control flows in sequential manner .

ELSIF«.THEN«.END IF 53 © 2009 Wipro Ltd ² Internal & Restricted .THEN«.ELSE«.END IF ± IF«.THEN«.END IF ± IF«.Conditional Statements ‡ Branches the execution by checking the condition ‡ Can be done using IF statements ‡ Types of IF statements available are ± IF«.

END IF. Example 2: IF (V_JOB=¶SALESMAN·) THEN V_BONUS:=2000. END IF. 54 © 2009 Wipro Ltd ² Internal & Restricted . ELSE V_BONUS:=1000.IF Statement -Example Example 1: IF (V_JOB=¶CLERK·) THEN V_BONUS:=2000.

55 © 2009 Wipro Ltd ² Internal & Restricted .IF ²THEN-ELSE Example 3: IF (V_JOB= SALESMAN ) THEN V_BONUS:=2000. END IF. ELSE V_BONUS:=1000. END IF. ELSE IF (V_JOB= CLERK ) THEN V_BONUS:=3000.

ELSIF (V_JOB= CLERK ) THEN V_BONUS:=3000. ELSE V_BONUS:=1000.ELSIF -Example Example 4: IF (V_JOB= SALESMAN ) THEN V_BONUS:=4000. 56 © 2009 Wipro Ltd ² Internal & Restricted . ELSIF (V_JOB= ANALYST ) THEN V_BONUS:=2000. END IF.

END CASE. WHEN condition THEN statements.CASE ‡ To group multiple conditions ‡ Syntax is CASE WHEN condition THEN statements. ELSE statements. 57 © 2009 Wipro Ltd ² Internal & Restricted .

END LOOP ± WHILE «LOOP«END LOOP ± FOR«IN«LOOP«END LOOP 58 © 2009 Wipro Ltd ² Internal & Restricted .Looping Constructs ‡ Executes set of statements repeatedly ‡ Looping Constructs ± LOOP«.

.. END LOOP ‡ Statements between LOOP and END LOOP will be executed repeated and also infinitely ‡ Use EXIT to terminate the endless looping 59 © 2009 Wipro Ltd ² Internal & Restricted . «.LOOP«END LOOP LOOP «.

END LOOP «. 60 © 2009 Wipro Ltd ² Internal & Restricted . EXIT. «..EXIT LOOP «..

PUT_LINE (¶Exceeded limit 10·).Example Loop « EXIT WHEN CNT>10.EXIT WHEN . IF (CNT>10) THEN DBMS_OUTPUT. « END LOOP. END IF. EXIT. 61 © 2009 Wipro Ltd ² Internal & Restricted .

to avoid infinite looping 62 © 2009 Wipro Ltd ² Internal & Restricted . ‡ Statements between LOOP and END LOOP will be executed while the condition is true ‡ Toggle the condition in loop body .WHILE LOOP WHILE (condition) LOOP « END LOOP.

FOR LOOP FOR counter IN [REVERSE] start_value . ‡ Implicit declaration ² FOR loop variable ‡ Scope is within the loop 63 © 2009 Wipro Ltd ² Internal & Restricted . final_value LOOP « END LOOP..

FOR LOOP - Example
FOR cnt IN 1..10 LOOP dbms_output.put_line (cnt); END LOOP; FOR cnt IN REVERSE 1..10 LOOP dbms_output.put_line (cnt); END LOOP;

64

© 2009 Wipro Ltd ² Internal & Restricted

NULL - Statement
‡ PL/SQL statement used to do nothing ‡ Blindly transfers the control to the next line without executing anything Example if (a=10) then NULL; else dbms_output.put_line (¶a is not equal to 10·); end if;

65

© 2009 Wipro Ltd ² Internal & Restricted

6. Stored Sub Programs

66

© 2009 Wipro Ltd ² Internal & Restricted

Advantages of Subprograms ‡ ‡ ‡ ‡ ‡ ‡ Modular approach Improved Maintenance Stored in an executable format Stored as Database objects in the server Security Parameterized 67 © 2009 Wipro Ltd ² Internal & Restricted .

Types of Parameters ‡ Formal Parameters ‡ Actual Parameters 68 © 2009 Wipro Ltd ² Internal & Restricted .

6. Stored Procedures 69 © 2009 Wipro Ltd ² Internal & Restricted .1.

OUT. IN OUT) ‡ IN Parameter ± To send input values to the sub program ‡ OUT Parameter ± Carry output values to the calling environment ‡ IN OUT Parameter ± Used in both the directions to send and carry from the sub block to the calling block 70 © 2009 Wipro Ltd ² Internal & Restricted .Different Modes of Parameters (IN.

IN Parameter ‡ Takes input to the sub program ‡ Formal Parameter ± If mode is not specified treated as IN parameter ± Is used as constant (IN parameter can·t be altered inside the sub program) ‡ The actual Parameter ± Can be variable. literal or an expression ± Should be an initialized variable 71 © 2009 Wipro Ltd ² Internal & Restricted .

OUT Parameter ‡ Carries the output to the calling environment ‡ Formal Parameter ± Mode OUT is specified explicitly ± OUT parameter is filled with the output data ‡ The actual Parameter ± Must be a variable ± Should be un-initialized 72 © 2009 Wipro Ltd ² Internal & Restricted .

IN OUT Parameter ‡ Send and receive data to and from the sub block ‡ Formal Parameter ± Mode IN OUT is specified explicitly ± Acts as input as well as output parameter ‡ The actual Parameter ± Must be a variable ± Should be initialized 73 © 2009 Wipro Ltd ² Internal & Restricted .

Formal parameter2 [MODE] Data type.Creating the Procedure CREATE [OR REPLACE] PROCEDURE Procedure name [(Formal parameter1 [MODE] Data type.)] IS/AS [Local_variable Data type] PL/SQL Block 74 © 2009 Wipro Ltd ² Internal & Restricted . «.

75 © 2009 Wipro Ltd ² Internal & Restricted .

Procedure .v_job from emp where empno=v_eno. end.job into v_name. v_name OUT varchar2. 76 © 2009 Wipro Ltd ² Internal & Restricted .Example Create or replace procedure retrieve( v_eno IN number. v_job OUT varchar2) is begin select ename.

Invoking the Procedure To call the procedure ´retrieveµ with 1 IN parameter and 2 OUT parameters SQL:>variable name varchar2(15) SQL:>variable job varchar2(15) SQL:> execute retrieve(7788.:job). Use PRINT command to know the ouptut SQL:>PRINT NAME SQL:>PRINT JOB 77 © 2009 Wipro Ltd ² Internal & Restricted .:name.

Invoking the Procedure ‡ To call the procedure ´retrieveµ with 1 IN parameter and 2 OUT parameters from an anonymous block Declare v_name varchar2(15). End. v_job varchar2(15).v_job). 78 © 2009 Wipro Ltd ² Internal & Restricted . Begin retrieve(7788.v_name.

‡ Example drop procedure retrieve. 79 © 2009 Wipro Ltd ² Internal & Restricted .Removing the Procedure ‡ Syntax is DROP PROCEDURE procedure_name.

Data Dictionary Views ‡ ‡ ‡ ‡ DESC procedure_name DESC USER_SOURCE DESC USER_OBJECTS DESC USER_DEPENDENCIES 80 © 2009 Wipro Ltd ² Internal & Restricted .

Stored Functions 81 © 2009 Wipro Ltd ² Internal & Restricted .6.2.

Stored Function
‡ Named and stored PL/SQL Block ‡ Should return at least one value ‡ Used like Built-in functions ± It can be single row function and not group function ‡ Invoked as part of expression ± No separate statement is needed to invoke functions

82

© 2009 Wipro Ltd ² Internal & Restricted

Creating the Functions
Syntax is CREATE [OR REPLACE] FUNCTION function_name [(Formal parameter1 [MODE] Data_type, Formal parameter2 [MODE] Data_type, «.)] RETURN Data_type IS|AS PL/SQL Block;

83

© 2009 Wipro Ltd ² Internal & Restricted

Return Statement
‡ RETURN data_type ± Only type has to be specified and size specification is not allowed ± Can be Scalar data type and composite data types. ± Can return only one value ± Should have at least one return statement in the PL/SQL block ‡ RETURN variable;

84

© 2009 Wipro Ltd ² Internal & Restricted

Example Create or replace function ret_maxsal (dno IN number) Return number IS v_sal number. Begin Select max(sal) Into v_sal From emp Where deptno = dno. Return v_sal. End. 85 © 2009 Wipro Ltd ² Internal & Restricted .

deptno) values(1234.50). 86 © 2009 Wipro Ltd ² Internal & Restricted .Invoking the Function ‡ SQL:>execute :salary:=ret_maxsal(10) ‡ Insert into emp (empno. sal.ret_maxsal(10). ‡ select ename from emp where sal>ret_maxsal(20).

Also remove the related data dictionary entries and contents.Removing the Function ‡ DROP FUNCTION function_name Example ± DROP FUNCTION ret_maxsal Will remove the stored function ret_maxsal. 87 © 2009 Wipro Ltd ² Internal & Restricted .

CHAR.Restrictions on using functions ‡ Single row function and not group function ‡ Should not have OUT and IN OUT parameters ‡ In case the functions are invoked from SQL ± Return data type should be a primitive data type like NUMBER. DATE ± Return data type should not be composite data type which is supported only in PL/SQL 88 © 2009 Wipro Ltd ² Internal & Restricted .

Procedures Vs Functions PROCEDURE FUNCTION Invoked as separate statement Can be invoked as part of expression Return zero or more values Return one value using Return using OUT parameter statement 89 © 2009 Wipro Ltd ² Internal & Restricted .

Data Dictionary Views ‡ ‡ ‡ ‡ ‡ DESC function_name DESC USER_SOURCE DESC USER_OBJECTS DESC USER_DEPENDENCIES DESC USER_ERRORS 90 © 2009 Wipro Ltd ² Internal & Restricted .

Cursors and Data types (as in 3GL) 91 © 2009 Wipro Ltd ² Internal & Restricted .7.

SAL NUMBER(7.%TYPE Declare V_SAL EMP. NUMBER(7.2) 92 © 2009 Wipro Ltd ² Internal & Restricted . DATA DICTIONARY DESC EMP «.SAL%TYPE.2) «..

« ± Implicit data type (structure) specification. 93 © 2009 Wipro Ltd ² Internal & Restricted . ± Fetch the current data type of SAL column.sal%type.%Type ‡ Declare v_sal emp. ± Map it for the variable v_sal. ± Refer the data dictionary for EMP table.

sal%TYPE. Example 2 DECLARE sal emp.%TYPE . 94 © 2009 Wipro Ltd ² Internal & Restricted . eno NUMBER(4).Example Example 1 DECLARE var1 NUMBER(7. var2 var1 %TYPE.2).

V_job varchar2(10).v_job.v_mgr.v_hiredate. Begin Select * Into v_eno. V_comm number(7.Example . v_comm.1 ‡ Retrieve all the columns of particular employee Declare V_eno number(4). V_sal number(7.v_sal.2). V_mgr number(4). V_hiredate date.v_dno «« 95 © 2009 Wipro Ltd ² Internal & Restricted .2). V_name varchar2(15).v_ename. V_dno number(2).

if (myemp.comm 96 © 2009 Wipro Ltd ² Internal & Restricted . i. ‡ To access the variables use rowtype variable and name of the column.myemp..%ROWTYPE Declare myemp emp%rowtype. Begin select * into myemp «.e.comm is not null) then « ‡ Structure of emp table is referred and copied to variable myemp.

Record Type ‡ ‡ ‡ ‡ User defined. customized data type Like structures in C Collection of various members Create the Data type and declare record variable which refers the user defined record type 97 © 2009 Wipro Ltd ² Internal & Restricted .

dname dept. my_emp my_data.dept WHERE emp. 98 © 2009 Wipro Ltd ² Internal & Restricted .Example DECLARE TYPE my_data is RECORD (ename emp. BEGIN SELECT ename. END.deptno AND empno=&ENO.dname%TYPE).ename%TYPE.Record Type .dname INTO my_emp FROM emp.dname).deptno=dept.put_line(my_emp. dbms_output.ename ||my_emp.

2). -.Record Type .2)).2). 99 © 2009 Wipro Ltd ² Internal & Restricted .Example TYPE WBP IS RECORD (LTA NUMBER(7. HRA NUMBER(7. my_allowance. fon NUMBER(7.LTA:=3000.fon:=2000.declare variable of record type WBP BEGIN my_allowance. my_allowance WBP.

PL/SQL Table ‡ ‡ ‡ ‡ Collection of records and not rows Store records like arrays Single dimensional No limits for upper bound ± Can store as many records as needed. 100 © 2009 Wipro Ltd ² Internal & Restricted .

PL/SQL Tables-Example 101 © 2009 Wipro Ltd ² Internal & Restricted .

Built-in-Functions ‡ Built in functions used to access PL/SQL tables are ± COUNT ± EXISTS(N) ± FIRST . LAST ± NEXT . PRIOR ± DELETE(N) 102 © 2009 Wipro Ltd ² Internal & Restricted .

Advantages-Composite Data types ‡ When the structure of base table changes no need to modify the PL/SQL block ‡ Refers the current structure and variables are declared accordingly ‡ Provides Logical Independence ‡ %ROWTYPE helps user to avoid individual member specification ‡ Helpful when row is retrieved from SQL 103 © 2009 Wipro Ltd ² Internal & Restricted .

8. Cursors 104 © 2009 Wipro Ltd ² Internal & Restricted .

When and Why Cursors ‡ ‡ ‡ ‡ Fetching more than one record is not possible with simple variables Can be done through cursors Cursor is the memory area with pointers Temporary memory area used to store data getting referred during ± PL/SQL fetch operation ± And DML statements 105 © 2009 Wipro Ltd ² Internal & Restricted .

Named and used by programmer ± Controlled by user 106 © 2009 Wipro Ltd ² Internal & Restricted .Implicit & Explicit Cursors ‡ Implicit Cursors ± Handled and controlled by Oracle ± System defined cursors ± Memory area used temporarily for fetching and DML operation ‡ Explicit Cursors ± Defined .

Cursor Attributes-Implicit ‡ SQL%ROWCOUNT ± Number of rows affected by the most recent SQL statement ‡ SQL%FOUND ± TRUE if the most recent SQL found any row ± Set to TRUE if SQL%ROWCOUNT is <>0 ‡ SQL%NOTFOUND ± TRUE if the most recent SQL didn·t find any row ± Set to true if SQL%ROWCOUNT is =0 or SQL%Found is false ‡ SQL%ISOPEN ± Always FALSE because control will be transferred to the user after closing implicit cursor 107 © 2009 Wipro Ltd ² Internal & Restricted .

end. end if. delete from emp where deptno=dno.put_line ('no employees working for deptno ||dno). end if.Example Declare dno number(4). if (sql%found) then dbms_output. Begin dno:=&depno.put_line (sql%rowcount). if (sql%notfound) then dbms_output. 108 © 2009 Wipro Ltd ² Internal & Restricted .

Brings the active set into the cursor area NP 109 © 2009 Wipro Ltd ² Internal & Restricted . OPEN CURSOR open my_cur.Stages in Cursors START No into in select DECLARE CURSOR Declare Cursor my_cur is select ename.sal from emp.

Stages in Cursors NP FETCH CURSOR INTO VARIABLE Fetch my_cur into cur_rec. IS EMPT Y YES CLOSE CURSOR close my_cur. STOP NO 110 © 2009 Wipro Ltd ² Internal & Restricted .

± Data type of the variable depends on structure of the cursor ± Variable can be declared using %rowtype of cursor or individual component specification is also allowed 111 © 2009 Wipro Ltd ² Internal & Restricted .Cursor to Record type ‡ Fetch cursor into variable ± Fetches the current record from active set to the PL/SQL variable.

Begin . sal from emp.sal%type.ename%type. 112 © 2009 Wipro Ltd ² Internal & Restricted . v_ename emp.v_sal.Cursor to Record type Example Declare Cursor my_cur is select ename. Example Declare . Fetch my_cur into cur_rec. Begin . v_sal emp. Fetch my_cur into v_ename. cur_rec my_cur%rowtype.

Explicit Cursor Attributes ‡ %ROWCOUNT ± Number of rows fetched so far by the cursor ‡ %FOUND ± TRUE if the most recent fetch operation found any row ‡ %NOTFOUND ± TRUE if the most recent fetch didn·t find any new record in cursor·s active set ± Set to TRUE if %Found is FALSE ‡ %ISOPEN ± Shows the status of the cursor ± TRUE if it is open else it is FALSE. 113 © 2009 Wipro Ltd ² Internal & Restricted .

Cursor Attributes-Explicit 114 © 2009 Wipro Ltd ² Internal & Restricted .

END LOOP.Cursor with FOR loop ‡ For record_variable IN cursor_name LOOP «. ‡ No need ± ± ± ± ± To declare the record_variable To Open To Fetch into record_variable To Check for new data found or not To Close 115 © 2009 Wipro Ltd ² Internal & Restricted .

116 © 2009 Wipro Ltd ² Internal & Restricted .

Example declare cursor dep_cur is select * from emp where deptno=10 order by sal. Salary details').sal). end. 117 © 2009 Wipro Ltd ² Internal & Restricted .put_line('-------------------------------'). begin dbms_output.put_line('-------------------------------').No.put_line ('Sl. FOR dep_rec IN dep_cur LOOP dbms_output.put_line('-------------------------------').ename ||'''s salary is '||dep_rec. dbms_output. dbms_output.put_line (dep_cur%rowcount||' '||dep_rec. END LOOP. dbms_output.

close 118 © 2009 Wipro Ltd ² Internal & Restricted . ‡ No need to ± declare the cursor and record variable ± Implicit open. check for empty. fetch.Sub queries in FOR loop ‡ FOR record_variable in (Sub query) LOOP « END LOOP.

. 119 © 2009 Wipro Ltd ² Internal & Restricted . END LOOP. End.Example ‡Begin Implicit declaration of cursor is done in the for loop FOR dep_rec IN (select * from emp where deptno=10 order by sal) ‡ No Access to the Explicit cursor attributes LOOP .

Cursor with Parameters Declare cursor dep_cur (v_did number) is select count(*) cnt from emp where deptno=v_did . close dep_cur. end. open dep_cur(20). dbms_output.put_line (dep_rec. --Retrieve dept 10 employees fetch dep_cur into dep_rec.put_line (dep_rec. cnt). 120 © 2009 Wipro Ltd ² Internal & Restricted . dep_rec dep_cur%rowtype. close dep_cur. --Retrieve dept 20 employees fetch dep_cur into dep_rec. dbms_output. Begin open dep_cur(10). cnt).

Locking ‡ ‡ ‡ ‡ Locks the data retrieved for updating No separate request is needed during update operation Use ´FOR UPDATEµ clause in SELECT statement To refer recently fetched record use ´WHERE CURRENT OF cursor nameµ 121 © 2009 Wipro Ltd ² Internal & Restricted .

122 © 2009 Wipro Ltd ² Internal & Restricted .FOR UPDATE ‡ Syntax is Select «. FOR UPDATE [OF COLUMN] [NOWAIT] ‡ Locks the ROWS being read for updating ‡ Other user·s request for the rows locked will be in the wait state ‡ Locks can be released using rollback/commit ‡ Example ± SELECT * FROM EMP WHERE DEPTNO=10 FOR UPDATE..

‡ No additional specifier is needed to refer the locked rows. ‡ Example ± DELETE emp WHERE CURRENT OF my_cur.WHERE CURRENT OF ‡ Syntax WHERE CURRENT OF cursor name. ‡ Used in Update & Delete commands ‡ Refers the rows recently fetched by the cursor. 123 © 2009 Wipro Ltd ² Internal & Restricted .

update emp set comm=1000 WHERE CURRENT OF my_cur.Example Declare Cursor my_cur IS Select * from emp where deptno=10 FOR UPDATE. current_rec my_cur%rowtype. 124 © 2009 Wipro Ltd ² Internal & Restricted . Begin . FETCH my_cur INTO current_rec.

9. Packages 125 © 2009 Wipro Ltd ² Internal & Restricted .

Introduction to Packages ‡ Groups related components together and stored as single object .Package ‡ Components includes ± Variables ± Sub Programs ²Packaged Subprograms  Functions  Procedures ± Cursors ± And all PL/SQL allowed Constructs 126 © 2009 Wipro Ltd ² Internal & Restricted .

Advantages of Packages ‡ Modularity ± Related modules are grouped and kept as one collection ‡ Interface ± Provides single and simple interface to access its components ‡ Sharable object ± Can be shared by many users at a time ‡ Minimal disk I/O ± Loads the code into the memory when it is referred for the first time 127 © 2009 Wipro Ltd ² Internal & Restricted .

Advantages ‡ Extended Functionality ± Additional facility provided along with stored sub programs ‡ Security ± Decide upon the list of operations allowed over the database objects ‡ Global Access ± Declared variable are accessible from anywhere ± Data remains throughout the session ‡ Overloading ± Is allowed with packaged sub programs and not with stored sub programs 128 © 2009 Wipro Ltd ² Internal & Restricted .

129 © 2009 Wipro Ltd ² Internal & Restricted .Packages -Restrictions ‡ Nesting is not allowed ± Creating package within another package is not allowed ‡ Parameter ± Parameter can·t be passed in packages ‡ Calling the Package directly is not possible ± Package can be referred by invoking any of the components and not the package directly.

· ‡ Creation of Packages involves two steps ± Package Specification-Header ‡ Includes details about WHAT it consists of? ± Package Body ‡ Implements/defines the specification ‡ Can change the contents without disturbing the header 130 © 2009 Wipro Ltd ² Internal & Restricted .Packages ‡ Components of the package is referred ± Using the package name as primary identifier ± Component name as second identifier ± Separated using a dot operator ¶.

Sub Program header specification.Package Specification ‡ Syntax CREATE [OR REPLACE] PACKAGE package_name IS Variable Declaration. END [package_name]. 131 © 2009 Wipro Ltd ² Internal & Restricted .

PROCEDURE retrieve_bonus(p_eno NUMBER). END [package_name]. 132 © 2009 Wipro Ltd ² Internal & Restricted . END bonus_pack. Sub Program header specification.Package Specification Syntax CREATE [OR REPLACE] PACKAGE package_name IS Variable Declaration. Example CREATE OR REPLACE PACKAGE bonus_pack IS v_bonus NUMBER:=0.

END [package_name]. 133 © 2009 Wipro Ltd ² Internal & Restricted . packaged sub program definition. local sub program declaration.Package Body ‡ Local variables and sub programs are declared and used inside the body ‡ They are local to the Package body -Private CREATE [OR REPLACE] PACKAGE BODY package_name IS local variable declaration.

11 v_bonus:=v_sal*0. 134 © 2009 Wipro Ltd ² Internal & Restricted . SQL> / Package body created.2+v_bonus. 13* END bonus_pack. 12 END retrieve_bonus. comm 8 INTO v_sal.Package Body 1 CREATE OR REPLACE PACKAGE body bonus_pack 2 IS 3 PROCEDURE retrieve_bonus (p_eno NUMBER) 4 IS 5 v_sal NUMBER. v_bonus 9 FROM emp 10 WHERE empno = p_eno. 6 BEGIN 7 SELECT sal.

dbms_output. 135 © 2009 Wipro Ltd ² Internal & Restricted .v_bonus:=200.retrieve_bonus(7369).retrieve_bonus(7788).Referencing Package objects SQL:>EXECUTE bonus_pack. SQL:>EXECUTE bonus_pack. BEGIN bonus_pack.v_bonus).v_bonus:=1000. . END.put_line(bonus_pack. bonus_pack.

Public and Private Members ‡ Declarations in package specification are public members ± Allowed for public reference ‡ In package body all the declarations made like local variable. subprograms are private ± Accessible only within the Body and not allowed for public ± Private member 136 © 2009 Wipro Ltd ² Internal & Restricted .

12 RETURN v_sal. 19* END bonus_pack. SQL> / Package body created. Private function 137 © 2009 Wipro Ltd ² Internal & Restricted . 4 FUNCTION retrieve_sal(p_eno NUMBER) 5 RETURN NUMBER 6 IS 7 BEGIN 8 SELECT sal 9 INTO v_sal 10 FROM emp 11 WHERE empno = p_eno.2. 14 PROCEDURE RETRIEVE_BONUS(p_eno NUMBER) 15 IS 16 BEGIN 17 v_bonus:=retrieve_sal(p_eno)*0. 13 END. 18 END retrieve_bonus.Private Member -Example 1 CREATE OR REPLACE PACKAGE body bonus_pack 2 IS 3 v_sal NUMBER.

Session state -Package variables ‡ Used as global variable ± Accessible from anywhere ‡ Initialization is done once per session ± Data are maintained throughout the session ‡ Scope of the value remains for the current session. ‡ Value accessed by one user can·t be shared/disturbed by other user 138 © 2009 Wipro Ltd ² Internal & Restricted .

Removing the Packages ‡ To drop the package body ± DROP PACKAGE BODY package_name ‡ To drop the package header ± DROP PACKAGE package_name ‡ After removing the package body for the existing header new body can be created ‡ But after deleting header the body will be no longer valid 139 © 2009 Wipro Ltd ² Internal & Restricted .

p_doj DATE) RETURN NUMBER. PROCEDURE print_data(p-job VARCHAR2) PROCEDURE print_data(p_ename VARCHAR2.p-job VARCHAR2) 140 © 2009 Wipro Ltd ² Internal & Restricted .Overloading ‡ Overloading is the concept of using the same name ‡ Overloading stored sub programs are not allowed whereas possible with packaged sub programs FUNCTION compute_salary(p_eno NUMBER) RETURN NUMBER. FUNCTION compute_salary(p_ename VARCHAR2.

END dept_pack.One time only Procedures Example CREATE OR REPLACE PACKAGE dept_pack IS v_dept_cnt NUMBER:=0. 141 © 2009 Wipro Ltd ² Internal & Restricted . PROCEDURE print_details.

of Records '|| v_dept_cnt).One time only Procedures CREATE OR REPLACE PACKAGE BODY dept_pack IS PROCEDURE print_details IS BEGIN DBMS_OUTPUT. Gets executed once when BEGIN loaded for the first time SELECT COUNT(*) INTO v_dept_cnt FROM DEPT. 142 © 2009 Wipro Ltd ² Internal & Restricted .PUT_LINE ( No. END. END.

'NY'). COUNT(*) ---------5 SQL> EXECUTE dept_pack.'Operations'.print_details No.Example SQL> EXECUTE dept_pack. SQL> SELECT COUNT(*) FROM DEPT. of Records4 SQL> INSERT INTO DEPT VALUES(50. of Records4 143 © 2009 Wipro Ltd ² Internal & Restricted .print_details No.

WNPS .WNPS to restrict function updating database and package variables ± RNDS. RNPS) ± WNDS.RNPS to restrict function reading database and package variables 144 © 2009 Wipro Ltd ² Internal & Restricted .Compiler directives on functions ‡ Pragma is the compiler directive ‡ Helps to insist purity level for the packaged functions ‡ PRAGMA RESTRICT_REFERENCES (function_name. RNDS.WNDS .

Built in packages ‡ ‡ ‡ ‡ ‡ ‡ DBMS_OUTPUT UTL_FILE DBMS_ALERT DBMS_LOCK DBMS_JOB DBMS_SESSION 145 © 2009 Wipro Ltd ² Internal & Restricted .

Exceptions 146 © 2009 Wipro Ltd ² Internal & Restricted .10.

Exception ‡ Any abnormal condition to the normal execution of PL/SQL Block is an Exception ‡ Way of handling Run time errors 147 © 2009 Wipro Ltd ² Internal & Restricted .Introduction .

Exception Block ‡ Syntax «. EXCEPTION WHEN name_of_exception1 THEN handler ² PL/SQL statements WHEN name_of_exception2 THEN handler END. 148 © 2009 Wipro Ltd ² Internal & Restricted .

149 © 2009 Wipro Ltd ² Internal & Restricted .Exception ‡ Any PL/SQL block can have its own exception block ‡ Exception block contains ± Name of the exception thrown ± HANDLER explains the actions to be performed when error occur ‡ Exception is not going to solve the current error condition.

Need for Exception ‡ When Error occurs ± Abruptly stop executing the current block ± ROLLBACK ‡ If Exception is Handled ± Stops the current process ± Saves the process done so far ± Transfer the control to exception handler ± Smooth Transition from error condition to end of program 150 © 2009 Wipro Ltd ² Internal & Restricted .

END. ‡ Will the new dept 55 get inserted? 151 © 2009 Wipro Ltd ² Internal & Restricted .EMPNO%TYPE. SELECT empno INTO v_empno FROM emp WHERE ename= ABC .PUT_LINE (v_empno). NY ). DBMS_OUTPUT.Demonstrate ‡ Observe and execute the following code DECLARE v_empno EMP. Operations . BEGIN INSERT INTO DEPT VALUES(55.

handler No need to DECLARE and INVOKE ‡ ‡ No_data_found Too_many_row s ‡ ‡ Invalid_number Zero_divide ‡ ‡ Cursor_already_open Dup_val_on_index 152 © 2009 Wipro Ltd ² Internal & Restricted .Pre-defined Exceptions ‡ ‡ ‡ ‡ PL/SQL defined exceptions Sensed and mapped to the corresponding exception handler automatically User has to DEFINE it .

PUT_LINE ( no employee found). END.PUT_LINE (v_empno). SELECT empno INTO v_empno FROM emp WHERE ename= ABC .Example DECLARE v_empno EMP. NY ). 153 © 2009 Wipro Ltd ² Internal & Restricted Will this get inserted in database? Will this get printed? . EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.EMPNO%TYPE. DBMS_OUTPUT. Operations . BEGIN INSERT INTO DEPT VALUES(55.

. If specific handler is not found OTHERS handler is executed ‡ Use SQLCODE & SQLERRM to print the error code and message 154 © 2009 Wipro Ltd ² Internal & Restricted .PUT_LINE (SQLERRM).When Others ‡ Unhandled exception can be trapped in the OTHERS category Example . END. WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE (SQLCODE).. handler is searched. ‡ When PL/SQL senses exception. DBMS_OUTPUT. EXCEPTION .

User defined Exception ‡ Designed by user as error ‡ Kind of Logical error ± Manager getting commission > 500 is invalid ‡ User has to ± DECLARE ± DEFINE & ± INVOKE 155 © 2009 Wipro Ltd ² Internal & Restricted .

DECLARE ± Exception_name EXCEPTION. ‡ In Exception Block ² DEFINE ± WHEN Exception_name THEN Handler ‡ In Execution Block ² INVOKE ± RAISE Exception_name 156 © 2009 Wipro Ltd ² Internal & Restricted .User defined Exception ‡ In Declaration Block .

v_job EMP. 157 © 2009 Wipro Ltd ² Internal & Restricted . EXCEPTION WHEN invalid_commisn THEN . BEGIN IF (v_job= MANAGER AND v_comm>500) THEN RAISE invalid_commisn. invalid_commisn EXCEPTION.. END.Example DECLARE v_comm EMP.job%TYPE. .comm%TYPE. END IF.

Non-Predefined Exception ‡ ‡ ‡ ‡ Name is not defined by PL/SQL PL/SQL identifies such exceptions as errors with error code User has to assign name for it. User need to ± DECLARE and DEFINE it ± Implicit INVOKING is done after user assigns name ± Use pragma EXEPTION_INIT to associate user defined exception name with the error code 158 © 2009 Wipro Ltd ² Internal & Restricted . map a exception name for the error.

INSERT INTO DEPT VALUES(10.Example DECLARE unique_constraint EXCEPTION.PUT_LINE ('caught exception').'Finance'..  PRAGMA EXCEPTION_INIT ± Associates name ´unique constraintµ with the error code 0001  Exception got declared. PRAGMA EXCEPTION_INIT(unique_constraint.. handled and not invoked 159 © 2009 Wipro Ltd ² Internal & Restricted .'CA'). BEGIN . . EXCEPTION WHEN unique_constraint THEN DBMS_OUTPUT. END.-0001).

RAISE_APPLICATION_ERROR(-20010.'Check Constraint Violation').RAISE APPLICATION ERROR ‡ Used to print user defined error message . ERROR at line 1: ORA-20010: Check Constraint Violation 160 © 2009 Wipro Ltd ² Internal & Restricted .

PUT_LINE (µno employee found). END.¶NY¶). DBMS_OUTPUT.¶Operations¶. BEGIN INSERT INTO DEPT VALUES(55.Propagation -Exception DECLARE v_empno EMP. SELECT empno INTO v_empno FROM emp WHERE ename=µABC¶.EMPNO%TYPE. EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT. 161 © 2009 Wipro Ltd ² Internal & Restricted .PUT_LINE (v_empno).

«..Propagation-Nested Blocks DECLARE « BEGIN «.... --Exception handler for outer block --Inner block ends 162 © 2009 Wipro Ltd ² Internal & Restricted . EXCEPTION --Exception handler for inner block --Inner block begins When no_data_found Exception is raised WHEN NO_DATA_FOUND THEN «. «« END. BEGIN «. END «. EXCEPTION ««.

.. END «. BEGIN «. --Exception handler for outer block --Inner block ends 163 © 2009 Wipro Ltd ² Internal & Restricted .. «« END. EXCEPTION --Exception handler for inner block --Inner block begins When too_many_rows Exception is raised WHEN NO_DATA_FOUND THEN «.Propagation-Nested Blocks DECLARE « BEGIN «.. «. EXCEPTION ««.

«.Propagation-Nested Blocks DECLARE « BEGIN «.. BEGIN «... 164 © 2009 Wipro Ltd ² Internal & Restricted . EXCEPTION --Exception handler for inner block --Inner block begins When no_data_found Exception is raised in inner block and handled in both blocks WHEN NO_DATA_FOUND THEN «. EXCEPTION --Exception handler for outer block --Inner block ends WHEN NO_DATA_FOUND THEN «« END. END «..

. EXCEPTION --Exception handler for inner block --Inner block begins When no_data_found Exception is raised in inner block and handled in both blocks WHEN NO_DATA_FOUND THEN RAISE. BEGIN «...RE-RAISE DECLARE « BEGIN «. «. 165 © 2009 Wipro Ltd ² Internal & Restricted . EXCEPTION --Exception handler for outer block --Inner block ends WHEN NO_DATA_FOUND THEN «« END. END «.

11. Triggers 166 © 2009 Wipro Ltd ² Internal & Restricted .

‡ Treats user·s request and trigger action as one transaction 167 © 2009 Wipro Ltd ² Internal & Restricted .trigger is the solution for it ‡ Gets fired automatically/implicitly.What a trigger is? ‡ PL/SQL block consists of actions to be continued implicitly for the current event ‡ Chain of action is to be performed whenever insertion happens .

Need for a Trigger ‡ Owner of the database objects can decide upon the chain of action to happen ‡ Along with the specified request trigger will also get executed 168 © 2009 Wipro Ltd ² Internal & Restricted .

Components of Triggers ‡ Trigger timing ± When to fire trigger after the request or before the current request ‡ Triggering event ± For what event this trigger is to be fired ± Is it insert/update/delete ‡ Table name ± Name of the table for which trigger is 169 © 2009 Wipro Ltd ² Internal & Restricted .

Components of Triggers ‡ Trigger type ± Two categories of trigger exist ²decides upon how trigger gets fired ± Statement level ² once per request ± Row level ² for each and every row got affected trigger is executed ‡ When clause ± Prepares selected rows for trigger action ± Allowed only for Row level trigger ‡ Trigger body ± Explains what to be done in the trigger end 170 © 2009 Wipro Ltd ² Internal & Restricted .

Database Triggers CREATE [OR REPLACE] TRIGGER trigger_name BEFORE/AFTER INSERT [OR DELETE OR UPDATE [OF COLUMNS] ] ON table_name PL/SQL BLOCK. 171 © 2009 Wipro Ltd ² Internal & Restricted .

Database Triggers-Example CREATE TRIGGER salhike_emp AFTER UPDATE OF SAL ON EMP BEGIN INSERT INTO LOG_HIKE(HIKEDATE. 172 © 2009 Wipro Ltd ² Internal & Restricted . END.USER).USER_NAME) VALUES(SYSDATE.

Database Triggers-Example ‡ How many times the previous trigger get executed if all the 14 employees are eligible for salary hike? ‡ Will this trigger help us to store details of the salary hike. like ± name of the person eligible for hike. ± old salary and ± the revised salary? 173 © 2009 Wipro Ltd ² Internal & Restricted .

Statement level & Row level Trigger ‡ Decides upon how trigger gets fired ± Statement level ± once per request ± Row level ± for each and every row got affected trigger body is executed 174 © 2009 Wipro Ltd ² Internal & Restricted .

175 © 2009 Wipro Ltd ² Internal & Restricted .Row level Triggers CREATE [OR REPLACE] TRIGGER BEFORE/AFTER INSERT [OR UPDATE OR DELETE] ON table_name [REFERENCING OLD AS old | NEW AS new] FOR EACH ROW [WHEN condition] PL/SQL Block.

Row level Triggers CREATE TRIGGER log_hike_employee AFTER UPDATE ON EMP FOR EACH ROW BEGIN INSERT INTO LOG_HIKE_EMP(EMPNO.EMPNO.SAL.PREVSAL.CURSAL) VALUES(:OLD.:NEW.:OLD. END. 176 © 2009 Wipro Ltd ² Internal & Restricted .SAL).

:CURSAL.SAL). 177 © 2009 Wipro Ltd ² Internal & Restricted .JOB='CLERK') BEGIN INSERT INTO HIK_EMP_HISTRY(EMPNO.PREVSAL. END.:PREVSAL.EMPNO.SAL.Row level Triggers CREATE OR REPLACE TRIGGER TR1 AFTER UPDATE ON EMP REFERENCING OLD AS PREVSAL NEW AS CURSAL FOR EACH ROW WHEN (PREVSAL.CURSAL) VALUES(:PREVSAL.

Requirement . 178 © 2009 Wipro Ltd ² Internal & Restricted .empno.Demo ‡ Whenever salary hike is announced comm is revised by 10%.1 where empno=:old. ‡ Will this trigger solve the problem? create or replace trigger sal_hike_comm before update of sal on emp for each row begin update emp set comm=comm*1. end.

Mutation Errors in Triggers ‡ When the data referred in the user query is used in its trigger mutation error occurs ‡ Example In the trigger written for update event if we try to delete the rows locked by update command mutation occurs 179 © 2009 Wipro Ltd ² Internal & Restricted .

PREVSAL.SAL). 180 © 2009 Wipro Ltd ² Internal & Restricted .Row level Triggers CREATE TRIGGER sal_hike_rowlevel BEFORE Will this work for After trigger? UPDATE ON EMP FOR EACH ROW BEGIN INSERT INTO LOG_HIKE_EMP(EMPNO.:NEW.CURSAL) VALUES(:OLD. :NEW. END.EMPNO.SAL.:OLD.COMM:=500.

Instead of Triggers ‡ Triggers are written for Tables and not for views ‡ Instead of triggers are applicable only for views and not for tables ‡ Get fired for any DML operations requested over the view ± Instead of updating view. modification can be done somewhere else ± Can be defined in the trigger body 181 © 2009 Wipro Ltd ² Internal & Restricted .

‡ Where event is the DML event which is requested towards this view_name 182 © 2009 Wipro Ltd ² Internal & Restricted .Syntax CREATE OR REPLACE TRIGGER trigger_name INSTEAD OF event ON view_name PL/SQL Block.

SYSDATE).DTE) VALUES(USER. END. / 183 © 2009 Wipro Ltd ² Internal & Restricted .Instead of trigger CREATE OR REPLACE TRIGGER TRG1 INSTEAD OF INSERT ON CLER_VIEW BEGIN INSERT INTO LOG(USER_NAME.

System Triggers ‡ Considered during the following event ± DDL ‡ CREATE. ALTER and DROP ± Database events ‡ server startup/shutdown ‡ user logon/logoff 184 © 2009 Wipro Ltd ² Internal & Restricted .

][SCHEMA] [WHEN CLUASE] [trigger_body] 185 © 2009 Wipro Ltd ² Internal & Restricted .Syntax CREATE OR REPLACE TRIGGER Trigger_name [BEFORE |AFTER] [ddl event list| database_event list] [ON| DATABASE| [schema.

186 © 2009 Wipro Ltd ² Internal & Restricted .'dy') not in ('sun'.'sat')) Begin insert into log values(user. end. schema WHEN (to_char(SYSDATE.Example CREATE TRIGGER scott_login_trigg AFTER LOGON ON SCOTT.sysdate).

187 © 2009 Wipro Ltd ² Internal & Restricted .sysdate). end.Example-DDL triggers CREATE TRIGGER scott_ddl_trigg AFTER CREATE ON schema Begin insert into log values (user.

Restrictions in Triggers ‡ TCL commands are not allowed ± Treats user·s request and trigger action as one transaction ± Part of the transactions can be neither committed nor rollback ‡ Avoid data/function Mutation 188 © 2009 Wipro Ltd ² Internal & Restricted .

‡ ALTER TRIGGER trigger_name ENABLE|DISABLE ‡ ALTER TABLE table_name ENABLE/DISABLE ALL TRIGGERS 189 © 2009 Wipro Ltd ² Internal & Restricted .Removing Triggers ‡ DROP TRIGGER trigger_name ‡ DROP TRIGGER emp_insert_trigg.

Data Dictionaries -Triggers ‡ ‡ ‡ ‡ DESC USER_OBJECTS DESC USER_SOURCE DESC USER_ERRORS DESC USER_TRIGGERS 190 © 2009 Wipro Ltd ² Internal & Restricted .

Dependencies among PL/SQL Constructs 191 © 2009 Wipro Ltd ² Internal & Restricted .12.

procedure is dependant on table and table is referenced by procedure ± Procedure is dependant object ²which depends on table ± Table is referenced object ² getting referred by other objects If referenced object is modified dependant object is affected ‡ 192 © 2009 Wipro Ltd ² Internal & Restricted .Dependant and Referenced Objects ‡ When a Procedure body refers a table.

Dependencies ‡ Assume ± stored function FUN1 invokes PROC1. ± PROC1 is getting changed NOW ± Makes FUN1 outdated and change its status to INVALID ± ALTER FUNCTION FUN1 COMPILE Similarly ± ALTER FUNCTION function_name COMPILE ± ALTER PROCEDURE procedure_name COMPILE ± ALTER PACKAGE package_name COMPILE PACKAGE ± ALTER PACKAGE package_name COMPILE BODY ± ALTER TRIGGER trigger_name [ENABLE|DISABLE|COMPILE[DEBUG] ‡ 193 © 2009 Wipro Ltd ² Internal & Restricted .

package ‡ Package body is dependant on header ‡ Changes in body doesn·t affect specification ‡ But changes in header affects the body needs to be reconstructed.Dependencies . 194 © 2009 Wipro Ltd ² Internal & Restricted .

Direct and Remote Dependencies ‡ Direct dependencies exist if dependant objects are in the same server ‡ In case of dependant objects scattered to different servers remote dependencies exists 195 © 2009 Wipro Ltd ² Internal & Restricted .

Data Dictionary views ‡ ‡ ‡ ‡ ‡ DESC USER_OBJECTS DESC USER_SOURCE DESC USER_ERRORS DESC USER_TRIGGERS DESC USER_DEPENDENCIES 196 © 2009 Wipro Ltd ² Internal & Restricted .

Thank You © 2009 Wipro Ltd ² Internal & Restricted .