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.

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

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 .

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

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

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

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 .

‡ Compatibility ± Supports all the data types available in Oracle/SQL. ‡ 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 .Advantages-Contd.

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 .

Stored Procedures ‡ Named PL/SQL Block ‡ Stored as Database Objects like Tables. Indexes. 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 . Sequences.Views.

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 .

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

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

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 .

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

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

Operators-Assignment ‡ := is the assignment operator in PL/SQL ‡ Example A:=10. ± 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 . ‡ Data :=null. ± Assign 10 to the variable A.

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

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

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

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

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 .

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

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

end.Example ² 2 DECLARE v_name varchar2(10). ‡ 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 .

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

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

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

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 .

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

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 .

THEN«.THEN«.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«.ELSIF«.ELSE«.END IF ± IF«.END IF 53 © 2009 Wipro Ltd ² Internal & Restricted .

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

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

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

ELSE statements. WHEN condition THEN statements. END CASE.CASE ‡ To group multiple conditions ‡ Syntax is CASE WHEN condition THEN 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 «.EXIT LOOP «. «.. 60 © 2009 Wipro Ltd ² Internal & Restricted . EXIT..

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

WHILE LOOP WHILE (condition) LOOP « END LOOP.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 .

final_value 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 .

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.

Different Modes of Parameters (IN. 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 . OUT.

literal or an expression ± Should be an initialized variable 71 © 2009 Wipro Ltd ² Internal & Restricted .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.

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 .

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

Use PRINT command to know the ouptut SQL:>PRINT NAME SQL:>PRINT JOB 77 © 2009 Wipro Ltd ² Internal & Restricted .:job).:name.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.

v_job).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). 78 © 2009 Wipro Ltd ² Internal & Restricted .v_name. Begin retrieve(7788. v_job varchar2(15). End.

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

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

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

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

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

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

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

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. CHAR. 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.

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

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

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

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

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

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 .Record Type ‡ ‡ ‡ ‡ User defined.

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

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

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 . PRIOR ± DELETE(N) 102 © 2009 Wipro Ltd ² Internal & Restricted . LAST ± NEXT .

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 .

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

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 .

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 .Named and used by programmer ± Controlled by user 106 © 2009 Wipro Ltd ² Internal & Restricted .

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 .

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

sal from emp. 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.

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

± 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.

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

113 © 2009 Wipro Ltd ² Internal & Restricted .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.

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

END 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 .Cursor with FOR loop ‡ For record_variable IN cursor_name LOOP «.

116 © 2009 Wipro Ltd ² Internal & Restricted .

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

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

End. END LOOP..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 . 119 © 2009 Wipro Ltd ² Internal & Restricted .

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

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 [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..FOR UPDATE ‡ Syntax is Select «.

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

current_rec my_cur%rowtype. FETCH my_cur INTO current_rec. 124 © 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. Begin .

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

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

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 .

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. 129 © 2009 Wipro Ltd ² Internal & Restricted .

· ‡ 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 ¶.

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

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

END [package_name]. 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. 133 © 2009 Wipro Ltd ² Internal & Restricted . packaged sub program definition.

2+v_bonus. 13* END bonus_pack. 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. 11 v_bonus:=v_sal*0. 12 END retrieve_bonus. SQL> / Package body created. 134 © 2009 Wipro Ltd ² Internal & Restricted . 6 BEGIN 7 SELECT sal.

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

subprograms are private ± Accessible only within the Body and not allowed for public ± Private member 136 © 2009 Wipro Ltd ² Internal & Restricted .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.

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. 14 PROCEDURE RETRIEVE_BONUS(p_eno NUMBER) 15 IS 16 BEGIN 17 v_bonus:=retrieve_sal(p_eno)*0. 13 END. 12 RETURN v_sal. SQL> / Package body created.Private Member -Example 1 CREATE OR REPLACE PACKAGE body bonus_pack 2 IS 3 v_sal NUMBER. 18 END retrieve_bonus. 19* END bonus_pack.2. Private function 137 © 2009 Wipro Ltd ² Internal & Restricted .

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 .

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.p_doj DATE) RETURN NUMBER. FUNCTION compute_salary(p_ename VARCHAR2. PROCEDURE print_data(p-job VARCHAR2) PROCEDURE print_data(p_ename VARCHAR2.p-job VARCHAR2) 140 © 2009 Wipro Ltd ² Internal & Restricted .

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

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

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

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

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 WHEN name_of_exception1 THEN handler ² PL/SQL statements WHEN name_of_exception2 THEN handler END.Exception Block ‡ Syntax «. 148 © 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. 149 © 2009 Wipro Ltd ² Internal & Restricted .

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 .

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

Pre-defined Exceptions ‡ ‡ ‡ ‡ PL/SQL defined exceptions Sensed and mapped to the corresponding exception handler automatically User has to DEFINE it .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 .

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

When Others ‡ Unhandled exception can be trapped in the OTHERS category Example . DBMS_OUTPUT. END. ‡ When PL/SQL senses exception.PUT_LINE (SQLCODE). WHEN OTHERS THEN DBMS_OUTPUT... EXCEPTION . 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). handler is searched.

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 .

User defined Exception ‡ In Declaration Block .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 .

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

map a exception name for the error.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 .

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

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

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

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

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

Propagation-Nested Blocks DECLARE « BEGIN «. 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 «. BEGIN «... END «. EXCEPTION --Exception handler for outer block --Inner block ends WHEN NO_DATA_FOUND THEN «« END. «... 164 © 2009 Wipro Ltd ² Internal & Restricted .

END «...RE-RAISE DECLARE « BEGIN «. 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 «. 165 © 2009 Wipro Ltd ² Internal & Restricted . «. EXCEPTION --Exception handler for outer block --Inner block ends WHEN NO_DATA_FOUND THEN «« 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 .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 .trigger is the solution for it ‡ Gets fired automatically/implicitly.

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 .

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

like ± name of the person eligible for hike.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. ± 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.

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

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

178 © 2009 Wipro Ltd ² Internal & Restricted .Requirement . ‡ 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.1 where empno=:old.Demo ‡ Whenever salary hike is announced comm is revised by 10%.empno.

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 .

:OLD.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. 180 © 2009 Wipro Ltd ² Internal & Restricted .CURSAL) VALUES(:OLD. :NEW. END.PREVSAL.COMM:=500.SAL).SAL.:NEW.EMPNO.

modification can be done somewhere else ± Can be defined in the trigger body 181 © 2009 Wipro Ltd ² Internal & Restricted .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.

‡ 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). END.Instead of trigger CREATE OR REPLACE TRIGGER TRG1 INSTEAD OF INSERT ON CLER_VIEW BEGIN INSERT INTO LOG(USER_NAME. / 183 © 2009 Wipro Ltd ² Internal & Restricted .DTE) VALUES(USER.

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

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

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

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

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.

± 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 .Dependencies ‡ Assume ± stored function FUN1 invokes PROC1.

194 © 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 .

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 .

Sign up to vote on this title
UsefulNot useful