PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.

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
Using Oracle PL/SQL PL/SQL stands for Procedural Language/SQL. PL/SQL extends SQL by adding constructs found in procedural languages, resulting in a structural.
A Guide to Oracle9i1 Advanced SQL And PL/SQL Topics Chapter 9.
Oracle PL/SQL Eyad Husni Elshami. Why PL/SQL Block Structures: – PL/SQL consists of blocks of code, which can be nested within each other. Each block.
Bordoloi and Bock PROCEDURES, FUNCTIONS & TRIGGERS.
Dr. James Dullea, CSC8490 Introduction to PL/SQLSlide 1 of 36 7From Prof. Dullea CSC8490 Introduction to PL/SQL Module 01-9 Revised: June 12, 2005 Dr.
Introduction to PL/SQL. Procedural Language extension for SQL Oracle Proprietary 3GL Capabilities Integration of SQL Portable within Oracle data bases.
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.
Cursor and Exception Handling By Nidhi Bhatnagar.
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:
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.
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
Advanced SQL: Cursors & Stored Procedures
CS178 Database Management PL/SQL session 8 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman.
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.
Oracle PL/SQL. PL/SQL Originally modeled after ADA Originally modeled after ADA Created for Dept. of DefenseCreated for Dept. of Defense Allows expanded.
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.
1 ISYS Triggers. 2 Agenda Triggers Review Correlation identifiers (pseudo records) Restrictions on triggers Trigger usage Mutating tables Enabling.
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.
School of Computing and Management Sciences © Sheffield Hallam University SQL is non-procedural –designed to be relatively approachable to non- programmers.
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
1 PL\SQL Dev Templates. 2 TEMPLATE DEFINITION Whenever you create a new program unit, its initial contents are based upon a template which contains pre-defined.
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,
Objectives Database triggers and syntax
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
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 
PL/SQLPL/SQL Oracle11g: PL/SQL Programming Chapter 9 Database Triggers.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
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.
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.
Advanced SQL: Cursors & Stored Procedures Instructor: Mohamed Eltabakh 1.
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.
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.
CS422 Principles of Database Systems Oracle PL/SQL Chengyu Sun California State University, Los Angeles.
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.
Pl/SQL LANGUAGE MULITPLE CHOICE QUESTION SET-3
Creating Stored Procedures and Functions
Active Database Concepts
PL/SQL.
Database Application Development
PL/SQL Scripting in Oracle:
Oracle9i Developer: PL/SQL Programming Chapter 8 Database Triggers.
Chapter 8 Advanced SQL.
Information Management
Chapter 8 Advanced SQL Pearson Education © 2009.
Prof. Arfaoui. COM390 Chapter 9
Database Application Development
Presentation transcript:

PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference

Introduction to PL/SQL PL/SQL is the procedural extension to SQL. PL/SQL is a programming language like C, Java or Pascal, used to access the database from various environments. e.g. Forms, Reports to create triggers, procedures, functions, etc… SQL-DML can be natively embedded in PL/SQL programs. PL/SQL2

Introduction to PL/SQL PL/SQL provides high-level language features such as block structure, conditional statements, loop statements, variable types, structured data and customized error handling. PL/SQL is integrated with the database server. It does not exist as a standalone language. PL/SQL3

Basic Structure of PL/SQL The basic unit in PL/SQL is a block. All PL/SQL programs are made up of blocks, which can be nested within each other. PL/SQL4

Basic Structure of PL/SQL DECLARE /* Declarative section: variables, types, and local subprograms. */ BEGIN /* Executable section: procedural and SQL-DML statements go here. */ /* This section of the block is required. */ EXCEPTION /* Exception handling section: error handling statements go here. */ END; PL/SQL5

Basic Structure of PL/SQL Only the executable section is required. The other sections are optional. The only SQL statements allowed in a PL/SQL program are SELECT, INSERT, UPDATE, DELETE and several other data manipulation statements plus some transaction control. Data definition statements like CREATE, ALTER, or DROP are not allowed. PL/SQL6

Basic Structure of PL/SQL The executable section also contains constructs such as assignments, branches, loops, procedure calls, and triggers. PL/SQL is not case sensitive. C style comments (/*... */) may be used, and for a one line comment precede it with (--). PL/SQL7

Variables and Types Types in PL/SQL are the same as in SQL. Variables can be declared in the following ways: PL/SQL8 Declare id NUMBER; name VARCHAR(20); 1.

Variables and Types PL/SQL9 Declare id emp.empno%TYPE; name emp.ename%TYPE; /* TableName.ColumnName%TYPE */ 2. Declare depttuple dept%ROWTYPE; /* depttuple will be a record that contains fields that represent the columns in table dept. */ /* depttuple(deptno,dname,location) */ 3.

Variables and Types A variable can be initialized: A variable can be constrained to not null: PL/SQL10 Declare a NUMBER :=3; Declare a NUMBER NOT NULL :=3; Declare a NUMBER NOT NULL DEFAULT 3; or

Select Statement Select statement has a different form: Select should return a single tuple, if several tuples are required, use a Cursor. PL/SQL11 SELECT column INTO variables FROM table WHERE condition ;

Simple Program Using the following table declaration: PL/SQL12 CREATE TABLE T1( e NUMBER, f NUMBER ); INSERT INTO T1 VALUES ( 1, 3 ); INSERT INTO T1 VALUES ( 2, 4 ); ef T1

Simple Program PL/SQL13 DECLARE a NUMBER; b NUMBER; BEGIN SELECT e, f INTO a, b FROM T1 WHERE e>1; INSERT INTO T1 VALUES ( b, a ); END; ef T1 before ef T1 after

Control Flow in PL/SQL IF – THEN – END IF LOOP – EXIT WHEN – END LOOP FOR – END LOOP WHILE – END LOOP PL/SQL14

IF – THEN – END IF PL/SQL15 IF condition_1 THEN actions_1; [ ELSE actions_last ; ] END IF; IF condition_1 THEN actions_1; [ ELSIF condition_2 THEN actions_2 ; ] [ ELSIF condition_n THEN actions_n ; ] [ ELSE actions_last ; ] END IF; Syntax 1. 2.

IF – THEN – END IF PL/SQL16 DECLARE a NUMBER; b NUMBER; BEGIN SELECT e, f INTO a, b FROM T1 WHERE e>1; IF b=1 THEN INSERT INTO T1 VALUES ( b, a ); ELSE INSERT INTO T1 VALUES ( b+10, a+10 ); END IF; END; Example ef T1 before ef T1 after

LOOP – EXIT WHEN – END LOOP PL/SQL17 LOOP /* list of statements */ EXIT WHEN condition ; /* list of statements */ END LOOP; Syntax

LOOP – EXIT WHEN – END LOOP Insert each of the pairs (1, 1) through (100, 100) into T1. PL/SQL18 Example DECLARE i NUMBER := 1; BEGIN LOOP INSERT INTO T1 VALUES ( i, i ); i := i+1; EXIT WHEN i>100; END LOOP; END;

FOR – END LOOP PL/SQL19 FOR counter_variable IN [REVERSE] lower_bound.. upper_bound LOOP /* list of statements for FOR loop body */ END LOOP; -- counter_variable will be declared implicitly. Syntax

WHILE – END LOOP PL/SQL20 WHILE condition LOOP /* list of statements for WHILE loop body */ END LOOP; Syntax

Cursors Cursor stands for “Current set of records”. A cursor is a variable that runs through the tuples of some relation. By fetching into the cursor each tuple of the relation, we can write a program to read and process the value of each such tuple. PL/SQL21

Cursor Example For example, delete every tuple whose first component is less than the second, and insert the reverse tuple into T1. PL/SQL22 DECLARE /* Output variables to hold the result of the query */ a T1.e%TYPE; b T1.f%TYPE; /* Cursor declaration */ CURSOR T1Cursor IS SELECT e, f FROM T1 WHERE e < f FOR UPDATE; ef T1

Cursor Example PL/SQL23 BEGIN OPEN T1Cursor; LOOP /* Retrieve each row of the result of the above query into PL/SQL variables */ FETCH T1Cursor INTO a, b; /* If there are no more rows to fetch, exit the loop */ EXIT WHEN T1Cursor%NOTFOUND; /* Delete the current tuple */ DELETE FROM T1 WHERE CURRENT OF T1Cursor; /* Insert the reverse tuple */ INSERT INTO T1 VALUES ( b, a ); END LOOP; CLOSE T1Cursor; /* Free cursor used by the query */ END; ef T1 before ef T1 after

Procedures Syntax PL/SQL24 CREATE [OR REPLACE] PROCEDURE procedure_name (parameters) IS /* No declare keyword */ local_var_declarations BEGIN /* list of statements for procedure body */ END procedure_name ; Parameters: variable_name mode data_type Modes: IN, OUT or INOUT. Types should be unconstrained, i.e. char and varchar should be used instead of char(10) and varchar(20).

Procedure Example Example: This creates the procedure, to execute it: PL/SQL25 CREATE PROCEDURE addtuple1( i IN NUMBER, j IN NUMBER ) IS BEGIN INSERT INTO T1 VALUES ( i, j ); END addtuple1; BEGIN addtuple1( 99,100 ); END;

Procedure Example Example: This creates the procedure, to execute it: PL/SQL26 CREATE PROCEDURE addtuple3( a IN NUMBER, b OUT NUMBER ) IS BEGIN b := 4; INSERT INTO T1 VALUES ( a, b ); END addtuple3; DECLARE v NUMBER; BEGIN addtuple3 (10, v ); END;

Functions Syntax PL/SQL27 CREATE [OR REPLACE] FUNCTION function_name ( parameters ) RETURN return_type IS /* No declare keyword */ Local_var_declarations BEGIN /* list of statements for procedure body */ Return return_variable; END function_name ;

Procedures & Functions PL/SQL28 To find out what procedures and functions you have created, use the following SQL query: Select object_type, object_name From user_objects Where object_type = 'PROCEDURE' or object_type = 'FUNCTION'; To drop a stored procedure/function: Drop procedure procedure_name ; Drop function function_name ;

Error Handling Two types of exceptions: Predefined exceptions. User-Defined exceptions. Predefined exceptions: INVALID_CURSOR, NO_DATA_FOUND, INVALID_NUMBER, ZERO_DIVIDE,TOO_MANY_ROWS, ROWTYPE_MISMATCH, etc. Exceptions must be: Declared in the declarative section of the block, Raised in the executable section, and Handled in the exception section. PL/SQL29

User Defined Exceptions User-defined exceptions are declared in the declarative section. PL/SQL30 DECLARE exception_name EXCEPTION; -- exceptions are declared here BEGIN executable_statements -- exceptions are raised here [ EXCEPTION exception_handling ] -- exceptions are handled here END;

User Defined Exceptions PL/SQL31 DECLARE e_toomany EXCEPTION; -- exception are declared here BEGIN IF num_students > 100 THEN RAISE e_toomany; -- exception is raised here -- Any code here is not executed, if the condition is true EXCEPTION WHEN e_toomany THEN -- Control passes to the exception handler Code here will be executed END;

Exceptions When an exception is raised, control immediately passes to the exception section of the block. Once control passes to the exception handler, there is no way to return to the executable section of the block. Predefined exceptions are automatically raised when the associated error occurs. PL/SQL32

Handling Exceptions PL/SQL33 …. EXCEPTION WHEN exception_name1 THEN Statements1; -- do something here WHEN exception_name2 THEN Statements2; WHEN OTHERS THEN Statements3; END;

Handling Exceptions A single handler can also be executed for more than one exception: PL/SQL34 …. EXCEPTION WHEN NO_DATA_FOUND OR TOO_MANY_ROWS THEN INSERT INTO log_table (info) VALUES ( 'A select error occurred.‘ ); END;

Triggers A trigger defines an action the database should take when some database-related event occurs (events such as inserts, updates, deletes). Triggers are similar to procedures, in that they are named PL/SQL blocks. Differences between Procedures and Triggers: A procedure is executed explicitly from another block via a procedure call with passing arguments, while a trigger is executed (or fired) implicitly whenever the triggering event happens (DML: INSERT, UPDATE, or DELETE), and a trigger doesn't accept arguments. PL/SQL35

Basic Trigger Syntax PL/SQL36 CREATE [OR REPLACE] TRIGGER trigger_name { BEFORE | AFTER | INSTEAD OF } { INSERT [OR] | DELETE [OR] | UPDATE } [ OF column_name ] ON table_name [ REFERENCING [ NEW AS new_row_name ] [ OLD AS old_row_name ] ] [ FOR EACH ROW [ WHEN ( trigger_condition ) ] ] BEGIN /* list of statements for trigger body */ END trigger_name ;

Basic Trigger Syntax You may specify up to three triggering events using the keyword OR. Furthermore, UPDATE can be optionally followed by the keyword OF and a list of attribute(s) in. If present, the OF clause defines the event to be only an update of the attribute(s) listed after OF. For example: If FOR EACH ROW option is specified, the trigger is row-level; otherwise, the trigger is statement-level. PL/SQL37... INSERT ON R INSERT OR DELETE OR UPDATE ON R... UPDATE OF A, B OR INSERT ON R...

Basic Trigger Syntax Only for row-level triggers: The special variables NEW and OLD are available to refer to new and old tuples respectively. Note: In the trigger body, NEW and OLD must be preceded by a colon (":"), but in the WHEN clause, they do not have a preceding colon! The REFERENCING clause can be used to assign aliases to the variables NEW and OLD. A trigger restriction can be specified in the WHEN clause, enclosed by parentheses. The trigger restriction is a SQL condition that must be satisfied in order for Oracle to fire the trigger. This condition cannot contain subqueries. Without the WHEN clause, the trigger is fired for each row. PL/SQL38

Trigger Example We create a trigger that may insert a tuple into T5 when a tuple is inserted into T4. Specifically, the trigger checks whether the new tuple has a first component 10 or less, and if so inserts the reverse tuple into T5: PL/SQL39 CREATE TABLE T4 ( a INTEGER, b CHAR(10) ); CREATE TABLE T5 ( c CHAR(10), d INTEGER ); CREATE TRIGGER trig1 AFTER INSERT ON T4 REFERENCING NEW AS newRow FOR EACH ROW WHEN ( newRow.a <= 10 ) BEGIN INSERT INTO T5 VALUES ( :newRow.b, :newRow.a ); END trig1;