Chapter 8 Advanced SQL Pearson Education © 2009.

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.
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.
INTRODUCTION TO ORACLE Lynnwood Brown System Managers LLC Introduction to PL/SQL – Lecture 6.
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.
Chapter 4B: More Advanced PL/SQL Programming
A Guide to Oracle9i1 Advanced SQL And PL/SQL Topics Chapter 9.
PL/SQL Agenda: Basic PL/SQL block structure
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.
Programming in Oracle with PL/SQL
Advanced SQL: Stored Procedures Instructor: Mohamed Eltabakh 1.
Bordoloi and Bock PROCEDURES, FUNCTIONS & TRIGGERS.
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.
Distributed Database Applications COSC 5050 Week Three.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
DAVID M. KROENKE’S DATABASE PROCESSING, 10th Edition © 2006 Pearson Prentice Hall 7-1 David M. Kroenke’s Chapter Seven: SQL for Database Construction and.
Stored Procedures Functions Packages
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.
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.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Cursors These slides are licensed under.
1. 1. Which type of argument passes a value from a procedure to the calling program? A. VARCHAR2 B. BOOLEAN C. OUT D. IN 2.
PL/SQL Cursors Session - II. Attributes Attributes %TYPE %ROWTYPE % Found % NotFound % RowCount % IsOPen %TYPE %ROWTYPE % Found % NotFound % RowCount.
Advanced SQL: Cursors & Stored Procedures
CS178 Database Management PL/SQL session 8 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman.
BIS Database Systems School of Management, Business Information Systems, Assumption University A.Thanop Somprasong Chapter # 8 Advanced SQL.
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.
Database Management COP4540, SCS, FIU Oracle PL/SQL (Ch 10.5)
Commercial RDBMSs Access and Oracle. Access DBMS Architchecture  Can be used as a standalone system on a single PC: -JET Engine -Microsoft Data Engine.
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,
Chapter 9: Advanced SQL and PL/SQL Guide to Oracle 10g.
ITEC 224 Database Programming PL/SQL Lab Cursors.
implicit and an explicit cursor
Learningcomputer.com SQL Server 2008 –Views, Functions and Stored Procedures.
Copyright © 2013 Curt Hill Triggers The Generation of Indirect Actions.
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.
PL/SQL programming Procedures and Cursors Lecture 1 [Part 2]
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.
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.
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.
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 Stored Procedures and Triggers Chengyu Sun California State University, Los Angeles.
1 Copyright © 2004, Oracle. All rights reserved. PL/SQL Programming Concepts: Review.
Chapter Seven: SQL for Database Construction and Application Processing.
Difference between Oracle PL/SQL and MySQL
PL/SQL.
Views, Stored Procedures, Functions, and Triggers
UNIT - V STORED PROCEDURE.
Database Application Development
Chapter 8 Advanced SQL Pearson Education © 2014.
PL/SQL Scripting in Oracle:
Database Processing: David M. Kroenke’s Chapter Seven:
Chapter 7 Using SQL in Applications
PRACTICE OVERVIEW PL/SQL Part - 1.
Chapter 8 Advanced SQL.
Information Management
Stored Procedure Language
Database Application Development
Presentation transcript:

Chapter 8 Advanced SQL Pearson Education © 2009

Chapter 8 - Objectives How to use the SQL programming language How to use SQL cursors How to create stored procedures How to create triggers How to use triggers to enforce integrity constraints Pearson Education © 2009

Chapter 8 – Objectives (continued) The advantages and disadvantages of triggers How to use recursive queries

The SQL Programming Language Impedance mismatch Mixing different programming paradigms SQL is a declarative language High-level language such as C is a procedural language SQL and 3GLs use different models to represent data

The SQL Programming Language (continued) SQL/PSM (Persistent Stored Modules) PL/SQL (Procedural Language/SQL) Oracle’s procedural extension to SQL Two versions

Declarations Variables and constant variables must be declared before they can be referenced Possible to declare a variable as NOT NULL %TYPE and %ROWTYPE

Declarations (continued)

Examples vRent NUMBER(6, 2) NOT NULL := 600; vStaffNo Staff.staffNo%TYPE;

Assignments Variables can be assigned in three ways: Using the normal assignment statement (:=) SET SQL SELECT or FETCH statement

Examples vX NUMBER; …. vStaffNo := ‘SG14’; vRent := 500; SELECT COUNT(*) INTO vX FROM PropertyForRent WHERE staffNo = vStaffNo; SET vStaffNo = ‘SG14’;

Control Statements Conditional IF statement Conditional CASE statement Iteration statement (LOOP) Iteration statement (WHILE and REPEAT) Iteration statement (FOR)

IF Statement IF ( vPosition = ‘Manager’) THEN vSalary := vSalary * 1.05; ELSIF (…) THEN //optional … ELSE //optional vSalary := vSalary * 1.08; END IF;

CASE Statement CASE lowercase(input) WHEN ‘a’ THEN x := 1; WHEN ‘b’ THEN x := 2; y := 3; WHEN ‘default’ THEN x := 3; END CASE;

LOOP Statement x := 1; myLoop: LOOP x := x+1; IF (x > 3) THEN EXIT myLoop; END IF; END LOOP myLoop; …

WHILE/REPEAT Statement myLoop: x := 1; WHILE (x < 4) DO x := x+1; END WHILE myLoop; REPEAT UNTIL (x>3) END REPEAT myLoop;

FOR Statement SELECT COUNT(*) INTO numberOfStaff FROM …. myLoop: FOR iStaff IN 1..numberOfStaff LOOP …. END LOOP myLoop;

Exceptions in PL/SQL Exception Identifier in PL/SQL Raised during the execution of a block Terminates block’s main body of actions Exception handlers Separate routines that handle raised exceptions User-defined exception Defined in the declarative part of a PL/SQL block

Example of Exception Handling in PL/SQL

Condition Handling Define a handler by Specifying its type Exception and completion conditions it can resolve Action it takes to do so Handler is activated When it is the most appropriate handler for the condition that has been raised by the SQL statement

Cursors in PL/SQL Cursor Allows the rows of a query result to be accessed one at a time Must be declared and opened before use Must be closed to deactivate it after it is no longer required Updating rows through a cursor

Using Cursors in PL/SQL to Process a Multirow Query

Cursor Flags %FOUND: true if the most recent fetch returns a row %NOTFOUND: true if the most recent fetch returns no row %ISOPEN: true if cursor is open %ROWCOUNT: total number of rows returned so far

Cursor Parameter A cursor may be reused with parameter(s): CURSOR propteryCursor(vStaffNo VARCHAR(4) ) IS SELECT propertyNo, street, city, postcode FROM PropertyForRent WHERE staffNo = vStaffNo ORDER BY propertyNo; Later the cursor can be opened as: OPEN propertyCursor(‘SG14’); … OPEN propertyCursor(‘SA9’);

Updating Rows through a Cursor A row may change after it has been fetched Example: CURSOR propterCursor IS SELECT propertyNo, street, city, postcode FROM PropertyForRent WHERE staffNo = ‘SG14’ ORDER BY propertyNo --Lock the PropertyForRent table immediately FOR UPDATE NOWAIT; Now in the loop: UPDATE PropertyForRent SET staffNo = ‘SG37’ WHERE CURRENT OF propertyCursor; … COMMIT;

Subprograms, Stored Procedures, Functions, and Packages Named PL/SQL blocks that can take parameters and be invoked Types Stored procedures: No return value Functions: Always returns a single value Parameters IN: for input only. Default. OUT: for output value only IN OUT: for input and output

Procedure (in PL/SQL) CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters] {IS|AS} Declaration section BEGIN Execution section EXCEPTION Exception section END;

Example CREATE PROCEDURE Get_emp_names (Dept_num IN NUMBER) IS Emp_name VARCHAR(10); CURSOR c1 (DepNo NUMBER) IS SELECT Ename FROM Emp_tab WHERE deptNo = DepNo; -- deptNo is an attribute BEGIN OPEN c1(Dept_num); LOOP FETCH c1 INTO Emp_name; EXIT WHEN c1%NOTFOUND; DBMS_OUTPUT.PUT_LINE(Emp_name); END LOOP; CLOSE c1; END;

Executing In standalone statement: EXECUTE procedure(parameter list); Called from another PL/SQL block: … procedure(parameter list);

Deleting DROP PROCEDURE procedure-name;

Function CREATE [OR REPLACE] FUNCTION function_name [ (parameter [,parameter]) ] RETURN return_datatype IS | AS [declaration_section] BEGIN executable_section [EXCEPTION exception_section] END [function_name];

Function Example CREATE [OR REPLACE] FUNCTION FindCourse ( name_in IN VARCHAR2 ) RETURN NUMBER IS cnumber NUMBER; CURSOR c1 IS SELECT course_number FROM courses_tbl WHERE course_name = name_in; BEGIN open c1; fetch c1 into cnumber; … close c1; RETURN cnumber; END;

Example cont’d SELECT course_name, FindCourse(course_name) AS course_id FROM courses WHERE subject = 'Mathematics';

Executing Similar to stored procedures Pass the required parameters along with function name; If function returns a value, you can store returned value Program control is transferred to the called function. A called function performs defined task and when its return statement is executed or when it last end statement is reached, it returns program control back to the main program.

MS SQL Server Stored Procedure Example To create: CREATE PROCEDURE getAddress (@City VARCHAR(30)) AS BEGIN SELECT * FROM Staff WHERE City = @City; END; GO To Execute: EXEC getAddress @City = ‘Houston’;

MS SQL Server Function Example To create: CREATE FUNCTION getSite ( @site_id INT ) RETURNS VARCHAR(50) AS BEGIN DECLARE @site_name VARCHAR(50); IF @site_id < 10 SET @site_name = ‘UHD.edu'; ELSE SET @site_name = ‘Houston.gov'; RETURN @site_name; END; To execute: SELECT dbo.getSite(8);

Triggers Trigger Defines an action that the database should take when some event occurs in the application Format of a trigger Types TRIGGER Privilege Advantages and disadvantages of triggers

Trigger Format

A BEFORE Trigger

An After Trigger CREATE TRIGGER StaffAfterInsert AFTER INSERT ON Staff REFERENCEING NEW AS newrow FOR EACH ROW BEGIN INSERT INTO StaffAudit VALUES (:newrow.staffNo, :newrow.fName, :newrow.LName, :newrow.position, :newrow.sex, ….); END;

INSTEAD OF Trigger Views are not updateable if there are more than two base tables INSTEAD OF Triggers are used to update views

Trigger Privilege Must be the owner of the table Or have been granted the TRIGGER privilege on the table

Trigger Advantages and Disadvantages Reduce redundancy Simply modifications Increase security Improve integrity Improve processing power … Performance overhead Cascading effects