Advanced SQL: Cursors & Stored Procedures

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.
SQL*PLUS, PLSQL and SQLLDR Ali Obaidi. SQL Advantages High level – Builds on relational algebra and calculus – Powerful operations – Enables automatic.
Stored Procedure Language Stored Procedure Overview Stored Procedure is a function in a shared library accessible to the database server can also write.
Murali Mani Persistent Stored Modules (Stored Procedures) : PSM.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13 Introduction to SQL Programming Techniques.
Chapter 4B: More Advanced PL/SQL Programming
Murali Mani SQL with other Programming Languages.
SPRING 2004CENG 3521 SQL: Constraints, Triggers, Embedded SQL Chapters: 5, 6.
EmbeddedSQL: 1 Impedance Mismatch Problem Problem : How to connect SQL statements with conventional programming languages Different models of language.
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.
Introduction to PL/SQL Lecture 0 – Self Study Akhtar Ali.
Advanced SQL: Stored Procedures Instructor: Mohamed Eltabakh 1.
Cursors in Pl/SQL Database 1. Practice. Sample Database The schema of the sample database is the following: Drinkers (name, occupation, birthday, salary)
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.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
Announcements Read JDBC Project Step 5, due Monday.
Python MySQL Database Access
Chapter 7 Advanced SQL Database Systems: Design, Implementation, and Management, Sixth Edition, Rob and Coronel.
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 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 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.
ICS 321 Fall 2010 SQL in a Server Environment (i) Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa 11/1/20101Lipyeow.
PL/SQL Procedural Language / Structured Query Language.
8 1 Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Database Management COP4540, SCS, FIU Oracle PL/SQL (Ch 10.5)
Advanced SQL: Triggers & Assertions
1 CS 430 Database Theory Winter 2005 Lecture 14: Additional SQL Topics.
Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Database Application Development Chapter 6 Sections –
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Implementing The Middle Tier These slides.
ITEC 224 Database Programming PL/SQL Lab Cursors.
DATABASE CONNECTIVITY TO MYSQL. Introduction =>A real life application needs to manipulate data stored in a Database. =>A database is a collection of.
Dr Gordon Russell, Napier University Unit Embedde SQL - V2.0 1 Embedded SQL Unit 5.1.
Chapter 16 Cursors and Exceptions. Chapter Objectives  Determine when an explicit cursor is required  Declare, open, and close an explicit cursor 
Chapter 4 An Introduction to SQL. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.4-2 Topics in this Chapter SQL: History and Overview The.
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.
1 Database Application Development Chapter 6 Sections –
implicit and an explicit cursor
SCU Fall 2002JoAnne Holliday10–1 Schedule Today u Triggers, Procedures, PL/SQL. u Read Sections , 8.1, 8.5. Next u Transaction concepts, security.
Introduction to JDBC Instructor: Mohamed Eltabakh 1.
Program with PL/SQL Lesson 3. Interacting with the Oracle Server.
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.
CS 440 Database Management Systems Stored procedures & OR mapping 1.
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.
Copyright © 2016 Ramez Elmasri and Shamkant B. Navathe.
CS422 Principles of Database Systems Stored Procedures and Triggers Chengyu Sun California State University, Los Angeles.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Module 7: Advanced SQL.
1. Advanced SQL Functions Procedural Constructs Triggers.
1st Semester, 2017 Sanghyun Park
A Guide to SQL, Seventh Edition
Difference between Oracle PL/SQL and MySQL
PL/SQL.
Chapter 5: Advanced SQL Database System concepts,6th Ed.
Database Application Development
SQL PL/SQL Presented by: Dr. Samir Tartir
Chapter 2 Handling Data in PL/SQL Blocks Oracle9i Developer:
Unit I-2.
Chapter 8 Advanced SQL Pearson Education © 2009.
Stored Procedure Language
Database Application Development
Presentation transcript:

Advanced SQL: Cursors & Stored Procedures Instructor: Mohamed Eltabakh meltabakh@cs.wpi.edu

Today’s Roadmap Views Triggers Assertions Cursors Stored Procedures

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…

What is a Cursor Creating 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 Creating Cursor Cursor HighSalEmp IS Select empID, name, salary From Employee Where salary > 120,000; Cursor <name> IS <SQL query>;

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

Cursor Operations Create cursor Open cursor Fetch next tuple Cursor HighSalEmp IS Select empID, name, salary From Employee Where salary > 120,000; 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 Open HighSalEmp; Fetch HighSalEmp into <variable>; Close HighSalEmp;

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

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

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

Parameterized Cursor Cursors can take parameters while opening them Very powerful to customize their execution each time Example: Like the previous example, but select products with price < customer’s budget 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; / Define the cursor with a parameter Pass the value at open time

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

Today’s Roadmap Views Triggers Assertions Cursors Stored Procedures

Stored Procedures What is stored procedure? Advantages 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 function

Stored Procedures in Oracle Stored procedures in Oracle follow a language called PL/SQL PL/SQL: Procedural Language SQL cs3431

Creating A Stored Procedure CREATE [OR REPLACE] PROCEDURE <procedureName> [(<paramList>)] AS <localDeclarations> <procedureBody>; A parameter in the paramList is specified as: <name> <mode> <type> <mode> is one of {IN, OUT, INOUT} Example: Create Procedure test (id in int, name out string) As Begin …. End; cs3431

Example Define a variable By default, it is IN In PL/SQL a ‘;’ ends a line without execution Execute the command and create the procedure

Calling a Stored Procedure SQL> exec <procedureName> [(<paramList>)]; SQL > exec remove_emp (10);

Printing From Stored Procedures Taking three parameters Printing them to screen

Features in Stored Procedures IN parameters 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; / OUT parameters Variable declaration Variable assignment IF statement

More Features: LOOP Statement CREATE PROCEDURE testProcedure (name varchar2(20)) AS num1 int; BEGIN num1 := 10; LOOP INSERT INTO Student VALUES (num1, name); num1 := num1 + 1; IF (num1 > 15) THEN EXIT; END IF; END LOOP; END;

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; /

Stored Functions Similar to stored procedures except that they return value CREATE [OR REPLACE] FUNCTION <functionName> RETURN <type> [(<paramList>)] AS <localDeclarations> <functionBody>;

Using Stored Procedures or Functions 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

Example CREATE FUNCTION MaxNum() RETURN int AS num1 int; BEGIN SELECT MAX (sNumber) INTO num1 FROM Student; RETURN num1; END; / SQL> Select * from Student where sNumber = MaxNum();

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)

Today’s Roadmap Triggers Assertions Cursors Stored Procedures ODBC/JDBC

ODBC/JDBC Interfaces that allow applications to connect to a database and execute queries Applications can be java, C, C++, C# programs Application makes calls to Connect with the database server Send SQL commands to the database server Get the results back in your program ODBC (Open Database Connectivity) works with C, C++, C#, and Visual Basic JDBC (Java Database Connectivity) works with Java

JDBC JDBC is a Java API for communicating with database systems supporting SQL JDBC supports a variety of features for querying and updating data, and for retrieving query results Model for communicating with the database: Open a connection Create a “statement” object Execute queries using the Statement object to send queries and fetch results Exception mechanism to handle errors

JDBC: Code Example Connecting to Oracle DB DB name, port number, userId, password Holder for SQL statement

JDBC: Code Example (Cont’d)

ODBC Similar to JDBC, but has its own syntax Works with C, C++, C# languages

End of Advanced SQL Triggers Assertions Cursors Stored Procedures ODBC/JDBC To check any syntax  Google is you friend !!!

Subqueries in DML

Subquery in DML DELETE DML: Data Manipulation Language

Subquery in DML UPDATE

Subquery in DML INSERT Any order of columns Follows the order in CREATE TABLE command