Advanced SQL: Cursors & Stored Procedures Instructor: Mohamed Eltabakh 1.

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.
Oracle PL/SQL IV Exceptions Packages.
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.
SQL*PLUS, PLSQL and SQLLDR Ali Obaidi. SQL Advantages High level – Builds on relational algebra and calculus – Powerful operations – Enables automatic.
Murali Mani Persistent Stored Modules (Stored Procedures) : PSM.
Lecture-5 Though SQL is the natural language of the DBA, it suffers from various inherent disadvantages, when used as a conventional programming language.
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.
Programming in Oracle with PL/SQL
A Guide to SQL, Seventh Edition. Objectives Embed SQL commands in PL/SQL programs Retrieve single rows using embedded SQL Update a table using embedded.
Advanced SQL: Stored Procedures Instructor: Mohamed Eltabakh 1.
Bordoloi and Bock PROCEDURES, FUNCTIONS & TRIGGERS.
PL/SQL Introduction Database 1. Practice. Sample Database The schema of the sample database is the following: Drinkers (name, occupation, birthday, salary)
Cursors in Pl/SQL Database 1. Practice. Sample Database The schema of the sample database is the following: Drinkers (name, occupation, birthday, salary)
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.
Advanced Databases Advanced PL/SQL Programming: Procedure, Function and Package.
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.
Distributed Database Applications COSC 5050 Week Three.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
Cursor and Exception Handling By Nidhi Bhatnagar.
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.
INTRODUCTION TO PL/SQL. Class Agenda Introduction Introduction to PL/SQL Declaring PL/SQL Variable Creating the Executable Section Interacting with the.
1 Copyright © 2004, Oracle. All rights reserved. Introduction to PL/SQL.
Stored procedures1 Stored procedures and functions Procedures and functions stored in the database.
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
Advanced SQL Instructor: Mohamed Eltabakh 1 Part II.
Stored Procedures Week 9. Test Details Stored Procedures SQL can call code written in iSeries High Level Languages –Called stored procedures SQL has.
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.
PL/SQL Oracle's Database Programming Language. Remember: Set serveroutput on With serveroutput off (default) executing procedure: With serveroutput on:
PL/SQL Procedural Language / Structured Query Language.
1 Copyright © 2004, Oracle. All rights reserved. Introduction to PL/SQL.
CIS4368: Advanced DatabaseSlide # 1 PL/SQL Dr. Peeter KirsSpring, 2003 PL/SQL.
Database Application Development using PL/SQL Programming.
Database Management COP4540, SCS, FIU Oracle PL/SQL (Ch 10.5)
Advanced SQL: Triggers & Assertions
Chapter 9: Advanced SQL and PL/SQL Guide to Oracle 10g.
CREATING STORED PROCEDURES AND FUNCTIONS. Objectives After completing this lecture, you should be able to do the following: Differentiate between anonymous.
Introduction to Explicit Cursors. 2 home back first prev next last What Will I Learn? Distinguish between an implicit and an explicit cursor Describe.
A Guide to SQL, Eighth Edition Chapter Eight SQL Functions and Procedures.
implicit and an explicit cursor
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.
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.
1 Introduction to Database Systems, CS420 SQL Persistent Stored Modules (PSM) – Stored Procedure.
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. Advanced SQL Functions Procedural Constructs Triggers.
1 Copyright © 2004, Oracle. All rights reserved. PL/SQL Programming Concepts: Review.
A Guide to SQL, Seventh Edition
Creating Stored Procedures and Functions
Difference between Oracle PL/SQL and MySQL
PL/SQL.
UNIT - V STORED PROCEDURE.
Database Application Development
SQL PL/SQL Presented by: Dr. Samir Tartir
Error Handling Summary of the next few pages: Error Handling Cursors.
PL/SQL Package Week 8.
Chapter 2 Handling Data in PL/SQL Blocks Oracle9i Developer:
Advanced SQL: Views & Triggers
Instructor: Mohamed Eltabakh
Instructor: Mohamed Eltabakh
Procedures Organized by Farrokh Alemi, Ph.D. Narrated by Yara Alemi
PL/SQL Declaring Variables.
Chapter 8 Advanced SQL Pearson Education © 2009.
COP 2700 – Data Structures (SQL)
Database Application Development
Presentation transcript:

Advanced SQL: Cursors & Stored Procedures Instructor: Mohamed Eltabakh 1

Today’s Roadmap Views Triggers Assertions Cursors Stored Procedures 2

Using Select Inside Triggers Create Trigger EmpDate Before Insert On Employee For Each Row Declare temp date; Begin Select sysdate into temp from dual; IF (:new.hireDate is null) Then :new.hireDate := temp; End IF; End; / - Execute Select inside trigger - Store the result in temp variables Create Trigger EmpDate Before Insert On Employee For Each Row Declare tempAge number; tempName varchar2(100); Begin Select age, name into tempAge, tempName from R where ID = 5; …. End; / - Select two columns into two variables Works fine if the Select returns one tuple… 3

Cursors: Introduction Select statement may return many records Select empID, name, salary From Employee Where salary > 120,000; Get 0 or more records What if inside a trigger: Want to execute a select statement Get one record at a time Do something with each record This’s what a cursor does for you… 4

What is a Cursor A mechanism to navigate tuple-by-tuple over a relation Typically used inside triggers, stored procedures, or stored functions Main Idea When we execute a query, a relation is returned It is stored in private work area for the query Cursor is a pointer to this area Move the cursor to navigate over the tuples 5

Creating a Cursor Cursor IS ; Cursor HighSalEmp IS Select empID, name, salary From Employee Where salary > 120,000; Cursor name Any query can go here 6

Cursor Operations Create cursor Open cursor Execute the query and put the pointer at the first tuple Fetch next tuple Pointer moves automatically when a tuple is fetched Close cursor Cursor HighSalEmp IS Select empID, name, salary From Employee Where salary > 120,000; Open HighSalEmp; Fetch HighSalEmp into ; Close HighSalEmp; 7

Example 1 Have two tables: Customer & Product When insert a new customer Put in Marketing table, the customer ID along with the products labeled ‘OnSale’ Create Trigger NewCust After Insert On Customer For Each Row Declare pid number; cursor C1 is Select product_id From Product Where label = 'OnSale'; Begin open C1; Loop Fetch C1 Into pid; IF (C1%Found) Then Insert into Marketing(Cust_id, Product_id) values (:new.Id, pid); END IF; Exit When C1%NotFound; END Loop; close C1; End; / Define the cursor in ‘Declare’ section Open the cursor Loop over each record at a time If the fetch returned a record Customer ID Close the cursor 8

Example 2: Another way Use of the FOR loop with cursors Create Trigger NewCust After Insert On Customer For Each Row Declare cursor C1 is Select product_id From Product Where label = 'OnSale'; Begin For rec In C1 Loop Insert into Marketing(Cust_id, Product_id) values (:new.Id, rec.product_id); End Loop; End; / Automatically opens the cursor and fetches a record in each iteration Automatically closes the cursor That is how to read the rec variable 9

Cursor Attributes These are attributes maintained by the system Assume C1 is the cursor name Attributes include: C1%ROWCOUNT: The number of tuples in C1 C1%FOUND: TRUE if the last fetch was successful C1%NOTFOUND: TRUE if the last fetch was not successful C1%ISOPEN: TRUE if C1 is open 10

Parameterized Cursor Cursors can take parameters while opening them Very powerful to customize their execution each time Create Trigger NewCust After Insert On Customer For Each Row Declare cursor C1 (budget number) is Select product_id From Product p Where p.label = 'OnSale' and p.price < budget; Begin For rec In C1(:new.budget) Loop Insert into Marketing(Cust_id, Product_id) values (:new.Id, rec.product_id); End Loop; End; / Example: Like the previous example, but select products with price < customer’s budget Define the cursor with a parameter Pass the value at open time 11

Summary of Cursors Efficient mechanism to iterate over a relation tuple-by- tuple Main operations Open, fetch, close Usually used inside loops Cursors can be parameterized What they return depends on the passed parameters 12

Today’s Roadmap Views Triggers Assertions Cursors Stored Procedures 13

Stored Procedures & Functions Views Way to register queries inside DBMS Stored Procedures & Functions Way to register code inside DBMS 14

Stored Procedures & Functions What is stored procedure? Piece of code stored inside the DBMS SQL allows you to define procedures and functions and store them inside DBMS Advantages Reusability: do not need to write the code again and again Programming language-like environment Assignment, Loop, For, IF statements Call it whenever needed From select statement, another procedure, or another function 15

Stored Procedures in Oracle Stored procedures in Oracle follow a language called PL/SQL PL/SQL: Procedural Language SQL Same language used inside DB triggers 16

Creating A Stored Procedure CREATE [OR REPLACE] PROCEDURE ( ) [IS| AS] Begin ; End; / A parameter in the paramList is specified as: Mode: IN  input parameter (default) OUT  output parameter INOUT  input and output parameter If exists, then drop it and create it again ‘IS’ or ‘AS’ both are valid 17

General Structure CREATE [OR REPLACE] PROCEDURE procedure_name [ (parameter [,parameter]) ] [IS | AS] [declaration_section] BEGIN executable_section [EXCEPTION exception_section] END [procedure_name]; Optional section for exception handling 18

Example I By default, it is IN Define a variable Execute the command and create the procedure In PL/SQL a ‘;’ ends a line without execution You can use the procedure name before the parameter name 19

Declaration section Define a cursor that references the input parameter Example II When anything goes wrong, it will come to Exception section 20

Calling a Stored Procedure SQL> exec [( )]; SQL > exec remove_emp (10); 21

Printing From Stored Procedures Taking three parameters Printing lines to output screen 22 For the output to appear on screen. Make sure to run: Sql > set serveroutput on; For the output to appear on screen. Make sure to run: Sql > set serveroutput on;

Features in Stored Procedures Create Procedure profiler_control(start_stop IN VARCHAR2, run_comm IN VARCHAR2, ret OUT number) AS ret_code INTEGER; BEGIN ret_code := 10; IF start_stop NOT IN ('START','STOP') THEN ret:= 0; ELSIF start_stop = 'START' THEN ret:= 1; ELSE ret:= ret_code; END IF; END profiler_control; / IN parameters OUT parameters Variable declaration Variable assignment IF statement 23

More Features: LOOP Statement CREATE PROCEDURE testProcedure (name varchar2) AS credit_rating NUMBER := 0; BEGIN LOOP credit_rating := credit_rating + 1; IF credit_rating > 3 THEN EXIT; END IF; END LOOP; -- control resumes here IF name > ‘abc’ THEN RETURN; END IF; DBMS_OUTPUT.PUT_LINE ('Credit rating: ' || TO_CHAR(credit_rating)); END; / Return means  exit the procedure The Loop statement 24

More Features: CURSOR & FOR Statement Create Procedure OpeningBal (p_type IN string) AS cursor C1 Is Select productId, name, price From products where type = p_type; Begin For rec in C1 Loop Insert into Temp values (rec.productId, rec.name, rec.price); End Loop; End; / 25

Return Value Stored procedures can set output variables Stored procedures do not return values Stored functions differ from procedure in that they return values 26

Stored Functions Similar to stored procedures except that they return value CREATE [OR REPLACE] FUNCTION RETURN [( )] AS ; The function return a number Select into a variable Return to the called 27

Stored Functions All features in stored procedures are valid in in stored functions Functions have an extra ‘Return’ statement 28

Using Stored Procedures or Functions Stored Procedures Called from other procedures, functions, triggers, or standalone Stored Functions In addition to above, can be used inside SELECT statement In WHERE, HAVING, or projection list 29

Example I CREATE FUNCTION MaxNum() RETURN number AS num1 number; BEGIN SELECT MAX (sNumber) INTO num1 FROM Student; RETURN num1; END; / SQL> Select * from Student where sNumber = MaxNum(); Calling the function in the Where clause (function will be executed once) 30

Example II CREATE FUNCTION MaxNum(lastName_in varchar2) RETURN number AS num1 number; BEGIN SELECT MAX (sNumber) INTO num1 FROM Student Where lastName = lastName_in; RETURN num1; END; / SQL> Select * from Student S where S.sNumber = MaxNum(S.lastName); Calling the function in the Where clause (function will execute with each record in Student) Adding a parameter 31

Example III CREATE FUNCTION MaxNum(lastName_in varchar2) RETURN number AS num1 number; BEGIN SELECT MAX (sNumber) INTO num1 FROM Student Where lastName = lastName_in; RETURN num1; END; / SQL> Select MaxNum(S.lastName) from Student S; Calling the function in the projection list 32

Summary of Stored Procedures/Functions Code modules that are stored inside the DBMS Used and called repeatedly Powerful programing language style Can be called from other procedures, functions, triggers, or from select statement (only functions) 33

End of Advanced SQL Views Triggers Assertions Cursors Stored Procedures/Functions 34