UNIT II PL / SQL AND TRIGGERS

Similar documents
PL/SQL Block structure

PL/SQL is a combination of SQL along with the procedural features of programming languages.

ADVANTAGES. Via PL/SQL, all sorts of calculations can be done quickly and efficiently without use of Oracle engine.

Sisteme Informatice şi Standarde Deschise (SISD) Curs 7 Standarde pentru programarea bazelor de date (1)

Question: Which statement would you use to invoke a stored procedure in isql*plus?

PL/SQL. Exception. When the PL/SQL engine cannot execute the PLSQL block it raise an error. Every Oracle error has an error number

Database Programming with PL/SQL

2 PL/SQL - fundamentals Variables and Constants Operators SQL in PL/SQL Control structures... 7

PLSQL 9i Index. Section Title Page

Procedural Language Structured Query Language (PL/SQL)

ORACLE: PL/SQL Programming

Introduction to Computer Science and Business

PL / SQL Basics. Chapter 3

Programming in Oracle with PL/SQL. Procedural Language Extension to SQL

Oracle Database 11g: SQL and PL/SQL Fundamentals

Section I : Section II : Question 1. Question 2. Question 3.

Question Bank PL/SQL Fundamentals-I

RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND ANSWERS

UNIT-IV (Relational Database Language, PL/SQL)

Oracle Database 11g: Program with PL/SQL Release 2

Oracle PLSQL. Course Summary. Duration. Objectives

When a database trigger routine does not have to take place before the triggering event, which timing should you assign to the trigger?

Contents I Introduction 1 Introduction to PL/SQL iii

Oracle Database: Program with PL/SQL

Oracle Database 11g: Program with PL/SQL

Oracle Class VI. Exception Block Cursors For Loops

2. Programming written ( main theme is to test our data structure knowledge, proficiency

Oracle Database: SQL and PL/SQL Fundamentals NEW

ORACLE Job Placement Paper. Paper Type : General - other

Oracle PLSQL Training Syllabus

PLSQL Interview Questions :

Topics Fundamentals of PL/SQL, Integration with PROIV SuperLayer and use within Glovia

Oracle Database: SQL and PL/SQL Fundamentals Ed 2

Slides by: Ms. Shree Jaswal

Lesson B Objectives IF/THEN. Chapter 4B: More Advanced PL/SQL Programming

Oracle Class VII More on Exception Sequence Triggers RowID & Rownum Views

Oracle Database: Program with PL/SQL

Oracle Database: Program with PL/SQL Ed 2

Oracle Database 12c: Program with PL/SQL Duration: 5 Days Method: Instructor-Led

Table of Contents. Oracle SQL PL/SQL Training Courses

1Z0-144 Q&As Oracle Database 11g: Program with PL/ SQL

Oracle Database 12c R2: Program with PL/SQL Ed 2 Duration: 5 Days

Conditionally control code flow (loops, control structures). Create stored procedures and functions.

PL/SQL-TYCS. The 'Hello World' Example

Part 18: Application Programming II (Stored Procedures,Triggers)

The PL/SQL Engine: PL/SQL. A PL/SQL Block: Declaration Section. Execution Section. Declaration Section 3/24/2014

Oracle. PL/SQL Procedural Language

OVERVIEW OF THE TYPES OF PL/SQL BLOCKS:

to use this Student Guide

IZ0-144Oracle 11g PL/SQL Certification (OCA) training

Vendor: Oracle. Exam Code: 1Z Exam Name: Oracle Database 11g: Program with PL/ SQL. Version: Demo

Oracle PL/SQL - 12c & 11g [Basic PL/SQL & Advanced PL/SQL]

Oracle Database: Introduction to SQL/PLSQL Accelerated

Oracle12c Release 1 PL/SQL (3 Days)

Banner Oracle PL/SQL and Database Objects Training Workbook

Introduction to SQL/PLSQL Accelerated Ed 2

1Z Oracle Database 11g - Program with PL/SQL Exam Summary Syllabus Questions

Oracle - Oracle Database: Program with PL/SQL Ed 2

SQL IN PL/SQL. In this chapter, you will learn about: Making Use of DML in PL/SQL Page 68 Making Use of Savepoint Page 77

5. Single-row function

Oracle PL SQL Training & Certification

数据库系统概论讲义, 第 8 章编程 SQL,2015,3

Private Institute of Aga NETWORK DATABASE LECTURER NIYAZ M. SALIH

Index. Boolean expression, , Business rules enforcement. see Declarative constraints table with Oracle constraints and,

ORACLE DATABASE 12C INTRODUCTION

M.SC(IT) I YEAR( ) CORE: ADVANCED DBMS-163B Semester : I Multiple Choice Questions

RNDr. Michal Kopecký, Ph.D. Department of Software Engineering, Faculty of Mathematics and Physics, Charles University in Prague

Oracle PLSQL Study Material ORACLE & PL/SQL STUDY MATERIAL

Oracle 1Z Oracle9i: Program with PL/SQL. Download Full Version :

Overview of PL/SQL. About PL/SQL. PL/SQL Environment. Benefits of PL/SQL. Integration

Oracle Database 11g & PL/SQL

Full file at

ORACLE TRAINING. ORACLE Training Course syllabus ORACLE SQL ORACLE PLSQL. Oracle SQL Training Syllabus

Appendix A Practices and Solutions

Oracle Exam 1z0-144 Oracle Database 11g: Program with PL/SQL Version: 8.5 [ Total Questions: 103 ]

Oracle Database 11g: PL/SQL Fundamentals

Oracle Internal & Oracle Academy

Lecture 08. Spring 2018 Borough of Manhattan Community College

Meet MariaDB Vicențiu Ciorbaru Software MariaDB Foundation * * 2017 MariaDB Foundation

PROCEDURAL DATABASE PROGRAMMING ( PL/SQL AND T-SQL)

"Charting the Course... Oracle 18c PL/SQL (5 Day) Course Summary

Actual4Test. Actual4test - actual test exam dumps-pass for IT exams

based mainly on course notes by Will Hyslop (UNB-F) and course notes by Jeff Ullman and others (Stanford)

Oracle Database: SQL and PL/SQL Fundamentals

Database Programming with PL/SQL

Index. Data Definition Language (DDL), 440 author_publications table, 4 5 constraints creation, 9 columns, 6 447

Introduction p. 1 The Logical and Physical View of Tables p. 1 Database Types p. 4 NULLs p. 6 DDL and DML Statements p. 7 Column and Table Constraint

UNIT 3

Full file at

Oracle Developer Track Course Contents. Mr. Sandeep M Shinde. Oracle Application Techno-Functional Consultant

Database Programming with PL/SQL

Business Analytics. SQL PL SQL [Oracle 10 g] P r i n c e S e t h i w w w. x l m a c r o. w e b s. c o m

Oracle Database 10g: PL/SQL Fundamentals. Oracle Internal & Oracle Academy Use Only. Volume I Student Guide. D17112GC30 Edition 3.0 April 2009 D59413

Constraints. Primary Key Foreign Key General table constraints Domain constraints Assertions Triggers. John Edgar 2

Persistent Stored Modules (Stored Procedures) : PSM

BASIC ELEMENTS OF A COMPUTER PROGRAM

SQL was defined in the late 60 s, early 70 s by the System R research group at IBM.

Oracle PL/SQL. DUMmIES. by Michael Rosenblum and Dr. Paul Dorsey FOR

Database Programming with PL/SQL

Question No : 1 Which statement is true about triggers on data definition language (DDL) statements?

Transcription:

UNIT II PL / SQL AND 1 TRIGGERS

TOPIC TO BE COVERED.. 2.1 Basics of PL / SQL 2.2 Datatypes 2.3 Advantages 2.4 Control Structures : Conditional, Iterative, Sequential 2.5 Exceptions: Predefined Exceptions,User defined exceptions 2.6 Cursors: Static (Implicit & Explicit), Dynamic 2.7 Procedures & Functions 2

TOPIC TO BE COVERED.. 2.8 Packages : Package specification, Package body, Advantages of package 2.9 Fundamentals of Database Triggers 2.10 Creating Triggers 2.11 Types of Triggers : Before, after for each row, for each statement 3

2.1 BASICS OF PL / SQL PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database language. With PL/SQL, you can use SQL statements to manipulate ORACLE data and the flow of control statements to process the data. Moreover, you can declare constants and variables, define subprograms (procedures and functions), and trap runtime errors. Thus, PL/SQL combines the data manipulating power of SQL with the data processing power of procedural languages. 4

2.1 BASICS OF PL / SQL Many Oracle applications are built using clientserver architecture. The Oracle database resides on the server. The program that makes requests against this database resides on the client machine. This program can be written in C, Java, or PL/SQL. While PL/SQL is just like any other programming language, it has syntax and rules that determine how programming statements work together. PL/SQL is a part of the Oracle RDBMS, and it can reside in two environments, the client and the server. 5

2.1 BASICS OF PL / SQL As a result, it is very easy to move PL/SQL modules between server-side and client-side applications. When the PL/SQL engine is located on the server, the whole PL/SQL block is passed to the PL/SQL engine on the Oracle server. The PL/SQL engine processes the block according to the Figure 2.1. 6

THE PL/SQL ENGINE PROCESSES 7

THE PL/SQL ENGINE PROCESSES When the PL/SQL engine is located on the client, as it is in the Oracle Developer Tools, the PL/SQL processing is done on the client side. All SQL statements that are embedded within the PL/SQL block are sent to the Oracle server for further processing. When PL/SQL block contains no SQL statement, the entire block is executed on the client side. 8

DIFFERENCE BETWEEN PL/SQL AND SQL SQL PL/SQL SQL is a Structured Query Language. SQL is executed one statement at a time. SQL is used to write queries, DDL and DML statemen ts. SQL does not support Exception Handling. SQL does not support variable declaration. PL-SQL is a procedural Structured Query Language. PL/SQL is executed as a block of code. PL/SQL is used to write program blocks, functions, procedures triggers, and packages. PL/SQL support Exception Handling. SQL does not support variable declaration. 9

PL/SQL BLOCKS PL/SQL blocks can be divided into two groups: Named and Anonymous. Named blocks are used when creating subroutines. These subroutines are procedures, functions, and packages. The subroutines can be stored in the database and referenced by their names later on. In addition, subroutines can be defined within the anonymous PL/SQL block. Anonymous PL/SQL blocks do not have names. As a result, they cannot be stored in the database and referenced later. 10

PL/SQL BLOCKS PL/SQL blocks contain three sections Declare section Executable section and Exception-handling section. The executable section is the only mandatory section of the block. Both the declaration and exception-handling sections are optional. 11

PL/SQL BLOCK STRUCTURE DECLARE.Optional <Declaration Section> BEGIN.Mandatory <Executable commands> EXCEPTION.Optional <Exception Handling> END;.Mandatory 12

DECLARATION SECTION The declaration section is the first section of the PL/SQL block. It contains definitions of PL/SQL identifiers such as variables, constants, cursors and so on. Example: DECLARE v_first_name VARCHAR2(35) ; v_last_name VARCHAR2(35) ; v_counter NUMBER := 0 ; 13

EXECUTABLE SECTION The executable section is the next section of the PL/SQL block. This section contains executable statements that allow you to manipulate the variables that have been declared in the declaration section. BEGIN SELECT first_name, last_name INTO v_first_name, v_last_name FROM student WHERE student_id = 123 ; DBMS_OUTPUT.PUT_LINE ( Student name : v_first_name v_last_name); END; 14

EXCEPTION-HANDLING SECTION The exception-handling section is the last section of the PL/SQL block. This section contains statements that are executed when a runtime error occurs within a block. Runtime errors occur while the program is running and cannot be detected by the PL/SQL compiler. Example: EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE ( There is no student with student id 123 ); END; 15

HOW PL/SQL GETS EXECUTED Every time an anonymous block is executed, the code is sent to the PL/SQL engine on the server where it is compiled. The named PL/SQL block is compiled only at the time of its creation, or if it has been changed. The compilation process includes syntax checking, binding and p-code generation. Syntax checking involves checking PL/SQL code for syntax or compilation errors. Once the programmer corrects syntax errors, the compiler can assign a storage address to program variables that are used to hold data for Oracle. This process is called Binding. 16

HOW PL/SQL GETS EXECUTED After binding, p-code is generated for the PL/SQL block. P-code is a list of instructions to the PL/SQL engine. For named blocks, p-code is stored in the database, and it is used the next time the program is executed. Once the process of compilation has completed successfully, the status for a named PL/SQL block is set to VALID, and also stored in the database. If the compilation process was not successful, the status for a named PL/SQL block is set to INVALID. 17

PL/SQL IN SQL*PLUS SQL*Plus is an interactive tool that allows you to type SQL or PL/SQL statements at the command prompt. These statements are then sent to the database. Once they are processed, the results are sent back from the database and displayed on the screen. There are some differences between entering SQL and PL/SQL statements. 18

SQL EXAMPLE SELECT first_name, last_name FROM student; The semicolon terminates this SELECT statement. Therefore, as soon as you type semicolon and hit the ENTER key, the result set is displayed to you. 19

PL/SQL EXAMPLE DECLARE BEGIN v_first_name VARCHAR2(35); v_last_name VARCHAR2(35); SELECT first_name, last_name INTO v_first_name, v_last_name FROM student WHERE student_id = 123; DBMS_OUTPUT.PUT_LINE ('Student name: ' v_first_name ' ' v_last_name); 20

PL/SQL EXAMPLE EXCEPTION END;. / WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE ('There is no student with student id 123'); 21

PL/SQL EXAMPLE There are two additional lines at the end of the block containing. and /. The. marks the end of the PL/SQL block and is optional. The / executes the PL/SQL block and is required. When SQL*Plus reads SQL statement, it knows that the semicolon marks the end of the statement. Therefore, the statement is complete and can be sent to the database. When SQL*Plus reads a PL/SQL block, a semicolon marks the end of the individual statement within the block. In other words, it is not a block terminator. 22

PL/SQL EXAMPLE Therefore, SQL*Plus needs to know when the block has ended. As you have seen in the example, it can be done with period and forward slash. 23

EXECUTING PL/SQL PL/SQL can be executed directly in SQL*Plus. A PL/SQL program is normally saved with an.sql extension. To execute an anonymous PL/SQL program, simply type the following command at the SQL prompt: SQL> @DisplayAge 24

DATATYPES Category Datatype Subtypes/Values Numerical NUMBER BINARY_INTEGER, DEC, DECIMAL, DOUBLE PRECISION, FLOAT, INTEGER, INT, NATURAL, NUMERIC, POSITIVE, REAL, SMALLINT, NATURAL Character CHAR, LOGN, VARCHAR2 CHARACTER, VARCHAR, STRING, NCHAR, NVARCHAR2 Date Binary DATE RAW, LONG RAW Boolean BOOLEAN Can have values like TRUE, FALSE and NULL RowID ROWID Stores values of address location of each record. 25

VARIABLES Oracle allows to use variables in PL/SQL. In PL/SQL, variables contain values resulting from queries to expressions. Variables are declared in declaration section. Declaring a variable: Syntax: VariableName datatype[not NULL] := initialvalue; Example: city char(10); counter number(2) NOT NULL :=0 26

VARIABLES Anchored datatype: A variable declared as anchored datatype means datatype for variable is determined based on the datatype of other object. This object can be other variable or column of table. Syntax: VariableName object% TYPE [NOT NULL] := initialvalue; Example: bal Account.ano%TYPE; name Customer.name%TYPE; 27

DECLARING A CONSTANT A constant is also used to store values but a value cannot be changed during program execution. Syntax: constantname CONSTANT datatype= initialvalue; Example: pi CONSTANT number(3,2) := 3.14; 28

ASSIGNING A VALUE Assigning a value in two ways: 1. Using assignment operator(:=) Syntax: VariableName := Value; Example: no := 101; 2. Reading from keyboard Syntax: VariableName := &VariableName; Example: no :=&no; 29

ASSIGNING A VALUE 3. Selecting or fetching table data values into variables Syntax: SELECT col1,col2, coln INTO var1,var2, varn FROM tablename WHERE condition; 30

GENERATING OUTPUT Like other programming languages, PL/SQL provides a procedure (i.e. PUT_LINE) to allow the user to display the output on the screen. For a user to able to view a result on the screen, two steps are required. First, before executing any PL/SQL program, type the following command at the SQL prompt (Note: you need to type in this command only once for every SQL*PLUS session): SQL> SET SERVEROUTPUT ON; or put the command at the beginning of the program, right before the declaration section. 31

GENERATING OUTPUT Second, use DBMS_OUTPUT.PUT_LINE in your executable section to display any message you want to the screen. Syntax for displaying a message: DBMS_OUTPUT.PUT_LINE(<string>); in which PUT_LINE is the procedure to generate the output on the screen, and DBMS_OUTPUT is the package to which the PUT_LINE belongs. DBMS_OUTPUT_PUT_LINE( My age is num_age); 32

SUBSTITUTIONVARIABLES SQL*Plus allows a PL/SQL block to receive input information with the help of substitution variables. Substitution variables cannot be used to output the values because no memory is allocated for them. SQL*Plus will substitute a variable before the PL/SQL block is sent to the database. Substitution variables are usually prefixed by the ampersand(&) character or double ampersand (&&) character. 33

EXAMPLE DECLARE BEGIN v_student_id NUMBER := &sv_student_id; v_first_name VARCHAR2(35); v_last_name VARCHAR2(35); SELECT first_name, last_name INTO v_first_name, v_last_name FROM student DBMS_OUTPUT.PUT_LINE ('Student name: ' v_first_name ' ' v_last_name); 34

EXAMPLE END; WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE('There is no such student'); When this example is executed, the user is asked to provide a value for the student ID. The example shown above uses a single ampersand for the substitution variable. When a single ampersand is used throughout the PL/SQL block, the user is asked to provide a value for each occurrence of the substitution variable. 35

EXAMPLE BEGIN DBMS_OUTPUT.PUT_LINE('Today is &sv_day'); END; This example produces the following output: Enter value for sv_day: Monday Today is Monday 36

EXAMPLE When a substitution variable is used in the script, the output produced by the program contains the statements that show how the substitution was done. If you do not want to see these lines displayed in the output produced by the script, use the SET command option before you run the script as shown below: SET VERIFY OFF; Using SET SERVEROUTPUT ON command we can display the output on. 37

EXAMPLE Then, the output changes as shown below: Enter value for sv_day: Monday Enter value for sv_day: Tuesday Today is Monday Tomorrow will be Tuesday PL/SQL procedure successfully completed. The substitution variable sv_day appears twice in this PL/SQL block. As a result, when this example is run, the user is asked twice to provide the value for the same variable. 38

CONTROL STRUCTURE Conditional control IF END IF IF ELSE END IF IF ELSIF ELSE END IF Iterative control LOOP EXIT WHEN END LOOP FOR LOOP END LOOP WHILE LOOP END LOOP Sequential control GOTO statement 39

CONTROL STRUCTURE Conditional control IF END IF IF ELSE END IF IF ELSIF ELSE END IF 40

--- IF END IF DECLARE BEGIN v_commison := 7500; IF v_dept = 10 THEN v_commision := 5000; END IF; END; /

--- IF ELSE END IF DECLARE BEGIN IF v_dept = 10 THEN v_commision := 5000; ELSE v_commision := 7500; END IF; END; /

--- IF ELSIF ELSE END IF DECLARE BEGIN IF v_dept = 10 THEN v_commision := 5000; ELSIF v_dept = 20 THEN v_commison := 5500; ELSIF v_dept = 30 THEN v_commison := 6200; ELSE v_commision := 7500; END IF; END; /

ITERATIVE CONTROL LOOP EXIT WHEN END LOOP FOR LOOP END LOOP WHILE LOOP END LOOP

--- LOOP EXIT WHEN END LOOP DECLARE v_deptno dept.deptno%type := 50; v_counter integer := 1; BEGIN LOOP INSERT INTO dept(deptno) VALUES(v_deptno); v_counter := v_counter + 1; v_deptno := v_deptno + 10; EXIT WHEN v_counter > 5; END LOOP; END; / 45ICS 334

--- FOR LOOP - END LOOP DECLARE v_deptno dept.deptno%type := 50; v_counter integer; BEGIN FOR v_counter IN 1..5 LOOP INSERT INTO dept(deptno) VALUES(v_deptno); v_deptno := v_deptno + 10; END LOOP; END; /

--- WHILE LOOP - END LOOP DECLARE v_deptno dept.deptno%type := 50; v_counter integer; BEGIN v_counter := 1; WHILE v_counter <= 5 LOOP INSERT INTO dept(deptno) VALUES(v_deptno); v_deptno := v_deptno + 10; END LOOP; END; /

SEQUENTIAL CONTROL To alter the sequence GOTO statement is used Syntax: GOTO jumhere; : :<<jumphere>> Example: Begin dbms_output.put_line( Code starts ); GOTO jump; 48

SEQUENTIAL CONTROL dbms_output.put_line( This statement is not executed ); <<jumphere>> dbms_output.put_line( Flow of Execution jumped here ); End; / 49

CURSORS A Cursor is an area in memory where the data required to execute SQL statement is stored. The data that is stored in the cursor is called the Active Data Set. The Size of the cursor will be same as a size to hold this data. The row that is being processed is called the current Row. A pointer known as a Row pointer is used to track the current row. 50

TYPES OF CURSORS 1.Implicit Cursors A cursors is called an Implicit cursor, if it is opened by Oracle itself to execute any SQL statement. 2.Explicit Cursors A cursors is called an Explicit cursor, if it is opened by user to process through PL/SQL block. 51

1.IMPLICIT CURSORS A cursors is called an Implicit cursor, if it is opened by Oracle itself to execute any SQL statement. Oracle perform the following operations to manage an implicit cursor. 1.reserves an area in memory to store data required to execute SQL statement 2.populates this area with required data 3.processes data 4.Fress memory area closes a cursor when processing is completed.

ATTRIBUTES OF IMPLICIT CURSORS Attributes SQL%ISOPEN SQL%FOUND SQL%NOTFO UND Description Always returns false If select found any record returns true else returns false. If select no found any record returns true else returns false. SQL%ROWCO UNT Returns number of records processed by select, insert,delete and update operation. 53

EXAMPLE Declare branch Account.bname%TYPE; Begin branch:=&branch; UPDATE Account SET bname=upper(branch) WHERE bname=branch; IF SQL%FOUND THEN dbms_output.put_line('total ' SQL%ROWCOUNT 'records are updated'); ELSE dbms_output.put_line('given branch not available"); END IF; End; / 54

2.EXPLICIT CURSORS A cursors is called an Explicit cursor, if it is opened by user to process data through PL/SQL block. An Explicit cursor is used when there is a need to process more than one record individually. The step required to manage Explicit cursors 1.Declare a Cursors 2. Open a Cursors 3.Fetching Data 4.Processing Data 5.Closing Cursors

EXPLICIT CURSORS 1) Declare a Cursor Syntax: CURSOR cursorname IS SELECT.; Example: CURSOR cacc IS SELECT ano,balance,bname FROM Account; 2) Open a Cursor Syntax: Open cursorname; Example: open cacc;

EXPLICIT CURSORS 3) Fetching a cursors Syntax: FETCH CursorName INTO variable1,variable2..variablen; Example: FETCH CAcc INTO no,bal,branch; 4) Processing Data This step involve actual processing of the table data. This step may involve various PL/SQL as well as SQL statements.

EXPLICIT CURSORS 5) Close a Cursor Syntax: Close cursorname; Example: Close CAcc;

EXAMPLE Declare CURSOR cacc is select ano,balance,bname from Account; no Account.ano%TYPE; bal Account.balance%TYPE; branch Account.bname%TYPE; Begin Open cacc; If cacc%isopen then loop Fetch cacc into no,bal,branch; Exit when cacc%notfound; 59

EXAMPLE If Branch='vvn' then end if; commit; else end loop; insert into Acc_vvn values(no,bal); delete from Account where ano=no; dbms_output.put_line('cursor can not be opened...'); end if; end; / 60

EXAMPLE IF SQL%FOUND THEN dbms_output.put_line('total ' SQL%ROWCOUNT 'records are ELSE updated'); dbms_output.put_line('given branch not available"); END IF; End; / 61

EXCEPTION HANDLING To handle various kinds of errors PL/SQL uses exception part. Type of Exception 1)Named Exception 2)Numbered Exception 3)User-define Exception 62

Scan PL/SQL Block Yes Exception Handling Section Available No Code Available to Handle Exception No Default Exception Handling Yes User Define Exception Handling Stop Working of the Exception Handler 63

NAMED EXCEPTION Some commonly occurring system exception are given name, and known as Named Exception. Oracle has defined 15 to 20 named Exception. Some of the named exception are listed below. 1. DUP_VAL_ON_INDEX 2. INVALID_CURSOR 3. INVALID_NUMBER 4. LOGIN_DENIED 5. NO_DATA_FOUND 6. NOT_LOGGED_ON 64

NAMED EXCEPTION 7. NOT_LOGGED_ON 8. PROGRAM_ERROR 9. TOO_MANY_ROWS 10. VALUE_ERROR 11. ZERO_DIVIDE 12. OTHER 65

NAMED EXCEPTION SYNTAX / DECLARE exceptionname EXCEPTION; PRAGMA EXCEPTION_INIT(exceptionName, errornumber); BEGIN ---EXECUTE Commands... EXCEPTION when exceptionname then ---code to handle Exception... END; 66

NAMED EXCEPTION EXAMPLE Declare exnull EXCEPTION; PRAGMA EXCEPTION_INIT(exNull,-1400); no Account.ano%Type; bal Account.balance%Type; branch Accout.bname%Type; Begin no :=&no; bal :=&bal; branch:='&branch'; insert into Account values(no,bal,branch); commit; 67

NAMED EXCEPTION EXAMPLE dbms_output.put_line('record inserted successfully...'); Exception when DUP_VAL_ON_INDEX then dbms_output.put_line('duplicate value found for primary key.'); when exnull then dbms_output.put_line('null value found for primary key.'); end; / 68

NUMBERED EXCEPTION SYNTAX / DECLARE exceptionname EXCEPTION; PRAGMA EXCEPTION_INIT(exceptionName, errornumber); BEGIN ---EXECUTE Commands... EXCEPTION when exceptionname then ---code to handle Exception... END; 69

NUMBERED EXCEPTION EXAMPLE Declare Begin exnull EXCEPTION; PRAGMA EXCEPTION_INIT(exNull,-1400); no Account.ano%Type; bal Account.balance%Type; branch Accout.bname%Type; no :=&no; bal :=&bal; branch:='&branch'; insert into Account values(no,bal,branch); commit; dbms_output.put_line('record inserted successfully...'); 70

NUMBERED EXCEPTION EXAMPLE when DUP_VAL_ON_INDEX then dbms_output.put_line('duplicate value found for primary key.'); when exnull then dbms_output.put_line('null value found for primary key.'); end; / 71

USER DEFINE EXCEPTION Declare 1400); exnull EXCEPTION; PRAGMA EXCEPTION_INIT(exNull,- myex EXCEPTION exception----- ----user define no Account.ano%Type; bal Account.balance%Type; branch Accout.bname%Type; 72

USER DEFINE EXCEPTION Begin no :=&no; bal :=&bal; branch:='&branch'; if bal<0 then raise myex; end if; insert into Account values(no,bal,branch); commit; dbms_output.put_line('record inserted successfully...'); Exception 73

USER DEFINE EXCEPTION when DUP_VAL_ON_INDEX then dbms_output.put_line('duplicate value found for primary key.'); when exnull then dbms_output.put_line('null value found for primary key.'); when myex then dbms_output.put_line('balance can not be negative value.'); end; / 74

PROCEDURES AND FUNCTION A procedure or function is a group or set of SQL and PL/SQL statement that perform a specific task. A procedure or function is a named PL/SQL block of code. This block can be compiled and successfully compiled block can be stored in oracle database. so that is called stored procedure and function. 75

STRUCTURE OF PROCEDURES Declaration --variable declaration--- Executable commands ---statement of SQL and PL/SQL Exception Handling ---handle exception or error-- 76

SYNTAX OF PROCEDURES Create or Replace PROCEDURE ProcedureName (argument [IN,OUT,IN OUT] datatype,..) IS <declaration section> Begin --mandatory --- <executable commands> Exception --optional--- <Exception Handling> End; ---Mandatory--- 77

EXAMPLE OF PROCEDURES create or replace procedure debitacc IS Begin ( no IN Account.ano%Type,amount IN Number) balaccount.balance%type; NewBalanceAccount.balance%TYPE; select balance into bal from Account where ano=no; NewBalance:=bal-amount; update Account Set balance=newbalance where ano=no; dbms_output.put_line('account' no 'debited...'); End; / 78

SYNTAX OF FUNCTION CREATE OR REPLACE FUNCTION Functionname (argument IN datatype ) RETURN datatype IS <Declaration Section> BEGIN <Executable Commands> EXCEPTION <Exception Handling> END; 79

EXAMPLE OF FUNCTION CREATE OR REPLACE FUNCTION totalcustomers RETURN number IS total number(2) := 0; BEGIN SELECT count(*) into total FROM customers; RETURN total; END; / 80

EXECUTION OF PROCEDURE AND FUNCTION For procedure EXEC debitacc( A01,1000); For function select getbalance( A01 ) from dual; 81

ADVANTAGES OF PROCEDURE AND FUNCTION Security Faster execution Sharing of code Productivity Integrity 82

PROCEDURE VS. FUNCTION FUNCTION PROCEDURE A function mast return a value. A procedure can also return value but not mandatory. A function can return only one value. A function use select command for execution of it. A function can not use EXEC command for execution of it. A procedure can return more than one value. A procedure can not use select command for execution of it. A procedure use EXEC command for execution of it. 83

PACKAGE A package is a container for other database objects. A package can hold other database objects such as variables, constants, cursors, exception, procedure, function and sub-programs. It is one kind of database object. 84

STRUCTURE OF PACKAGE 1.Package Specification CREATE OR REPLACE PACKAGE packagename IS --Package specification... END packagename; 2.Package Body CREATE OR REPLACE PACKAGE BODY packagename IS --Package body... END packagename; 85

PACKAGE SPECIFICATION CREATE OR REPLACE PACKAGE transaction IS (No IN Account.ano%TYPE, Amount IN NUMBER) (No IN Account.ano%TYPE) RETURN NUMBER END transaction; / 86

PACKAGE BODY CREATE OR REPLACE PACKAGE transaction IS --define procedure debitacc CREATE OR REPLACE PROCEDURE debitacc (no IN Account.ano%TYPE, Amount IN NUMBER) IS bal Account.balance%TYPE; newbal Account.balance%TYPE; BEGIN SELECT balance INTO bal FROM Account WHERE ANO = NO: newbalance := bal amount; dbms_output.put_line ( Account no debited); END; 87

PACKAGE BODY --define function getbalance CREATE OR REPLACE FUNCTION getbalance (No IN Account.ano%TYPE) RETURN NUMBER IS BEGIN BAL Account.balance%TYPE; SELECT balance INTO BAL FROM Account END; WHERE ANO = NO: END transaction; / RETURN BAL; 88

RUN OR REFERENCING A PACKAGE SUBPROGRAM For procedure EXEC transaction.debitacc( A01,1000); For function select transaction.getbalance( A01 ) from dual; 89

DESTROYING A PACKAGE Syntax: drop package[body] packagename; Example: drop package transaction; 90

TRIGGERS Triggers are stored programs, which are automatically executed or fired when some events occur. Triggers are, in fact, written to be executed in response to any of the following events: A database manipulation (DML) statement (DELETE, INSERT, or UPDATE). A database definition (DDL) statement (CREATES, ALTER, or DROP). A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN). Triggers could be defined on the table, view, schema, or database with which the event is associated. 91

SYNTAX OF TRIGGERS CREATE OR REPLACE TRIGGER triggername [BEFORE / AFTER] column]] [INSERT, DELETE, UPDATE [OF ON Tablename [REFERENCING [OLD AS old, NEW AS new] ] 92

SYNTAX OF TRIGGERS / [FOR EACH ROW [WHEN condition] Commands> IS BEGIN <Declaration Section> <Executable EXCEPTION END; <Exception Handling> 93

EXAMPLE OF TRIGGER CREATE OR REPLACE TRIGGER Invalid_bal BEFORE INSERT ON Account FOR EACH ROW BEGIN IF NEW. Balance < 1000 THEN dbms_output.put_line ( Balance is not sufficient ); END IF; END; / 94

GTU IMPORTANT QUESTIONS 1. Differentiate : SQL and PL/SQL. 2. Write short note on Structure of PL/SQL block. 3. Explain Anchored data type with example. 4. Find out maximum value out of given three numbers. 5. What is explicit cursor? Explain various steps to manage it. 6. Explain different types of explicit cursor. 7. State the meaning of PRAGMA EXCEPTION_INIT. 8. Explain error handling using example. 9. Display three account having top three highest balance. 95

GTU IMPORTANT QUESTIONS 11. Write short note on : Stored Procedure. 12. Explain procedure in detail with example. 13. Define package. Write steps to create package in PL/SQL. 14. What is trigger? Explain advantages and types of triggers. 15. Explain RAISE_APPLICATION_ERROR. 96

97