Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded.

Slides:



Advertisements
Similar presentations
PL/SQL.
Advertisements

BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures.
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
PL/SQL. Introduction to PL/SQL PL/SQL is the procedure extension to Oracle SQL. It is used to access an Oracle database from various environments (e.g.
Triggers The different types of integrity constraints discussed so far provide a declarative mechanism to associate “simple” conditions with a table such.
Chapter 4B: More Advanced PL/SQL Programming
A Guide to Oracle9i1 Advanced SQL And PL/SQL Topics Chapter 9.
Introduction to PL/SQL
Introduction to PL/SQL Lecture 0 – Self Study Akhtar Ali.
Bordoloi and Bock PROCEDURES, FUNCTIONS & TRIGGERS.
Bordoloi and Bock CURSORS. Bordoloi and Bock CURSOR MANIPULATION To process an SQL statement, ORACLE needs to create an area of memory known as the context.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
Cursor and Exception Handling By Nidhi Bhatnagar.
1 Introduction to PL/SQL. 2  Procedural programming language  Uses detailed instructions  Processes statements sequentially  Combines SQL commands.
Oracle10g Developer: PL/SQL Programming1 Objectives Manipulating data with cursors Managing errors with exception handlers Addressing exception-handling.
Chapter 4 Cursors and Exception Handling Oracle10g Developer:
Chapter 4: Introduction to PL/SQL
Triggers A Quick Reference and Summary BIT 275. Triggers SQL code permits you to access only one table for an INSERT, UPDATE, or DELETE statement. The.
Program with PL/SQL. Interacting with the Oracle Server.
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
CS178 Database Management PL/SQL session 8 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman.
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.
1 CursorsCursors. 2 SQL Cursor A cursor is a private SQL work area. A cursor is a private SQL work area. There are two types of cursors: There are two.
CIS4368: Advanced DatabaseSlide # 1 PL/SQL Dr. Peeter KirsSpring, 2003 PL/SQL.
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.
Trigger Oracle PL/SQL. Triggers Associated with a particular table Associated with a particular table Automatically executed when a particular event occurs.
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.
SQL Fundamentals  SQL: Structured Query Language is a simple and powerful language used to create, access, and manipulate data and structure in the database.
1 PL/SQLPL/SQL Declaring Variables Declaring Variables Declaring Variables Declaring Variables Writing Executable Statements Writing Executable Statements.
Fall 2001Database Systems1 Triggers Assertions –Assertions describe rules that should hold for a given database. –An assertion is checked anytime a table.
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,
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
Using SQL in PL/SQL ITEC 224 Database Programming.
PL/SQLPL/SQL Oracle11g: PL/SQL Programming Chapter 4 Cursors and Exception Handling.
ITEC 224 Database Programming PL/SQL Lab Cursors.
Chapter 16 Cursors and Exceptions. Chapter Objectives  Determine when an explicit cursor is required  Declare, open, and close an explicit cursor 
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
implicit and an explicit cursor
Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha Function, Trigger used in PosgreSQL.
Chapter 18: Exception Handling1 Chapter Eighteen Exception Handling Objective: – Define exceptions – List types of exception handlers – Trap errors – Exception.
A procedure is a module performing one or more actions; it does not need to return any values. The syntax for creating a procedure is as follows: CREATE.
PRACTICE OVERVIEW PL/SQL Part Your stored procedure, GET_BUDGET, has a logic problem and must be modified. The script that contains the procedure.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
Introduction to PL/SQL Francis Thottungal. The outline The basic PL/SQL code structure is : DECLARE -- optional, which declares and define variables,
Program with PL/SQL Lesson 3. Interacting with the Oracle Server.
Chapter 8 Advanced SQL Pearson Education © Chapter 8 - Objectives How to use the SQL programming language How to use SQL cursors How to create stored.
Kingdom of Saudi Arabia Ministry of Higher Education Al-Imam Muhammad Ibn Saud Islamic University College of Computer and Information Sciences Overview.
SQL Triggers, Functions & Stored Procedures Programming Operations.
CS422 Principles of Database Systems Stored Procedures and Triggers Chengyu Sun California State University, Los Angeles.
1 Copyright © 2004, Oracle. All rights reserved. PL/SQL Programming Concepts: Review.
ITEC 224 Database Programming
Pl/SQL LANGUAGE MULITPLE CHOICE QUESTION SET-3
Interacting with the Oracle Server
PL/SQL.
SQL Stored Triggers Presented by: Dr. Samir Tartir
Oracle11g: PL/SQL Programming Chapter 4 Cursors and Exception Handling.
Oracle9i Developer: PL/SQL Programming Chapter 3 PL/SQL Processing.
Handling Exceptions.
SQL PL/SQL Presented by: Dr. Samir Tartir
Database Management Systems 2
Handling Exceptions.
Chapter 4: Introduction to PL/SQL
Chapter 2 Handling Data in PL/SQL Blocks Oracle9i Developer:
Oracle9i Developer: PL/SQL Programming Chapter 8 Database Triggers.
Chapter 8 Advanced SQL.
Presentation transcript:

Oracle PL/SQL

PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded functionality of database applications Allows expanded functionality of database applications Continues to improve with each new database release Continues to improve with each new database release

PL/SQL Features Features Tight integration with SQLTight integration with SQL Supports data types, functions, pseudo-columns, etc. Supports data types, functions, pseudo-columns, etc. Increased performanceIncreased performance A block of statements sent as a single statement A block of statements sent as a single statement Increased productivityIncreased productivity Same techniques can be used with most Oracle products Same techniques can be used with most Oracle products PortabilityPortability Works on any Oracle platform Works on any Oracle platform Tighter securityTighter security Users may access database objects without granted privileges Users may access database objects without granted privileges

PL/SQL Programs Declaration section (optional) Declaration section (optional) Any needed variables declared hereAny needed variables declared here Executable or begin section Executable or begin section Program code such as statements to retrieve or manipulate data in a tableProgram code such as statements to retrieve or manipulate data in a table Exception section (optional) Exception section (optional) Error traps can catch situations which might ordinarily crash the programError traps can catch situations which might ordinarily crash the program

PL/SQL Block Structure

PL/SQL Variables Variables are local to the code block Variables are local to the code block Names can be up to 30 characters long and must begin with a character Names can be up to 30 characters long and must begin with a character Declaration is like that in a table Declaration is like that in a table Name then data type the semi-colonName then data type the semi-colon Can be initialized using := operator in the declarationCan be initialized using := operator in the declaration Can be changed with := in the begin sectionCan be changed with := in the begin section Can use constraintsCan use constraints Variables can be composite or collection types Variables can be composite or collection types Multiple values of different or same typeMultiple values of different or same type

Common PL/SQL Data Types CHAR ( max_length )CHAR ( max_length ) VARCHAR2 ( max_length )VARCHAR2 ( max_length ) NUMBER ( precision, scale )NUMBER ( precision, scale ) BINARY_INTEGER – more efficient than numberBINARY_INTEGER – more efficient than number RAW ( max_length )RAW ( max_length ) DATEDATE BOOLEAN (true, false, null)BOOLEAN (true, false, null) Also LONG, LONG RAW and LOB types but the capacity is usually less in PL/SQL than SQLAlso LONG, LONG RAW and LOB types but the capacity is usually less in PL/SQL than SQL

PL/SQL Variable Constraints NOT NULL NOT NULL Can not be emptyCan not be empty CONSTANT CONSTANT Can not be changedCan not be changed

PL/SQL Variables Examples Age number; Last char ( 10 ); DVal Date := Sysdate; SID number not null; Adjust constant number := 1; CanLoop boolean := true

Predefined Exceptions INVALID_NUMBER (ORA-01722) INVALID_NUMBER (ORA-01722) Attempted to store non-numeric data in a variable with a numeric data typeAttempted to store non-numeric data in a variable with a numeric data type NO_DATA_FOUND (ORA-01403) NO_DATA_FOUND (ORA-01403) Query resulted in no rows being foundQuery resulted in no rows being found NOT_LOGGED_ON (ORA-01012) NOT_LOGGED_ON (ORA-01012) Not currently connected to an Oracle databaseNot currently connected to an Oracle database TOO_MANY_ROWS (ORA-01422) TOO_MANY_ROWS (ORA-01422) A SELECT INTO statement returned more than one rowA SELECT INTO statement returned more than one row

Predefined Exceptions (cont.) DUP_VALUE_ON_INDEX (ORA-00001) DUP_VALUE_ON_INDEX (ORA-00001) Value inserted for a primary key is not uniqueValue inserted for a primary key is not unique VALUE_ERROR (ORA-06502) VALUE_ERROR (ORA-06502) The value being placed in a variable is the wrong length or data typeThe value being placed in a variable is the wrong length or data type ZERO_DIVIDE (ORA-01476) ZERO_DIVIDE (ORA-01476) An attempt was made to divide a number by zeroAn attempt was made to divide a number by zero

Structure of Exception Section

Conditional Structures IF-THEN IF-THEN IF-THEN-ELSE IF-THEN-ELSE IF-THEN-ELSIF IF-THEN-ELSIF An alternative to nested IF-THEN_ELSEAn alternative to nested IF-THEN_ELSE

IF-THEN Structure

IF-THEN-ELSE Structure

IF-THEN-ELSIF Structure

Stored Procedures

The first line is called the Procedure Specification The first line is called the Procedure Specification The remainder is the Procedure Body The remainder is the Procedure Body A procedure is compiled and loaded in the database as an object A procedure is compiled and loaded in the database as an object Procedures can have parameters passed to them Procedures can have parameters passed to them

Stored Procedures Run a procedure with the PL/SQL EXECUTE command Run a procedure with the PL/SQL EXECUTE command Parameters are enclosed in parentheses Parameters are enclosed in parentheses

Stored Functions Like a procedure except they return a single value Like a procedure except they return a single value

Triggers Associated with a particular table Associated with a particular table Automatically executed when a particular event occurs Automatically executed when a particular event occurs InsertInsert UpdateUpdate DeleteDelete OthersOthers

Triggers vs. Procedures Procedures are explicitly executed by a user or application Procedures are explicitly executed by a user or application Triggers are implicitly executed (fired) when the triggering event occurs Triggers are implicitly executed (fired) when the triggering event occurs Triggers should not be used as a lazy way to invoke a procedure as they are fired every time the event occurs Triggers should not be used as a lazy way to invoke a procedure as they are fired every time the event occurs

Triggers

Triggers The trigger specification names the trigger and indicates when it will fire The trigger specification names the trigger and indicates when it will fire The trigger body contains the PL/SQL code to accomplish whatever task(s) need to be performed The trigger body contains the PL/SQL code to accomplish whatever task(s) need to be performed

Triggers

Triggers Timing A triggers timing has to be specified first A triggers timing has to be specified first Before (most common)Before (most common) Trigger should be fired before the operation Trigger should be fired before the operation i.e. before an inserti.e. before an insert AfterAfter Trigger should be fired after the operation Trigger should be fired after the operation i.e. after a delete is performedi.e. after a delete is performed

Trigger Events Three types of events are available Three types of events are available DML eventsDML events DDL eventsDDL events Database eventsDatabase events

DML Events Changes to data in a table Changes to data in a table InsertInsert UpdateUpdate DeleteDelete

DDL Events Changes to the definition of objects Changes to the definition of objects TablesTables IndexesIndexes ProceduresProcedures FunctionsFunctions OthersOthers Include CREATE, ALTER and DROP statements on these objects Include CREATE, ALTER and DROP statements on these objects

Database Events Server Errors Server Errors Users Log On or Off Users Log On or Off Database Started or Stopped Database Started or Stopped

Trigger DML Events Can specify one or more events in the specification Can specify one or more events in the specification i.e. INSERT OR UPDATE OR DELETEi.e. INSERT OR UPDATE OR DELETE Can specify one or more columns to be associated with a type of event Can specify one or more columns to be associated with a type of event i.e. BEFORE UPDATE OF SID OR SNAMEi.e. BEFORE UPDATE OF SID OR SNAME

Table Name The next item in the trigger is the name of the table to be affected The next item in the trigger is the name of the table to be affected

Trigger Level Two levels for Triggers Two levels for Triggers Row-level triggerRow-level trigger Requires FOR EACH ROW clause Requires FOR EACH ROW clause If operation affects multiple rows, trigger fires once for each row affectedIf operation affects multiple rows, trigger fires once for each row affected Statement-level triggerStatement-level trigger DML triggers should be row-levelDML triggers should be row-level DDL and Database triggers should not be row-levelDDL and Database triggers should not be row-level

Event Examples

Triggers Conditions Available So Multiple Operations Can Be Dealt With In Same Trigger Conditions Available So Multiple Operations Can Be Dealt With In Same Trigger Inserting, Updating, DeletingInserting, Updating, Deleting Column Prefixes Allow Identification Of Value Changes Column Prefixes Allow Identification Of Value Changes New, OldNew, Old

Triggers Exceptions EXCEPTION Data Type Allows Custom Exceptions EXCEPTION Data Type Allows Custom Exceptions RAISE Allows An Exception To Be Manually Occur RAISE Allows An Exception To Be Manually Occur RAISE_APPLICATION_ERROR Allows Termination Using A Custom Error Message RAISE_APPLICATION_ERROR Allows Termination Using A Custom Error Message Must Be Between and Must Be Between and Message Can Be Up to 512 BytesMessage Can Be Up to 512 Bytes

Cursors Cursors Hold Result of an SQL Statement Cursors Hold Result of an SQL Statement Two Types of Cursors in PL/SQL Two Types of Cursors in PL/SQL Implicit – Automatically Created When a Query or Manipulation is for a Single RowImplicit – Automatically Created When a Query or Manipulation is for a Single Row Explicit – Must Be Declared by the UserExplicit – Must Be Declared by the User Creates a Unit of Storage Called a Result Set Creates a Unit of Storage Called a Result Set

Cursors Result Set MIS380 DATABASE DESIGN4 MIS202 INFORMATION SYSTEMS 3 <Cursor MIS485 MANAGING TECHNOLOGY4 MIS480 ADVANCED DATABASE 4

Cursors Declaring an Explicit Cursor Declaring an Explicit Cursor CURSOR CursorName IS SelectStatement; Opening an Explicit Cursor Opening an Explicit Cursor OPEN CursorName; Accessing Rows from an Explicit Cursor Accessing Rows from an Explicit Cursor FETCH CursorName INTO RowVariables;

Cursors Declaring Variables of the Proper Type with %TYPE Declaring Variables of the Proper Type with %TYPE VarName TableName.FieldName%TYPE; Declaring Variables to Hold An Entire Row Declaring Variables to Hold An Entire Row VarName CursorName%ROWTYPE; Releasing the Storage Area Used by an Explicit Cursor Releasing the Storage Area Used by an Explicit Cursor CLOSE CursorName;

Iterative Structures LOOP … EXIT … END LOOP LOOP … EXIT … END LOOP EXIT with an If Avoids Infinite LoopEXIT with an If Avoids Infinite Loop LOOP … EXIT WHEN … END LOOP LOOP … EXIT WHEN … END LOOP Do Not Need An If to Control EXITDo Not Need An If to Control EXIT WHILE … LOOP … END LOOP WHILE … LOOP … END LOOP Eliminates Need for EXITEliminates Need for EXIT FOR … IN … END LOOP FOR … IN … END LOOP Eliminates Need for Initialization of CounterEliminates Need for Initialization of Counter

Cursor Control With Loops Need a Way to Fetch Repetitively Need a Way to Fetch Repetitively Need a Way to Determine How Many Rows to Process With a Cursor Need a Way to Determine How Many Rows to Process With a Cursor Cursor AttributesCursor Attributes CursorName%ROWCOUNT – Number of Rows in a Result Set CursorName%ROWCOUNT – Number of Rows in a Result Set CursorName%FOUND – True if a Fetch Returns a Row CursorName%FOUND – True if a Fetch Returns a Row CursorName%NOTFOUND – True if Fetch Goes Past Last Row CursorName%NOTFOUND – True if Fetch Goes Past Last Row

Cursor For Loop Processing an Entire Result Set Common Processing an Entire Result Set Common Special Form of FOR … IN to Manage Cursors Special Form of FOR … IN to Manage Cursors No Need for Separate OPEN, FETCH and CLOSE statements No Need for Separate OPEN, FETCH and CLOSE statements Requires %ROWTYPE Variable Requires %ROWTYPE Variable