Oracle PL/SQL IV Exceptions Packages.

Slides:



Advertisements
Similar presentations
PL/SQL.
Advertisements

Chapter 8 Advanced SQL Pearson Education © Chapter 8 - Objectives u How to use the SQL programming language u How to use SQL cursors u How to create.
BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures.
Procedure and Functions. Procedures Syntax: [CREATE [OR REPLACE]] PROCEDURE Pname [(p1, p2…)][IS | AS] [declarations] BEGIN [Execution Statements] [EXCEPTIONS.
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
SQL*PLUS, PLSQL and SQLLDR Ali Obaidi. SQL Advantages High level – Builds on relational algebra and calculus – Powerful operations – Enables automatic.
PL/SQL.
Chapter 7: User-Defined Functions II
Advanced Package Concepts. 2 home back first prev next last What Will I Learn? Write packages that use the overloading feature Write packages that use.
VBA Modules, Functions, Variables, and Constants
1 Copyright © 2004, Oracle. All rights reserved. Creating Stored Procedures.
Creating Packages. 2 home back first prev next last What Will I Learn? Describe the reasons for using a package Describe the two components of a package:
A Guide to Oracle9i1 Advanced SQL And PL/SQL Topics Chapter 9.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
Bordoloi and Bock EXCEPTIONS. Bordoloi and Bock Errors Two types of errors can be found in a program: compilation errors and runtime errors. There is.
Cursor and Exception Handling By Nidhi Bhatnagar.
Stored Procedures Functions Packages
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Lecture 4 PL/SQL language. PL/SQL – procedural SQL Allows combining procedural and SQL code PL/SQL code is compiled, including SQL commands PL/SQL code.
Stored Procedures, Transactions, and Error-Handling
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 7 PL/SQL Packages.
INTRODUCTION TO PL/SQL. Class Agenda Introduction Introduction to PL/SQL Declaring PL/SQL Variable Creating the Executable Section Interacting with the.
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
PL/SQL A BRIEF OVERVIEW DAVID WILSON. PL/SQL User’s Guide and Reference PL/SQL User’s Guide and Reference.
PL SQL Block Structures. What is PL SQL A good way to get acquainted with PL/SQL is to look at a sample program. PL/SQL combines the data manipulating.
Advanced SQL: Cursors & Stored Procedures
PRACTICE OVERVIEW PL/SQL Part Examine this package specification and body: Which statement about the V_TOTAL_BUDGET variable is true? A. It must.
CSIT 313 DB PROGRAMMING EXCEPTION HANDLING. In PL/SQL, an error condition is called an exception. An exception can be either –internally defined (by the.
PL / SQL By Mohammed Baihan. What is PL/SQL? PL/SQL stands for Procedural Language extension of SQL. PL/SQL is a combination of SQL along with the procedural.
PL/SQL Oracle's Database Programming Language. Remember: Set serveroutput on With serveroutput off (default) executing procedure: With serveroutput on:
Programmatic SQL Shaista Khan CS 157B. Topic Embedded SQL statements in high-level programming languages.
8 1 Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Trapping Oracle Server Exceptions. 2 home back first prev next last What Will I Learn? Describe and provide an example of an error defined by the Oracle.
BIS Database Systems School of Management, Business Information Systems, Assumption University A.Thanop Somprasong Chapter # 8 Advanced SQL.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
PL/SQL Block Structure DECLARE - Optional Variables, cursors, user-defined exceptions BEGIN - Mandatory SQL Statements PL/SQL Statements EXCEPTIONS - Optional.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
Guide to Oracle 10g ITBIS373 Database Development Lecture 4a - Chapter 4: Using SQL Queries to Insert, Update, Delete, and View Data.
Advanced SQL: Triggers & Assertions
What is a Package? A package is an Oracle object, which holds other objects within it. Objects commonly held within a package are procedures, functions,
© 2007 by Prentice Hall7-1 Introduction to Oracle 10g Chapter 7 Using PL/SQL to Your Advantage James Perry and Gerald Post.
Chapter 9: Advanced SQL and PL/SQL Guide to Oracle 10g.
1 Handling Exceptions Part F. 2 Handling Exceptions with PL/SQL What is an exception? Identifier in PL/SQL that is raised during execution What is an.
Chapter 16 Cursors and Exceptions. Chapter Objectives  Determine when an explicit cursor is required  Declare, open, and close an explicit cursor 
CREATING STORED PROCEDURES AND FUNCTIONS. Objectives After completing this lecture, you should be able to do the following: Differentiate between anonymous.
Handling Exceptions. Objectives What is exception Types of exceptions How to handle exceptions Trapping pre defined oracle errors.
PRACTICE OVERVIEW PL/SQL Part Your stored procedure, GET_BUDGET, has a logic problem and must be modified. The script that contains the procedure.
Oracle10g Developer: PL/SQL Programming1 Objectives Named program units How to identify parameters The CREATE PROCEDURE statement Creating a procedure.
Creating Procedures. PL/SQL Program Construct Tools Constructs Anonymous Block Application procedures or functions Application packages Application Triggers.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
Advanced SQL: Cursors & Stored Procedures Instructor: Mohamed Eltabakh 1.
Lab 2 Writing PL/SQL Blocks CISB514 Advanced Database Systems.
Last Updated : 27 th April 2004 Center of Excellence Data Warehousing Group Teradata RDBMS Concepts.
Kingdom of Saudi Arabia Ministry of Higher Education Al-Imam Muhammad Ibn Saud Islamic University College of Computer and Information Sciences Overview.
Introduction to PL/SQL N. Dimililer. About PL/SQL –PL/SQL is an extension to SQL with design features of programming languages. –Data manipulation and.
What Are Subprograms? Subprograms are named PL/SQL blocks that can take parameters and be invoked. Subprograms allow decomposition of a program into logical.
CS422 Principles of Database Systems Oracle PL/SQL Chengyu Sun California State University, Los Angeles.
Oracle9i Developer: PL/SQL Programming Chapter 6 PL/SQL Packages.
1 Copyright © 2004, Oracle. All rights reserved. PL/SQL Programming Concepts: Review.
Pl/SQL LANGUAGE MULITPLE CHOICE QUESTION SET-3
Creating Stored Procedures and Functions
PL/SQL.
UNIT - V STORED PROCEDURE.
Handling Exceptions.
SQL PL/SQL Presented by: Dr. Samir Tartir
PL/SQL Package Week 8.
Handling Exceptions.
Sa0951a PL/SQL 1: Introduction
PL/SQL Declaring Variables.
Prof. Arfaoui. COM390 Chapter 7
Presentation transcript:

Oracle PL/SQL IV Exceptions Packages

Exception Handling Remember it is optional [DECLARE] BEGIN [EXCEPTION] END;

More on Exception Handling Exceptions are pre-defined or designer-specified occurrences during the operation of a PL/SQL block Exceptions are named by user or by Oracle Exceptions are raised internally by PL/SQL or explicitly by designer using RAISE keyword A routine in the Exception section will then be called

User-defined Declare a name for the exception Identify point to raise exception Defining code to fire when raised DECLARE Salary_too_high EXCEPTION; Invalid_tax_code EXCEPTION; ….

RAISING Once control has passed to the Exception section it cannot be returned to the block that raised it RAISE exception_name IF v_salary>v_max then RAISE salary_too_high; End if Jump to the exception section user defined as salary_too_high

EXCEPTION Section EXCEPTION WHEN salary_too_high then “PL/SQL statements here”; WHEN another_error OR yet_another WHEN OTHERS -- Oracle defined END; Note OTHERS will trap any other error that you have not accounted for

Example / set serveroutput on DECLARE v_bonus number; null_bonus_alert exception; BEGIN select bonus into v_bonus from personnel where snum=3813; if v_bonus is null then raise null_bonus_alert; end if; EXCEPTION when null_bonus_alert then dbms_output.put_line('This exmployee really should get a bonus!'); END; /

RAISE_APPLICATION _ERROR We have seen this already Error_number is a negative integer in the range -20000 to -20999 Error_message is a character string up to 512 bytes Raise_application_error(error_number,error_message)

Example and error generated DECLARE v_bonus number; BEGIN select bonus into v_bonus from personnel where snum=3813; if v_bonus is null then raise_application_error(-20111,'For goodness sake give him a bonus!!'); end if; END; / declare * ERROR at line 1: ORA-20111: For goodness sake give him a bonus!! ORA-06512: at line 6

Common Pre-defined Exceptions Oracle Error Exception description ORA-00001 DUP_VAL_ON_INDEX PK violation ORA-01403 NO_DATA_FOUND No records ORA-01422 TOO_MANY_ROWS > 1 row ORA-01476 ZERO_DIVIDE ORA-01722 INVALID_NUMBER Can’t convert Note: there are others too!

Example using pre-defined method --This example returns salaries for branch 10 DECLARE v_salary personnel.salary%type; BEGIN select salary into v_salary from personnel where div=10; EXCEPTION when too_many_rows -- this is the pre-defined exception then raise_application_error (-20001, ' Did not expect so many'); END; / declare * ERROR at line 1: ORA-20001: Did not expect so many ORA-06512: at line 7

If you don’t trap it Oracle takes over! --in this example branch 40 has no staff yet! DECLARE v_salary personnel.salary%type; BEGIN select salary into v_salary from personnel where div=40; EXCEPTION when too_many_rows -- this is the pre-defined exception then raise_application_error (-20001, ' Did not expect so many'); END; / declare * ERROR at line 1: ORA-01403: no data found – occurs as div 40 has no staff! ORA-06512: at line 4 This is NO_DATA_FOUND exception

PACKAGES

What are they? A collection of PL/SQL objects that are logically grouped together to form one unit They can contain: Procedures, functions Cursors, variables, Constants Tables Exceptions Typically, they may contain all routines to process purchase orders, for example.

Package structure Has 2 parts: Package Specification Package Body Declares public procedures etc Other programs can access them outside the package Package Body Implements the public procedures etc but also may specify private procedures, functions etc The private units are only accessible within the scope of the package itself All units declared in specification MUST be implemented in the body

Package Specification example CREATE OR REPLACE PACKAGE package_name IS PROCEDURE sal_raise (p1 NUMBER, p2 NUMBER); --------------------------------------------- FUNCTION div_bal (div_no IN NUMBER) RETURN NUMBER; END package_name; -- not necessary to name package here -- just for clarity Note there is no PL/SQL executable code

Package Body CREATE OR REPLACE PACKAGE BODY package_name IS PROCEDURE sal_raise (p1 NUMBER, p2 NUMBER) BEGIN update staff set salary=salary*1.1 where div=p2; END sal_raise; --------------------------------------------- FUNCTION div_bal (div_no IN NUMBER) RETURN NUMBER bal number; select sum(salary) into bal from staff where div=div_no; RETURN bal; END div_bal; END package_name;

How do we use them? Execute package_name.element DROP PACKAGE package_name Will remove specification and body DROP PACKAGE BODY package_name Will only remove the body To run/access an element of a package body Execute package_name.element empName:=package_name.getName(empID); The package The function element The parameter

Global variables CREATE OR REPLACE PACKAGE BODY stdcomp IS gcompany NUMBER; -- global to the package PROCEDURE setcomp (xcompany IN NUMBER) IS BEGIN gcompany:=xcompany; END setcomp; --------------------------------------------- FUNCTION getcomp RETURN NUMBER IS RETURN NVL(gcompany,0); END getcomp; END stdcomp;

Instantiation and persistence Instantiation occurs each time you connect to the database So any state of your current session is lost when this happens And packages are instantiated again The default behaviour of a package is to maintain its state once it has been instantiated throughout the life of the session

Persistence execution Execute pack1.proc1 – do it 3 times! v1 2 3 4 v2 CREATE OR REPLACE PACKAGE pack1 IS V1 NUMBER:=1; Procedure proc1; End pack1; CREATE OR REPLACE PACKAGE BODY pack1 IS V2 NUMBER:=2; Procedure proc1 IS V3 NUMBER:=3; BEGIN v1:=v1+1; v2:=v2+2; v3:=v3+3; DBMS_OUTPUT.PUT_LINE(‘v1 = ‘||v1); DBMS_OUTPUT.PUT_LINE(‘v2 = ‘||v2); DBMS_OUTPUT.PUT_LINE(‘v3 = ‘||v3); END proc1; END pack1; execution 1st 2nd 3rd v1 2 3 4 v2 6 8 v3 Execute pack1.proc1 – do it 3 times!

Pragma SERIALLY_REUSABLE Causes the PL/SQL runtime to discard the state of the package. So instantiation occurs each time it is invoked Pragma serially_reusable needs to be applied to both the SPECIFICATION and the BODY Now, execution 3 times of the previous code would be as follows CREATE OR REPLACE PACKAGE pack1 IS Pragma serially_reusable; V1 NUMBER:=1; Procedure proc1; End pack1; v1 2 v2 4 v3 6

Overloading Sub-programs in a package body can have the same names so long as parameter lists are not the same. E.g. the TO_CHAR function in SQL takes either a number or a date. The appropriate function is called depending on what the user enters.

Overload example Code Continues on next slide CREATE OR REPLACE PACKAGE overload IS Function sal_return (p_detail NUMBER) Return NUMBER; Function sal_return (p_detail VARCHAR2) End overload; CREATE OR REPLACE PACKAGE BODY overload IS Return NUMBER IS v_salary NUMBER; BEGIN Select salary into v_salary from staff where snum=p_detail; Return v_salary; END sal_return; Code Continues on next slide

Continued ….. Same name different parameter datatype Different attribute Function sal_return (p_detail VARCHAR2) Return NUMBER IS v_salary NUMBER; BEGIN Select salary into v_salary from staff where surname=p_detail; Return v_salary; END sal_return; END overload; SELECT overload.sal_return(3488) from dual ; -- this would call the first sal_return SELECT overload.sal_return(‘STYLES’) from dual; -- this would call the second

Legal and illegal packages! CREATE OR REPLACE PACKAGE ovtest IS Function cat (n1 NUMBER, c2 VARCHAR2) Return VARCHAR2; ---------------------------------------------- Function cat (c1 VARCHAR2, n2 NUMBER) End ovtest; LEGAL as positions are different CREATE OR REPLACE PACKAGE ovtest IS Function cat (n1 NUMBER, c2 VARCHAR2) Return VARCHAR2; ---------------------------------------------------------- Function cat (n1 INTEGER, c2 CHAR) End ovtest; ILLEGAL as parameters in both are compatible

Summary Exceptions Packages RAISE_APPLICATION_ERROR RAISE User or pre-defined Exception WHEN ……… Packages Specification and Body Executing and calling Instantiation and persistence Global and local variables

READING Connolly/Begg (4th ed) 8.2.5, 8.2.6 Shah (Ch 10,12) Morrison/Morrison “Guide to ORACLE 10g” Ch.4 & 9 – selected bits Casteel, J (2003). Oracle 9i Developer: PL/SQL Programming – chapter 3 & 6.